62a7a8dea4d1e372b4d51b397ebf55bb3215b59c
[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 int %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %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 Mask, 
323                               uint64_t &KnownZero, uint64_t &KnownOne,
324                               unsigned Depth = 0);
325
326     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
327                                       uint64_t &UndefElts, unsigned Depth = 0);
328       
329     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
330     // PHI node as operand #0, see if we can fold the instruction into the PHI
331     // (which is only possible if all operands to the PHI are constants).
332     Instruction *FoldOpIntoPhi(Instruction &I);
333
334     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
335     // operator and they all are only used by the PHI, PHI together their
336     // inputs, and do the operation once, to the result of the PHI.
337     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
338     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
339     
340     
341     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
342                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
343     
344     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
345                               bool isSub, Instruction &I);
346     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
347                                  bool isSigned, bool Inside, Instruction &IB);
348     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
349     Instruction *MatchBSwap(BinaryOperator &I);
350
351     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
352   };
353
354   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
355 }
356
357 // getComplexity:  Assign a complexity or rank value to LLVM Values...
358 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
359 static unsigned getComplexity(Value *V) {
360   if (isa<Instruction>(V)) {
361     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
362       return 3;
363     return 4;
364   }
365   if (isa<Argument>(V)) return 3;
366   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
367 }
368
369 // isOnlyUse - Return true if this instruction will be deleted if we stop using
370 // it.
371 static bool isOnlyUse(Value *V) {
372   return V->hasOneUse() || isa<Constant>(V);
373 }
374
375 // getPromotedType - Return the specified type promoted as it would be to pass
376 // though a va_arg area...
377 static const Type *getPromotedType(const Type *Ty) {
378   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
379     if (ITy->getBitWidth() < 32)
380       return Type::Int32Ty;
381   } else if (Ty == Type::FloatTy)
382     return Type::DoubleTy;
383   return Ty;
384 }
385
386 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
387 /// expression bitcast,  return the operand value, otherwise return null.
388 static Value *getBitCastOperand(Value *V) {
389   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
390     return I->getOperand(0);
391   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
392     if (CE->getOpcode() == Instruction::BitCast)
393       return CE->getOperand(0);
394   return 0;
395 }
396
397 /// This function is a wrapper around CastInst::isEliminableCastPair. It
398 /// simply extracts arguments and returns what that function returns.
399 static Instruction::CastOps 
400 isEliminableCastPair(
401   const CastInst *CI, ///< The first cast instruction
402   unsigned opcode,       ///< The opcode of the second cast instruction
403   const Type *DstTy,     ///< The target type for the second cast instruction
404   TargetData *TD         ///< The target data for pointer size
405 ) {
406   
407   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
408   const Type *MidTy = CI->getType();                  // B from above
409
410   // Get the opcodes of the two Cast instructions
411   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
412   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
413
414   return Instruction::CastOps(
415       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
416                                      DstTy, TD->getIntPtrType()));
417 }
418
419 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
420 /// in any code being generated.  It does not require codegen if V is simple
421 /// enough or if the cast can be folded into other casts.
422 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
423                               const Type *Ty, TargetData *TD) {
424   if (V->getType() == Ty || isa<Constant>(V)) return false;
425   
426   // If this is another cast that can be eliminated, it isn't codegen either.
427   if (const CastInst *CI = dyn_cast<CastInst>(V))
428     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
429       return false;
430   return true;
431 }
432
433 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
434 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
435 /// casts that are known to not do anything...
436 ///
437 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
438                                              Value *V, const Type *DestTy,
439                                              Instruction *InsertBefore) {
440   if (V->getType() == DestTy) return V;
441   if (Constant *C = dyn_cast<Constant>(V))
442     return ConstantExpr::getCast(opcode, C, DestTy);
443   
444   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
445 }
446
447 // SimplifyCommutative - This performs a few simplifications for commutative
448 // operators:
449 //
450 //  1. Order operands such that they are listed from right (least complex) to
451 //     left (most complex).  This puts constants before unary operators before
452 //     binary operators.
453 //
454 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
455 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
456 //
457 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
458   bool Changed = false;
459   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
460     Changed = !I.swapOperands();
461
462   if (!I.isAssociative()) return Changed;
463   Instruction::BinaryOps Opcode = I.getOpcode();
464   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
465     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
466       if (isa<Constant>(I.getOperand(1))) {
467         Constant *Folded = ConstantExpr::get(I.getOpcode(),
468                                              cast<Constant>(I.getOperand(1)),
469                                              cast<Constant>(Op->getOperand(1)));
470         I.setOperand(0, Op->getOperand(0));
471         I.setOperand(1, Folded);
472         return true;
473       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
474         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
475             isOnlyUse(Op) && isOnlyUse(Op1)) {
476           Constant *C1 = cast<Constant>(Op->getOperand(1));
477           Constant *C2 = cast<Constant>(Op1->getOperand(1));
478
479           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
480           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
481           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
482                                                     Op1->getOperand(0),
483                                                     Op1->getName(), &I);
484           AddToWorkList(New);
485           I.setOperand(0, New);
486           I.setOperand(1, Folded);
487           return true;
488         }
489     }
490   return Changed;
491 }
492
493 /// SimplifyCompare - For a CmpInst this function just orders the operands
494 /// so that theyare listed from right (least complex) to left (most complex).
495 /// This puts constants before unary operators before binary operators.
496 bool InstCombiner::SimplifyCompare(CmpInst &I) {
497   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
498     return false;
499   I.swapOperands();
500   // Compare instructions are not associative so there's nothing else we can do.
501   return true;
502 }
503
504 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
505 // if the LHS is a constant zero (which is the 'negate' form).
506 //
507 static inline Value *dyn_castNegVal(Value *V) {
508   if (BinaryOperator::isNeg(V))
509     return BinaryOperator::getNegArgument(V);
510
511   // Constants can be considered to be negated values if they can be folded.
512   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
513     return ConstantExpr::getNeg(C);
514   return 0;
515 }
516
517 static inline Value *dyn_castNotVal(Value *V) {
518   if (BinaryOperator::isNot(V))
519     return BinaryOperator::getNotArgument(V);
520
521   // Constants can be considered to be not'ed values...
522   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
523     return ConstantExpr::getNot(C);
524   return 0;
525 }
526
527 // dyn_castFoldableMul - If this value is a multiply that can be folded into
528 // other computations (because it has a constant operand), return the
529 // non-constant operand of the multiply, and set CST to point to the multiplier.
530 // Otherwise, return null.
531 //
532 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
533   if (V->hasOneUse() && V->getType()->isInteger())
534     if (Instruction *I = dyn_cast<Instruction>(V)) {
535       if (I->getOpcode() == Instruction::Mul)
536         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
537           return I->getOperand(0);
538       if (I->getOpcode() == Instruction::Shl)
539         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
540           // The multiplier is really 1 << CST.
541           Constant *One = ConstantInt::get(V->getType(), 1);
542           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
543           return I->getOperand(0);
544         }
545     }
546   return 0;
547 }
548
549 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
550 /// expression, return it.
551 static User *dyn_castGetElementPtr(Value *V) {
552   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
553   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
554     if (CE->getOpcode() == Instruction::GetElementPtr)
555       return cast<User>(V);
556   return false;
557 }
558
559 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
560 static ConstantInt *AddOne(ConstantInt *C) {
561   return cast<ConstantInt>(ConstantExpr::getAdd(C,
562                                          ConstantInt::get(C->getType(), 1)));
563 }
564 static ConstantInt *SubOne(ConstantInt *C) {
565   return cast<ConstantInt>(ConstantExpr::getSub(C,
566                                          ConstantInt::get(C->getType(), 1)));
567 }
568
569 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
570 /// known to be either zero or one and return them in the KnownZero/KnownOne
571 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
572 /// processing.
573 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
574 /// we cannot optimize based on the assumption that it is zero without changing
575 /// it to be an explicit zero.  If we don't change it to zero, other code could
576 /// optimized based on the contradictory assumption that it is non-zero.
577 /// Because instcombine aggressively folds operations with undef args anyway,
578 /// this won't lose us code quality.
579 static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero, 
580                               APInt& KnownOne, unsigned Depth = 0) {
581   uint32_t BitWidth = Mask.getBitWidth();
582   assert(KnownZero.getBitWidth() == BitWidth && 
583          KnownOne.getBitWidth() == BitWidth &&
584          "Mask, KnownOne and KnownZero should have same BitWidth");
585   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
586     // We know all of the bits for a constant!
587     APInt Tmp(CI->getValue());
588     Tmp.zextOrTrunc(BitWidth);
589     KnownOne = Tmp & Mask;
590     KnownZero = ~KnownOne & Mask;
591     return;
592   }
593
594   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
595   if (Depth == 6 || Mask == 0)
596     return;  // Limit search depth.
597
598   Instruction *I = dyn_cast<Instruction>(V);
599   if (!I) return;
600
601   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
602   Mask &= APInt::getAllOnesValue(
603     cast<IntegerType>(V->getType())->getBitWidth()).zextOrTrunc(BitWidth);
604   
605   switch (I->getOpcode()) {
606   case Instruction::And:
607     // If either the LHS or the RHS are Zero, the result is zero.
608     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
609     Mask &= ~KnownZero;
610     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
611     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
612     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
613     
614     // Output known-1 bits are only known if set in both the LHS & RHS.
615     KnownOne &= KnownOne2;
616     // Output known-0 are known to be clear if zero in either the LHS | RHS.
617     KnownZero |= KnownZero2;
618     return;
619   case Instruction::Or:
620     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
621     Mask &= ~KnownOne;
622     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
623     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
624     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
625     
626     // Output known-0 bits are only known if clear in both the LHS & RHS.
627     KnownZero &= KnownZero2;
628     // Output known-1 are known to be set if set in either the LHS | RHS.
629     KnownOne |= KnownOne2;
630     return;
631   case Instruction::Xor: {
632     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
633     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
634     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
635     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
636     
637     // Output known-0 bits are known if clear or set in both the LHS & RHS.
638     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
639     // Output known-1 are known to be set if set in only one of the LHS, RHS.
640     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
641     KnownZero = KnownZeroOut;
642     return;
643   }
644   case Instruction::Select:
645     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
646     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
647     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
648     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
649
650     // Only known if known in both the LHS and RHS.
651     KnownOne &= KnownOne2;
652     KnownZero &= KnownZero2;
653     return;
654   case Instruction::FPTrunc:
655   case Instruction::FPExt:
656   case Instruction::FPToUI:
657   case Instruction::FPToSI:
658   case Instruction::SIToFP:
659   case Instruction::PtrToInt:
660   case Instruction::UIToFP:
661   case Instruction::IntToPtr:
662     return; // Can't work with floating point or pointers
663   case Instruction::Trunc: 
664     // All these have integer operands
665     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666     return;
667   case Instruction::BitCast: {
668     const Type *SrcTy = I->getOperand(0)->getType();
669     if (SrcTy->isInteger()) {
670       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
671       return;
672     }
673     break;
674   }
675   case Instruction::ZExt:  {
676     // Compute the bits in the result that are not present in the input.
677     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
678     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
679       
680     Mask &= SrcTy->getMask().zextOrTrunc(BitWidth);
681     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
683     // The top bits are known to be zero.
684     KnownZero |= NewBits;
685     return;
686   }
687   case Instruction::SExt: {
688     // Compute the bits in the result that are not present in the input.
689     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
690     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
691       
692     Mask &= SrcTy->getMask().zextOrTrunc(BitWidth);
693     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
694     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
695
696     // If the sign bit of the input is known set or clear, then we know the
697     // top bits of the result.
698     APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
699     InSignBit.zextOrTrunc(BitWidth);
700     if ((KnownZero & InSignBit) != 0) {          // Input sign bit known zero
701       KnownZero |= NewBits;
702       KnownOne &= ~NewBits;
703     } else if ((KnownOne & InSignBit) != 0) {    // Input sign bit known set
704       KnownOne |= NewBits;
705       KnownZero &= ~NewBits;
706     } else {                              // Input sign bit unknown
707       KnownZero &= ~NewBits;
708       KnownOne &= ~NewBits;
709     }
710     return;
711   }
712   case Instruction::Shl:
713     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
714     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
715       uint64_t ShiftAmt = SA->getZExtValue();
716       Mask = APIntOps::lshr(Mask, ShiftAmt);
717       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
718       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
719       KnownZero <<= ShiftAmt;
720       KnownOne  <<= ShiftAmt;
721       KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1;  // low bits known zero.
722       return;
723     }
724     break;
725   case Instruction::LShr:
726     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
727     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
728       // Compute the new bits that are at the top now.
729       uint64_t ShiftAmt = SA->getZExtValue();
730       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
731       
732       // Unsigned shift right.
733       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 = APIntOps::lshr(KnownZero, ShiftAmt);
737       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
738       KnownZero |= HighBits;  // high bits known zero.
739       return;
740     }
741     break;
742   case Instruction::AShr:
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       // Signed 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         
756       // Handle the sign bits and adjust to where it is now in the mask.
757       APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
758         
759       if ((KnownZero & SignBit) != 0) {       // New bits are known zero.
760         KnownZero |= HighBits;
761       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
762         KnownOne |= HighBits;
763       }
764       return;
765     }
766     break;
767   }
768 }
769
770 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
771 /// known to be either zero or one and return them in the KnownZero/KnownOne
772 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
773 /// processing.
774 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero, 
775                               uint64_t &KnownOne, unsigned Depth = 0) {
776   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
777   // we cannot optimize based on the assumption that it is zero without changing
778   // it to be an explicit zero.  If we don't change it to zero, other code could
779   // optimized based on the contradictory assumption that it is non-zero.
780   // Because instcombine aggressively folds operations with undef args anyway,
781   // this won't lose us code quality.
782   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
783     // We know all of the bits for a constant!
784     KnownOne = CI->getZExtValue() & Mask;
785     KnownZero = ~KnownOne & Mask;
786     return;
787   }
788
789   KnownZero = KnownOne = 0;   // Don't know anything.
790   if (Depth == 6 || Mask == 0)
791     return;  // Limit search depth.
792
793   uint64_t KnownZero2, KnownOne2;
794   Instruction *I = dyn_cast<Instruction>(V);
795   if (!I) return;
796
797   Mask &= cast<IntegerType>(V->getType())->getBitMask();
798   
799   switch (I->getOpcode()) {
800   case Instruction::And:
801     // If either the LHS or the RHS are Zero, the result is zero.
802     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
803     Mask &= ~KnownZero;
804     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
805     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
806     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
807     
808     // Output known-1 bits are only known if set in both the LHS & RHS.
809     KnownOne &= KnownOne2;
810     // Output known-0 are known to be clear if zero in either the LHS | RHS.
811     KnownZero |= KnownZero2;
812     return;
813   case Instruction::Or:
814     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
815     Mask &= ~KnownOne;
816     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
817     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
818     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
819     
820     // Output known-0 bits are only known if clear in both the LHS & RHS.
821     KnownZero &= KnownZero2;
822     // Output known-1 are known to be set if set in either the LHS | RHS.
823     KnownOne |= KnownOne2;
824     return;
825   case Instruction::Xor: {
826     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
827     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
828     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
829     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
830     
831     // Output known-0 bits are known if clear or set in both the LHS & RHS.
832     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
833     // Output known-1 are known to be set if set in only one of the LHS, RHS.
834     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
835     KnownZero = KnownZeroOut;
836     return;
837   }
838   case Instruction::Select:
839     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
840     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
841     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
842     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
843
844     // Only known if known in both the LHS and RHS.
845     KnownOne &= KnownOne2;
846     KnownZero &= KnownZero2;
847     return;
848   case Instruction::FPTrunc:
849   case Instruction::FPExt:
850   case Instruction::FPToUI:
851   case Instruction::FPToSI:
852   case Instruction::SIToFP:
853   case Instruction::PtrToInt:
854   case Instruction::UIToFP:
855   case Instruction::IntToPtr:
856     return; // Can't work with floating point or pointers
857   case Instruction::Trunc: 
858     // All these have integer operands
859     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
860     return;
861   case Instruction::BitCast: {
862     const Type *SrcTy = I->getOperand(0)->getType();
863     if (SrcTy->isInteger()) {
864       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
865       return;
866     }
867     break;
868   }
869   case Instruction::ZExt:  {
870     // Compute the bits in the result that are not present in the input.
871     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
872     uint64_t NotIn = ~SrcTy->getBitMask();
873     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
874       
875     Mask &= SrcTy->getBitMask();
876     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
878     // The top bits are known to be zero.
879     KnownZero |= NewBits;
880     return;
881   }
882   case Instruction::SExt: {
883     // Compute the bits in the result that are not present in the input.
884     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
885     uint64_t NotIn = ~SrcTy->getBitMask();
886     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
887       
888     Mask &= SrcTy->getBitMask();
889     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
890     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
891
892     // If the sign bit of the input is known set or clear, then we know the
893     // top bits of the result.
894     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
895     if (KnownZero & InSignBit) {          // Input sign bit known zero
896       KnownZero |= NewBits;
897       KnownOne &= ~NewBits;
898     } else if (KnownOne & InSignBit) {    // Input sign bit known set
899       KnownOne |= NewBits;
900       KnownZero &= ~NewBits;
901     } else {                              // Input sign bit unknown
902       KnownZero &= ~NewBits;
903       KnownOne &= ~NewBits;
904     }
905     return;
906   }
907   case Instruction::Shl:
908     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
909     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
910       uint64_t ShiftAmt = SA->getZExtValue();
911       Mask >>= ShiftAmt;
912       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
913       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
914       KnownZero <<= ShiftAmt;
915       KnownOne  <<= ShiftAmt;
916       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
917       return;
918     }
919     break;
920   case Instruction::LShr:
921     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
922     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
923       // Compute the new bits that are at the top now.
924       uint64_t ShiftAmt = SA->getZExtValue();
925       uint64_t HighBits = (1ULL << ShiftAmt)-1;
926       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
927       
928       // Unsigned shift right.
929       Mask <<= ShiftAmt;
930       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
931       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
932       KnownZero >>= ShiftAmt;
933       KnownOne  >>= ShiftAmt;
934       KnownZero |= HighBits;  // high bits known zero.
935       return;
936     }
937     break;
938   case Instruction::AShr:
939     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
940     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
941       // Compute the new bits that are at the top now.
942       uint64_t ShiftAmt = SA->getZExtValue();
943       uint64_t HighBits = (1ULL << ShiftAmt)-1;
944       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
945       
946       // Signed shift right.
947       Mask <<= ShiftAmt;
948       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
949       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
950       KnownZero >>= ShiftAmt;
951       KnownOne  >>= ShiftAmt;
952         
953       // Handle the sign bits.
954       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
955       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
956         
957       if (KnownZero & SignBit) {       // New bits are known zero.
958         KnownZero |= HighBits;
959       } else if (KnownOne & SignBit) { // New bits are known one.
960         KnownOne |= HighBits;
961       }
962       return;
963     }
964     break;
965   }
966 }
967
968 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
969 /// this predicate to simplify operations downstream.  Mask is known to be zero
970 /// for bits that V cannot have.
971 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
972   uint64_t KnownZero, KnownOne;
973   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
974   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
975   return (KnownZero & Mask) == Mask;
976 }
977
978 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
979 /// this predicate to simplify operations downstream.  Mask is known to be zero
980 /// for bits that V cannot have.
981 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
982   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
983   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
984   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
985   return (KnownZero & Mask) == Mask;
986 }
987
988 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
989 /// specified instruction is a constant integer.  If so, check to see if there
990 /// are any bits set in the constant that are not demanded.  If so, shrink the
991 /// constant and return true.
992 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
993                                    uint64_t Demanded) {
994   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
995   if (!OpC) return false;
996
997   // If there are no bits set that aren't demanded, nothing to do.
998   if ((~Demanded & OpC->getZExtValue()) == 0)
999     return false;
1000
1001   // This is producing any bits that are not needed, shrink the RHS.
1002   uint64_t Val = Demanded & OpC->getZExtValue();
1003   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
1004   return true;
1005 }
1006
1007 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1008 // set of known zero and one bits, compute the maximum and minimum values that
1009 // could have the specified known zero and known one bits, returning them in
1010 // min/max.
1011 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1012                                                    uint64_t KnownZero,
1013                                                    uint64_t KnownOne,
1014                                                    int64_t &Min, int64_t &Max) {
1015   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
1016   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1017
1018   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1019   
1020   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1021   // bit if it is unknown.
1022   Min = KnownOne;
1023   Max = KnownOne|UnknownBits;
1024   
1025   if (SignBit & UnknownBits) { // Sign bit is unknown
1026     Min |= SignBit;
1027     Max &= ~SignBit;
1028   }
1029   
1030   // Sign extend the min/max values.
1031   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1032   Min = (Min << ShAmt) >> ShAmt;
1033   Max = (Max << ShAmt) >> ShAmt;
1034 }
1035
1036 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1037 // a set of known zero and one bits, compute the maximum and minimum values that
1038 // could have the specified known zero and known one bits, returning them in
1039 // min/max.
1040 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1041                                                      uint64_t KnownZero,
1042                                                      uint64_t KnownOne,
1043                                                      uint64_t &Min,
1044                                                      uint64_t &Max) {
1045   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
1046   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1047   
1048   // The minimum value is when the unknown bits are all zeros.
1049   Min = KnownOne;
1050   // The maximum value is when the unknown bits are all ones.
1051   Max = KnownOne|UnknownBits;
1052 }
1053
1054
1055 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
1056 /// DemandedMask bits of the result of V are ever used downstream.  If we can
1057 /// use this information to simplify V, do so and return true.  Otherwise,
1058 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
1059 /// the expression (used to simplify the caller).  The KnownZero/One bits may
1060 /// only be accurate for those bits in the DemandedMask.
1061 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1062                                         uint64_t &KnownZero, uint64_t &KnownOne,
1063                                         unsigned Depth) {
1064   const IntegerType *VTy = cast<IntegerType>(V->getType());
1065   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1066     // We know all of the bits for a constant!
1067     KnownOne = CI->getZExtValue() & DemandedMask;
1068     KnownZero = ~KnownOne & DemandedMask;
1069     return false;
1070   }
1071   
1072   KnownZero = KnownOne = 0;
1073   if (!V->hasOneUse()) {    // Other users may use these bits.
1074     if (Depth != 0) {       // Not at the root.
1075       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1076       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1077       return false;
1078     }
1079     // If this is the root being simplified, allow it to have multiple uses,
1080     // just set the DemandedMask to all bits.
1081     DemandedMask = VTy->getBitMask();
1082   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1083     if (V != UndefValue::get(VTy))
1084       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1085     return false;
1086   } else if (Depth == 6) {        // Limit search depth.
1087     return false;
1088   }
1089   
1090   Instruction *I = dyn_cast<Instruction>(V);
1091   if (!I) return false;        // Only analyze instructions.
1092
1093   DemandedMask &= VTy->getBitMask();
1094   
1095   uint64_t KnownZero2 = 0, KnownOne2 = 0;
1096   switch (I->getOpcode()) {
1097   default: break;
1098   case Instruction::And:
1099     // If either the LHS or the RHS are Zero, the result is zero.
1100     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1101                              KnownZero, KnownOne, Depth+1))
1102       return true;
1103     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1104
1105     // If something is known zero on the RHS, the bits aren't demanded on the
1106     // LHS.
1107     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1108                              KnownZero2, KnownOne2, Depth+1))
1109       return true;
1110     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1111
1112     // If all of the demanded bits are known 1 on one side, return the other.
1113     // These bits cannot contribute to the result of the 'and'.
1114     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1115       return UpdateValueUsesWith(I, I->getOperand(0));
1116     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1117       return UpdateValueUsesWith(I, I->getOperand(1));
1118     
1119     // If all of the demanded bits in the inputs are known zeros, return zero.
1120     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
1121       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1122       
1123     // If the RHS is a constant, see if we can simplify it.
1124     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
1125       return UpdateValueUsesWith(I, I);
1126       
1127     // Output known-1 bits are only known if set in both the LHS & RHS.
1128     KnownOne &= KnownOne2;
1129     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1130     KnownZero |= KnownZero2;
1131     break;
1132   case Instruction::Or:
1133     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1134                              KnownZero, KnownOne, Depth+1))
1135       return true;
1136     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1137     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
1138                              KnownZero2, KnownOne2, Depth+1))
1139       return true;
1140     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1141     
1142     // If all of the demanded bits are known zero on one side, return the other.
1143     // These bits cannot contribute to the result of the 'or'.
1144     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
1145       return UpdateValueUsesWith(I, I->getOperand(0));
1146     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
1147       return UpdateValueUsesWith(I, I->getOperand(1));
1148
1149     // If all of the potentially set bits on one side are known to be set on
1150     // the other side, just use the 'other' side.
1151     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
1152         (DemandedMask & (~KnownZero)))
1153       return UpdateValueUsesWith(I, I->getOperand(0));
1154     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
1155         (DemandedMask & (~KnownZero2)))
1156       return UpdateValueUsesWith(I, I->getOperand(1));
1157         
1158     // If the RHS is a constant, see if we can simplify it.
1159     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1160       return UpdateValueUsesWith(I, I);
1161           
1162     // Output known-0 bits are only known if clear in both the LHS & RHS.
1163     KnownZero &= KnownZero2;
1164     // Output known-1 are known to be set if set in either the LHS | RHS.
1165     KnownOne |= KnownOne2;
1166     break;
1167   case Instruction::Xor: {
1168     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1169                              KnownZero, KnownOne, Depth+1))
1170       return true;
1171     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1172     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1173                              KnownZero2, KnownOne2, Depth+1))
1174       return true;
1175     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1176     
1177     // If all of the demanded bits are known zero on one side, return the other.
1178     // These bits cannot contribute to the result of the 'xor'.
1179     if ((DemandedMask & KnownZero) == DemandedMask)
1180       return UpdateValueUsesWith(I, I->getOperand(0));
1181     if ((DemandedMask & KnownZero2) == DemandedMask)
1182       return UpdateValueUsesWith(I, I->getOperand(1));
1183     
1184     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1185     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1186     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1187     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1188     
1189     // If all of the demanded bits are known to be zero on one side or the
1190     // other, turn this into an *inclusive* or.
1191     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1192     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1193       Instruction *Or =
1194         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1195                                  I->getName());
1196       InsertNewInstBefore(Or, *I);
1197       return UpdateValueUsesWith(I, Or);
1198     }
1199     
1200     // If all of the demanded bits on one side are known, and all of the set
1201     // bits on that side are also known to be set on the other side, turn this
1202     // into an AND, as we know the bits will be cleared.
1203     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1204     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1205       if ((KnownOne & KnownOne2) == KnownOne) {
1206         Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
1207         Instruction *And = 
1208           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1209         InsertNewInstBefore(And, *I);
1210         return UpdateValueUsesWith(I, And);
1211       }
1212     }
1213     
1214     // If the RHS is a constant, see if we can simplify it.
1215     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1216     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1217       return UpdateValueUsesWith(I, I);
1218     
1219     KnownZero = KnownZeroOut;
1220     KnownOne  = KnownOneOut;
1221     break;
1222   }
1223   case Instruction::Select:
1224     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1225                              KnownZero, KnownOne, Depth+1))
1226       return true;
1227     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1228                              KnownZero2, KnownOne2, Depth+1))
1229       return true;
1230     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1231     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1232     
1233     // If the operands are constants, see if we can simplify them.
1234     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1235       return UpdateValueUsesWith(I, I);
1236     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1237       return UpdateValueUsesWith(I, I);
1238     
1239     // Only known if known in both the LHS and RHS.
1240     KnownOne &= KnownOne2;
1241     KnownZero &= KnownZero2;
1242     break;
1243   case Instruction::Trunc:
1244     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1245                              KnownZero, KnownOne, Depth+1))
1246       return true;
1247     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1248     break;
1249   case Instruction::BitCast:
1250     if (!I->getOperand(0)->getType()->isInteger())
1251       return false;
1252       
1253     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1254                              KnownZero, KnownOne, Depth+1))
1255       return true;
1256     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1257     break;
1258   case Instruction::ZExt: {
1259     // Compute the bits in the result that are not present in the input.
1260     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1261     uint64_t NotIn = ~SrcTy->getBitMask();
1262     uint64_t NewBits = VTy->getBitMask() & NotIn;
1263     
1264     DemandedMask &= SrcTy->getBitMask();
1265     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1266                              KnownZero, KnownOne, Depth+1))
1267       return true;
1268     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1269     // The top bits are known to be zero.
1270     KnownZero |= NewBits;
1271     break;
1272   }
1273   case Instruction::SExt: {
1274     // Compute the bits in the result that are not present in the input.
1275     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1276     uint64_t NotIn = ~SrcTy->getBitMask();
1277     uint64_t NewBits = VTy->getBitMask() & NotIn;
1278     
1279     // Get the sign bit for the source type
1280     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1281     int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1282
1283     // If any of the sign extended bits are demanded, we know that the sign
1284     // bit is demanded.
1285     if (NewBits & DemandedMask)
1286       InputDemandedBits |= InSignBit;
1287       
1288     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1289                              KnownZero, KnownOne, Depth+1))
1290       return true;
1291     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1292       
1293     // If the sign bit of the input is known set or clear, then we know the
1294     // top bits of the result.
1295
1296     // If the input sign bit is known zero, or if the NewBits are not demanded
1297     // convert this into a zero extension.
1298     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1299       // Convert to ZExt cast
1300       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1301       return UpdateValueUsesWith(I, NewCast);
1302     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1303       KnownOne |= NewBits;
1304       KnownZero &= ~NewBits;
1305     } else {                              // Input sign bit unknown
1306       KnownZero &= ~NewBits;
1307       KnownOne &= ~NewBits;
1308     }
1309     break;
1310   }
1311   case Instruction::Add:
1312     // If there is a constant on the RHS, there are a variety of xformations
1313     // we can do.
1314     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1315       // If null, this should be simplified elsewhere.  Some of the xforms here
1316       // won't work if the RHS is zero.
1317       if (RHS->isNullValue())
1318         break;
1319       
1320       // Figure out what the input bits are.  If the top bits of the and result
1321       // are not demanded, then the add doesn't demand them from its input
1322       // either.
1323       
1324       // Shift the demanded mask up so that it's at the top of the uint64_t.
1325       unsigned BitWidth = VTy->getPrimitiveSizeInBits();
1326       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1327       
1328       // If the top bit of the output is demanded, demand everything from the
1329       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1330       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1331
1332       // Find information about known zero/one bits in the input.
1333       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1334                                KnownZero2, KnownOne2, Depth+1))
1335         return true;
1336
1337       // If the RHS of the add has bits set that can't affect the input, reduce
1338       // the constant.
1339       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1340         return UpdateValueUsesWith(I, I);
1341       
1342       // Avoid excess work.
1343       if (KnownZero2 == 0 && KnownOne2 == 0)
1344         break;
1345       
1346       // Turn it into OR if input bits are zero.
1347       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1348         Instruction *Or =
1349           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1350                                    I->getName());
1351         InsertNewInstBefore(Or, *I);
1352         return UpdateValueUsesWith(I, Or);
1353       }
1354       
1355       // We can say something about the output known-zero and known-one bits,
1356       // depending on potential carries from the input constant and the
1357       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1358       // bits set and the RHS constant is 0x01001, then we know we have a known
1359       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1360       
1361       // To compute this, we first compute the potential carry bits.  These are
1362       // the bits which may be modified.  I'm not aware of a better way to do
1363       // this scan.
1364       uint64_t RHSVal = RHS->getZExtValue();
1365       
1366       bool CarryIn = false;
1367       uint64_t CarryBits = 0;
1368       uint64_t CurBit = 1;
1369       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1370         // Record the current carry in.
1371         if (CarryIn) CarryBits |= CurBit;
1372         
1373         bool CarryOut;
1374         
1375         // This bit has a carry out unless it is "zero + zero" or
1376         // "zero + anything" with no carry in.
1377         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1378           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1379         } else if (!CarryIn &&
1380                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1381           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1382         } else {
1383           // Otherwise, we have to assume we have a carry out.
1384           CarryOut = true;
1385         }
1386         
1387         // This stage's carry out becomes the next stage's carry-in.
1388         CarryIn = CarryOut;
1389       }
1390       
1391       // Now that we know which bits have carries, compute the known-1/0 sets.
1392       
1393       // Bits are known one if they are known zero in one operand and one in the
1394       // other, and there is no input carry.
1395       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1396       
1397       // Bits are known zero if they are known zero in both operands and there
1398       // is no input carry.
1399       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1400     } else {
1401       // If the high-bits of this ADD are not demanded, then it does not demand
1402       // the high bits of its LHS or RHS.
1403       if ((DemandedMask & VTy->getSignBit()) == 0) {
1404         // Right fill the mask of bits for this ADD to demand the most
1405         // significant bit and all those below it.
1406         unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1407         uint64_t DemandedFromOps = ~0ULL >> NLZ;
1408         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1409                                  KnownZero2, KnownOne2, Depth+1))
1410           return true;
1411         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1412                                  KnownZero2, KnownOne2, Depth+1))
1413           return true;
1414       }
1415     }
1416     break;
1417   case Instruction::Sub:
1418     // If the high-bits of this SUB are not demanded, then it does not demand
1419     // the high bits of its LHS or RHS.
1420     if ((DemandedMask & VTy->getSignBit()) == 0) {
1421       // Right fill the mask of bits for this SUB to demand the most
1422       // significant bit and all those below it.
1423       unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1424       uint64_t DemandedFromOps = ~0ULL >> NLZ;
1425       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1426                                KnownZero2, KnownOne2, Depth+1))
1427         return true;
1428       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1429                                KnownZero2, KnownOne2, Depth+1))
1430         return true;
1431     }
1432     break;
1433   case Instruction::Shl:
1434     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1435       uint64_t ShiftAmt = SA->getZExtValue();
1436       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1437                                KnownZero, KnownOne, Depth+1))
1438         return true;
1439       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1440       KnownZero <<= ShiftAmt;
1441       KnownOne  <<= ShiftAmt;
1442       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1443     }
1444     break;
1445   case Instruction::LShr:
1446     // For a logical shift right
1447     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1448       unsigned ShiftAmt = SA->getZExtValue();
1449       
1450       // Compute the new bits that are at the top now.
1451       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1452       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1453       uint64_t TypeMask = VTy->getBitMask();
1454       // Unsigned shift right.
1455       if (SimplifyDemandedBits(I->getOperand(0),
1456                               (DemandedMask << ShiftAmt) & TypeMask,
1457                                KnownZero, KnownOne, Depth+1))
1458         return true;
1459       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1460       KnownZero &= TypeMask;
1461       KnownOne  &= TypeMask;
1462       KnownZero >>= ShiftAmt;
1463       KnownOne  >>= ShiftAmt;
1464       KnownZero |= HighBits;  // high bits known zero.
1465     }
1466     break;
1467   case Instruction::AShr:
1468     // If this is an arithmetic shift right and only the low-bit is set, we can
1469     // always convert this into a logical shr, even if the shift amount is
1470     // variable.  The low bit of the shift cannot be an input sign bit unless
1471     // the shift amount is >= the size of the datatype, which is undefined.
1472     if (DemandedMask == 1) {
1473       // Perform the logical shift right.
1474       Value *NewVal = BinaryOperator::createLShr(
1475                         I->getOperand(0), I->getOperand(1), I->getName());
1476       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1477       return UpdateValueUsesWith(I, NewVal);
1478     }    
1479     
1480     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1481       unsigned ShiftAmt = SA->getZExtValue();
1482       
1483       // Compute the new bits that are at the top now.
1484       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1485       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1486       uint64_t TypeMask = VTy->getBitMask();
1487       // Signed shift right.
1488       if (SimplifyDemandedBits(I->getOperand(0),
1489                                (DemandedMask << ShiftAmt) & TypeMask,
1490                                KnownZero, KnownOne, Depth+1))
1491         return true;
1492       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1493       KnownZero &= TypeMask;
1494       KnownOne  &= TypeMask;
1495       KnownZero >>= ShiftAmt;
1496       KnownOne  >>= ShiftAmt;
1497         
1498       // Handle the sign bits.
1499       uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
1500       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1501         
1502       // If the input sign bit is known to be zero, or if none of the top bits
1503       // are demanded, turn this into an unsigned shift right.
1504       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1505         // Perform the logical shift right.
1506         Value *NewVal = BinaryOperator::createLShr(
1507                           I->getOperand(0), SA, I->getName());
1508         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1509         return UpdateValueUsesWith(I, NewVal);
1510       } else if (KnownOne & SignBit) { // New bits are known one.
1511         KnownOne |= HighBits;
1512       }
1513     }
1514     break;
1515   }
1516   
1517   // If the client is only demanding bits that we know, return the known
1518   // constant.
1519   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1520     return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
1521   return false;
1522 }  
1523
1524
1525 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1526 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1527 /// actually used by the caller.  This method analyzes which elements of the
1528 /// operand are undef and returns that information in UndefElts.
1529 ///
1530 /// If the information about demanded elements can be used to simplify the
1531 /// operation, the operation is simplified, then the resultant value is
1532 /// returned.  This returns null if no change was made.
1533 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1534                                                 uint64_t &UndefElts,
1535                                                 unsigned Depth) {
1536   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1537   assert(VWidth <= 64 && "Vector too wide to analyze!");
1538   uint64_t EltMask = ~0ULL >> (64-VWidth);
1539   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1540          "Invalid DemandedElts!");
1541
1542   if (isa<UndefValue>(V)) {
1543     // If the entire vector is undefined, just return this info.
1544     UndefElts = EltMask;
1545     return 0;
1546   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1547     UndefElts = EltMask;
1548     return UndefValue::get(V->getType());
1549   }
1550   
1551   UndefElts = 0;
1552   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1553     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1554     Constant *Undef = UndefValue::get(EltTy);
1555
1556     std::vector<Constant*> Elts;
1557     for (unsigned i = 0; i != VWidth; ++i)
1558       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1559         Elts.push_back(Undef);
1560         UndefElts |= (1ULL << i);
1561       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1562         Elts.push_back(Undef);
1563         UndefElts |= (1ULL << i);
1564       } else {                               // Otherwise, defined.
1565         Elts.push_back(CP->getOperand(i));
1566       }
1567         
1568     // If we changed the constant, return it.
1569     Constant *NewCP = ConstantVector::get(Elts);
1570     return NewCP != CP ? NewCP : 0;
1571   } else if (isa<ConstantAggregateZero>(V)) {
1572     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1573     // set to undef.
1574     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1575     Constant *Zero = Constant::getNullValue(EltTy);
1576     Constant *Undef = UndefValue::get(EltTy);
1577     std::vector<Constant*> Elts;
1578     for (unsigned i = 0; i != VWidth; ++i)
1579       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1580     UndefElts = DemandedElts ^ EltMask;
1581     return ConstantVector::get(Elts);
1582   }
1583   
1584   if (!V->hasOneUse()) {    // Other users may use these bits.
1585     if (Depth != 0) {       // Not at the root.
1586       // TODO: Just compute the UndefElts information recursively.
1587       return false;
1588     }
1589     return false;
1590   } else if (Depth == 10) {        // Limit search depth.
1591     return false;
1592   }
1593   
1594   Instruction *I = dyn_cast<Instruction>(V);
1595   if (!I) return false;        // Only analyze instructions.
1596   
1597   bool MadeChange = false;
1598   uint64_t UndefElts2;
1599   Value *TmpV;
1600   switch (I->getOpcode()) {
1601   default: break;
1602     
1603   case Instruction::InsertElement: {
1604     // If this is a variable index, we don't know which element it overwrites.
1605     // demand exactly the same input as we produce.
1606     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1607     if (Idx == 0) {
1608       // Note that we can't propagate undef elt info, because we don't know
1609       // which elt is getting updated.
1610       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1611                                         UndefElts2, Depth+1);
1612       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1613       break;
1614     }
1615     
1616     // If this is inserting an element that isn't demanded, remove this
1617     // insertelement.
1618     unsigned IdxNo = Idx->getZExtValue();
1619     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1620       return AddSoonDeadInstToWorklist(*I, 0);
1621     
1622     // Otherwise, the element inserted overwrites whatever was there, so the
1623     // input demanded set is simpler than the output set.
1624     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1625                                       DemandedElts & ~(1ULL << IdxNo),
1626                                       UndefElts, Depth+1);
1627     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1628
1629     // The inserted element is defined.
1630     UndefElts |= 1ULL << IdxNo;
1631     break;
1632   }
1633     
1634   case Instruction::And:
1635   case Instruction::Or:
1636   case Instruction::Xor:
1637   case Instruction::Add:
1638   case Instruction::Sub:
1639   case Instruction::Mul:
1640     // div/rem demand all inputs, because they don't want divide by zero.
1641     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1642                                       UndefElts, Depth+1);
1643     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1644     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1645                                       UndefElts2, Depth+1);
1646     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1647       
1648     // Output elements are undefined if both are undefined.  Consider things
1649     // like undef&0.  The result is known zero, not undef.
1650     UndefElts &= UndefElts2;
1651     break;
1652     
1653   case Instruction::Call: {
1654     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1655     if (!II) break;
1656     switch (II->getIntrinsicID()) {
1657     default: break;
1658       
1659     // Binary vector operations that work column-wise.  A dest element is a
1660     // function of the corresponding input elements from the two inputs.
1661     case Intrinsic::x86_sse_sub_ss:
1662     case Intrinsic::x86_sse_mul_ss:
1663     case Intrinsic::x86_sse_min_ss:
1664     case Intrinsic::x86_sse_max_ss:
1665     case Intrinsic::x86_sse2_sub_sd:
1666     case Intrinsic::x86_sse2_mul_sd:
1667     case Intrinsic::x86_sse2_min_sd:
1668     case Intrinsic::x86_sse2_max_sd:
1669       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1670                                         UndefElts, Depth+1);
1671       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1672       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1673                                         UndefElts2, Depth+1);
1674       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1675
1676       // If only the low elt is demanded and this is a scalarizable intrinsic,
1677       // scalarize it now.
1678       if (DemandedElts == 1) {
1679         switch (II->getIntrinsicID()) {
1680         default: break;
1681         case Intrinsic::x86_sse_sub_ss:
1682         case Intrinsic::x86_sse_mul_ss:
1683         case Intrinsic::x86_sse2_sub_sd:
1684         case Intrinsic::x86_sse2_mul_sd:
1685           // TODO: Lower MIN/MAX/ABS/etc
1686           Value *LHS = II->getOperand(1);
1687           Value *RHS = II->getOperand(2);
1688           // Extract the element as scalars.
1689           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1690           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1691           
1692           switch (II->getIntrinsicID()) {
1693           default: assert(0 && "Case stmts out of sync!");
1694           case Intrinsic::x86_sse_sub_ss:
1695           case Intrinsic::x86_sse2_sub_sd:
1696             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1697                                                         II->getName()), *II);
1698             break;
1699           case Intrinsic::x86_sse_mul_ss:
1700           case Intrinsic::x86_sse2_mul_sd:
1701             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1702                                                          II->getName()), *II);
1703             break;
1704           }
1705           
1706           Instruction *New =
1707             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1708                                   II->getName());
1709           InsertNewInstBefore(New, *II);
1710           AddSoonDeadInstToWorklist(*II, 0);
1711           return New;
1712         }            
1713       }
1714         
1715       // Output elements are undefined if both are undefined.  Consider things
1716       // like undef&0.  The result is known zero, not undef.
1717       UndefElts &= UndefElts2;
1718       break;
1719     }
1720     break;
1721   }
1722   }
1723   return MadeChange ? I : 0;
1724 }
1725
1726 /// @returns true if the specified compare instruction is
1727 /// true when both operands are equal...
1728 /// @brief Determine if the ICmpInst returns true if both operands are equal
1729 static bool isTrueWhenEqual(ICmpInst &ICI) {
1730   ICmpInst::Predicate pred = ICI.getPredicate();
1731   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1732          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1733          pred == ICmpInst::ICMP_SLE;
1734 }
1735
1736 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1737 /// function is designed to check a chain of associative operators for a
1738 /// potential to apply a certain optimization.  Since the optimization may be
1739 /// applicable if the expression was reassociated, this checks the chain, then
1740 /// reassociates the expression as necessary to expose the optimization
1741 /// opportunity.  This makes use of a special Functor, which must define
1742 /// 'shouldApply' and 'apply' methods.
1743 ///
1744 template<typename Functor>
1745 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1746   unsigned Opcode = Root.getOpcode();
1747   Value *LHS = Root.getOperand(0);
1748
1749   // Quick check, see if the immediate LHS matches...
1750   if (F.shouldApply(LHS))
1751     return F.apply(Root);
1752
1753   // Otherwise, if the LHS is not of the same opcode as the root, return.
1754   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1755   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1756     // Should we apply this transform to the RHS?
1757     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1758
1759     // If not to the RHS, check to see if we should apply to the LHS...
1760     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1761       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1762       ShouldApply = true;
1763     }
1764
1765     // If the functor wants to apply the optimization to the RHS of LHSI,
1766     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1767     if (ShouldApply) {
1768       BasicBlock *BB = Root.getParent();
1769
1770       // Now all of the instructions are in the current basic block, go ahead
1771       // and perform the reassociation.
1772       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1773
1774       // First move the selected RHS to the LHS of the root...
1775       Root.setOperand(0, LHSI->getOperand(1));
1776
1777       // Make what used to be the LHS of the root be the user of the root...
1778       Value *ExtraOperand = TmpLHSI->getOperand(1);
1779       if (&Root == TmpLHSI) {
1780         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1781         return 0;
1782       }
1783       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1784       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1785       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1786       BasicBlock::iterator ARI = &Root; ++ARI;
1787       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1788       ARI = Root;
1789
1790       // Now propagate the ExtraOperand down the chain of instructions until we
1791       // get to LHSI.
1792       while (TmpLHSI != LHSI) {
1793         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1794         // Move the instruction to immediately before the chain we are
1795         // constructing to avoid breaking dominance properties.
1796         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1797         BB->getInstList().insert(ARI, NextLHSI);
1798         ARI = NextLHSI;
1799
1800         Value *NextOp = NextLHSI->getOperand(1);
1801         NextLHSI->setOperand(1, ExtraOperand);
1802         TmpLHSI = NextLHSI;
1803         ExtraOperand = NextOp;
1804       }
1805
1806       // Now that the instructions are reassociated, have the functor perform
1807       // the transformation...
1808       return F.apply(Root);
1809     }
1810
1811     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1812   }
1813   return 0;
1814 }
1815
1816
1817 // AddRHS - Implements: X + X --> X << 1
1818 struct AddRHS {
1819   Value *RHS;
1820   AddRHS(Value *rhs) : RHS(rhs) {}
1821   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1822   Instruction *apply(BinaryOperator &Add) const {
1823     return BinaryOperator::createShl(Add.getOperand(0),
1824                                   ConstantInt::get(Add.getType(), 1));
1825   }
1826 };
1827
1828 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1829 //                 iff C1&C2 == 0
1830 struct AddMaskingAnd {
1831   Constant *C2;
1832   AddMaskingAnd(Constant *c) : C2(c) {}
1833   bool shouldApply(Value *LHS) const {
1834     ConstantInt *C1;
1835     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1836            ConstantExpr::getAnd(C1, C2)->isNullValue();
1837   }
1838   Instruction *apply(BinaryOperator &Add) const {
1839     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1840   }
1841 };
1842
1843 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1844                                              InstCombiner *IC) {
1845   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1846     if (Constant *SOC = dyn_cast<Constant>(SO))
1847       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1848
1849     return IC->InsertNewInstBefore(CastInst::create(
1850           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1851   }
1852
1853   // Figure out if the constant is the left or the right argument.
1854   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1855   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1856
1857   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1858     if (ConstIsRHS)
1859       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1860     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1861   }
1862
1863   Value *Op0 = SO, *Op1 = ConstOperand;
1864   if (!ConstIsRHS)
1865     std::swap(Op0, Op1);
1866   Instruction *New;
1867   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1868     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1869   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1870     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1871                           SO->getName()+".cmp");
1872   else {
1873     assert(0 && "Unknown binary instruction type!");
1874     abort();
1875   }
1876   return IC->InsertNewInstBefore(New, I);
1877 }
1878
1879 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1880 // constant as the other operand, try to fold the binary operator into the
1881 // select arguments.  This also works for Cast instructions, which obviously do
1882 // not have a second operand.
1883 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1884                                      InstCombiner *IC) {
1885   // Don't modify shared select instructions
1886   if (!SI->hasOneUse()) return 0;
1887   Value *TV = SI->getOperand(1);
1888   Value *FV = SI->getOperand(2);
1889
1890   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1891     // Bool selects with constant operands can be folded to logical ops.
1892     if (SI->getType() == Type::Int1Ty) return 0;
1893
1894     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1895     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1896
1897     return new SelectInst(SI->getCondition(), SelectTrueVal,
1898                           SelectFalseVal);
1899   }
1900   return 0;
1901 }
1902
1903
1904 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1905 /// node as operand #0, see if we can fold the instruction into the PHI (which
1906 /// is only possible if all operands to the PHI are constants).
1907 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1908   PHINode *PN = cast<PHINode>(I.getOperand(0));
1909   unsigned NumPHIValues = PN->getNumIncomingValues();
1910   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1911
1912   // Check to see if all of the operands of the PHI are constants.  If there is
1913   // one non-constant value, remember the BB it is.  If there is more than one
1914   // or if *it* is a PHI, bail out.
1915   BasicBlock *NonConstBB = 0;
1916   for (unsigned i = 0; i != NumPHIValues; ++i)
1917     if (!isa<Constant>(PN->getIncomingValue(i))) {
1918       if (NonConstBB) return 0;  // More than one non-const value.
1919       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1920       NonConstBB = PN->getIncomingBlock(i);
1921       
1922       // If the incoming non-constant value is in I's block, we have an infinite
1923       // loop.
1924       if (NonConstBB == I.getParent())
1925         return 0;
1926     }
1927   
1928   // If there is exactly one non-constant value, we can insert a copy of the
1929   // operation in that block.  However, if this is a critical edge, we would be
1930   // inserting the computation one some other paths (e.g. inside a loop).  Only
1931   // do this if the pred block is unconditionally branching into the phi block.
1932   if (NonConstBB) {
1933     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1934     if (!BI || !BI->isUnconditional()) return 0;
1935   }
1936
1937   // Okay, we can do the transformation: create the new PHI node.
1938   PHINode *NewPN = new PHINode(I.getType(), "");
1939   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1940   InsertNewInstBefore(NewPN, *PN);
1941   NewPN->takeName(PN);
1942
1943   // Next, add all of the operands to the PHI.
1944   if (I.getNumOperands() == 2) {
1945     Constant *C = cast<Constant>(I.getOperand(1));
1946     for (unsigned i = 0; i != NumPHIValues; ++i) {
1947       Value *InV;
1948       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1949         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1950           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1951         else
1952           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1953       } else {
1954         assert(PN->getIncomingBlock(i) == NonConstBB);
1955         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1956           InV = BinaryOperator::create(BO->getOpcode(),
1957                                        PN->getIncomingValue(i), C, "phitmp",
1958                                        NonConstBB->getTerminator());
1959         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1960           InV = CmpInst::create(CI->getOpcode(), 
1961                                 CI->getPredicate(),
1962                                 PN->getIncomingValue(i), C, "phitmp",
1963                                 NonConstBB->getTerminator());
1964         else
1965           assert(0 && "Unknown binop!");
1966         
1967         AddToWorkList(cast<Instruction>(InV));
1968       }
1969       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1970     }
1971   } else { 
1972     CastInst *CI = cast<CastInst>(&I);
1973     const Type *RetTy = CI->getType();
1974     for (unsigned i = 0; i != NumPHIValues; ++i) {
1975       Value *InV;
1976       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1977         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1978       } else {
1979         assert(PN->getIncomingBlock(i) == NonConstBB);
1980         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1981                                I.getType(), "phitmp", 
1982                                NonConstBB->getTerminator());
1983         AddToWorkList(cast<Instruction>(InV));
1984       }
1985       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1986     }
1987   }
1988   return ReplaceInstUsesWith(I, NewPN);
1989 }
1990
1991 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1992   bool Changed = SimplifyCommutative(I);
1993   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1994
1995   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1996     // X + undef -> undef
1997     if (isa<UndefValue>(RHS))
1998       return ReplaceInstUsesWith(I, RHS);
1999
2000     // X + 0 --> X
2001     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2002       if (RHSC->isNullValue())
2003         return ReplaceInstUsesWith(I, LHS);
2004     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2005       if (CFP->isExactlyValue(-0.0))
2006         return ReplaceInstUsesWith(I, LHS);
2007     }
2008
2009     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2010       // X + (signbit) --> X ^ signbit
2011       uint64_t Val = CI->getZExtValue();
2012       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
2013         return BinaryOperator::createXor(LHS, RHS);
2014       
2015       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2016       // (X & 254)+1 -> (X&254)|1
2017       uint64_t KnownZero, KnownOne;
2018       if (!isa<VectorType>(I.getType()) &&
2019           SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
2020                                KnownZero, KnownOne))
2021         return &I;
2022     }
2023
2024     if (isa<PHINode>(LHS))
2025       if (Instruction *NV = FoldOpIntoPhi(I))
2026         return NV;
2027     
2028     ConstantInt *XorRHS = 0;
2029     Value *XorLHS = 0;
2030     if (isa<ConstantInt>(RHSC) &&
2031         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2032       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2033       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2034       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2035       
2036       uint64_t C0080Val = 1ULL << 31;
2037       int64_t CFF80Val = -C0080Val;
2038       unsigned Size = 32;
2039       do {
2040         if (TySizeBits > Size) {
2041           bool Found = false;
2042           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2043           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2044           if (RHSSExt == CFF80Val) {
2045             if (XorRHS->getZExtValue() == C0080Val)
2046               Found = true;
2047           } else if (RHSZExt == C0080Val) {
2048             if (XorRHS->getSExtValue() == CFF80Val)
2049               Found = true;
2050           }
2051           if (Found) {
2052             // This is a sign extend if the top bits are known zero.
2053             uint64_t Mask = ~0ULL;
2054             Mask <<= 64-(TySizeBits-Size);
2055             Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
2056             if (!MaskedValueIsZero(XorLHS, Mask))
2057               Size = 0;  // Not a sign ext, but can't be any others either.
2058             goto FoundSExt;
2059           }
2060         }
2061         Size >>= 1;
2062         C0080Val >>= Size;
2063         CFF80Val >>= Size;
2064       } while (Size >= 8);
2065       
2066 FoundSExt:
2067       const Type *MiddleType = 0;
2068       switch (Size) {
2069       default: break;
2070       case 32: MiddleType = Type::Int32Ty; break;
2071       case 16: MiddleType = Type::Int16Ty; break;
2072       case 8:  MiddleType = Type::Int8Ty; break;
2073       }
2074       if (MiddleType) {
2075         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2076         InsertNewInstBefore(NewTrunc, I);
2077         return new SExtInst(NewTrunc, I.getType());
2078       }
2079     }
2080   }
2081
2082   // X + X --> X << 1
2083   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2084     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2085
2086     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2087       if (RHSI->getOpcode() == Instruction::Sub)
2088         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2089           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2090     }
2091     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2092       if (LHSI->getOpcode() == Instruction::Sub)
2093         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2094           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2095     }
2096   }
2097
2098   // -A + B  -->  B - A
2099   if (Value *V = dyn_castNegVal(LHS))
2100     return BinaryOperator::createSub(RHS, V);
2101
2102   // A + -B  -->  A - B
2103   if (!isa<Constant>(RHS))
2104     if (Value *V = dyn_castNegVal(RHS))
2105       return BinaryOperator::createSub(LHS, V);
2106
2107
2108   ConstantInt *C2;
2109   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2110     if (X == RHS)   // X*C + X --> X * (C+1)
2111       return BinaryOperator::createMul(RHS, AddOne(C2));
2112
2113     // X*C1 + X*C2 --> X * (C1+C2)
2114     ConstantInt *C1;
2115     if (X == dyn_castFoldableMul(RHS, C1))
2116       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
2117   }
2118
2119   // X + X*C --> X * (C+1)
2120   if (dyn_castFoldableMul(RHS, C2) == LHS)
2121     return BinaryOperator::createMul(LHS, AddOne(C2));
2122
2123   // X + ~X --> -1   since   ~X = -X-1
2124   if (dyn_castNotVal(LHS) == RHS ||
2125       dyn_castNotVal(RHS) == LHS)
2126     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2127   
2128
2129   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2130   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2131     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2132       return R;
2133
2134   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2135     Value *X = 0;
2136     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
2137       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2138       return BinaryOperator::createSub(C, X);
2139     }
2140
2141     // (X & FF00) + xx00  -> (X+xx00) & FF00
2142     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2143       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2144       if (Anded == CRHS) {
2145         // See if all bits from the first bit set in the Add RHS up are included
2146         // in the mask.  First, get the rightmost bit.
2147         uint64_t AddRHSV = CRHS->getZExtValue();
2148
2149         // Form a mask of all bits from the lowest bit added through the top.
2150         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2151         AddRHSHighBits &= C2->getType()->getBitMask();
2152
2153         // See if the and mask includes all of these bits.
2154         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
2155
2156         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2157           // Okay, the xform is safe.  Insert the new add pronto.
2158           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2159                                                             LHS->getName()), I);
2160           return BinaryOperator::createAnd(NewAdd, C2);
2161         }
2162       }
2163     }
2164
2165     // Try to fold constant add into select arguments.
2166     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2167       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2168         return R;
2169   }
2170
2171   // add (cast *A to intptrtype) B -> 
2172   //   cast (GEP (cast *A to sbyte*) B) -> 
2173   //     intptrtype
2174   {
2175     CastInst *CI = dyn_cast<CastInst>(LHS);
2176     Value *Other = RHS;
2177     if (!CI) {
2178       CI = dyn_cast<CastInst>(RHS);
2179       Other = LHS;
2180     }
2181     if (CI && CI->getType()->isSized() && 
2182         (CI->getType()->getPrimitiveSizeInBits() == 
2183          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2184         && isa<PointerType>(CI->getOperand(0)->getType())) {
2185       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2186                                    PointerType::get(Type::Int8Ty), I);
2187       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2188       return new PtrToIntInst(I2, CI->getType());
2189     }
2190   }
2191
2192   return Changed ? &I : 0;
2193 }
2194
2195 // isSignBit - Return true if the value represented by the constant only has the
2196 // highest order bit set.
2197 static bool isSignBit(ConstantInt *CI) {
2198   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
2199   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
2200 }
2201
2202 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2203   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2204
2205   if (Op0 == Op1)         // sub X, X  -> 0
2206     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2207
2208   // If this is a 'B = x-(-A)', change to B = x+A...
2209   if (Value *V = dyn_castNegVal(Op1))
2210     return BinaryOperator::createAdd(Op0, V);
2211
2212   if (isa<UndefValue>(Op0))
2213     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2214   if (isa<UndefValue>(Op1))
2215     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2216
2217   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2218     // Replace (-1 - A) with (~A)...
2219     if (C->isAllOnesValue())
2220       return BinaryOperator::createNot(Op1);
2221
2222     // C - ~X == X + (1+C)
2223     Value *X = 0;
2224     if (match(Op1, m_Not(m_Value(X))))
2225       return BinaryOperator::createAdd(X,
2226                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2227     // -(X >>u 31) -> (X >>s 31)
2228     // -(X >>s 31) -> (X >>u 31)
2229     if (C->isNullValue()) {
2230       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2231         if (SI->getOpcode() == Instruction::LShr) {
2232           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2233             // Check to see if we are shifting out everything but the sign bit.
2234             if (CU->getZExtValue() == 
2235                 SI->getType()->getPrimitiveSizeInBits()-1) {
2236               // Ok, the transformation is safe.  Insert AShr.
2237               return BinaryOperator::create(Instruction::AShr, 
2238                                           SI->getOperand(0), CU, SI->getName());
2239             }
2240           }
2241         }
2242         else if (SI->getOpcode() == Instruction::AShr) {
2243           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2244             // Check to see if we are shifting out everything but the sign bit.
2245             if (CU->getZExtValue() == 
2246                 SI->getType()->getPrimitiveSizeInBits()-1) {
2247               // Ok, the transformation is safe.  Insert LShr. 
2248               return BinaryOperator::createLShr(
2249                                           SI->getOperand(0), CU, SI->getName());
2250             }
2251           }
2252         } 
2253     }
2254
2255     // Try to fold constant sub into select arguments.
2256     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2257       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2258         return R;
2259
2260     if (isa<PHINode>(Op0))
2261       if (Instruction *NV = FoldOpIntoPhi(I))
2262         return NV;
2263   }
2264
2265   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2266     if (Op1I->getOpcode() == Instruction::Add &&
2267         !Op0->getType()->isFPOrFPVector()) {
2268       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2269         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2270       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2271         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2272       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2273         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2274           // C1-(X+C2) --> (C1-C2)-X
2275           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2276                                            Op1I->getOperand(0));
2277       }
2278     }
2279
2280     if (Op1I->hasOneUse()) {
2281       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2282       // is not used by anyone else...
2283       //
2284       if (Op1I->getOpcode() == Instruction::Sub &&
2285           !Op1I->getType()->isFPOrFPVector()) {
2286         // Swap the two operands of the subexpr...
2287         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2288         Op1I->setOperand(0, IIOp1);
2289         Op1I->setOperand(1, IIOp0);
2290
2291         // Create the new top level add instruction...
2292         return BinaryOperator::createAdd(Op0, Op1);
2293       }
2294
2295       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2296       //
2297       if (Op1I->getOpcode() == Instruction::And &&
2298           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2299         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2300
2301         Value *NewNot =
2302           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2303         return BinaryOperator::createAnd(Op0, NewNot);
2304       }
2305
2306       // 0 - (X sdiv C)  -> (X sdiv -C)
2307       if (Op1I->getOpcode() == Instruction::SDiv)
2308         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2309           if (CSI->isNullValue())
2310             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2311               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2312                                                ConstantExpr::getNeg(DivRHS));
2313
2314       // X - X*C --> X * (1-C)
2315       ConstantInt *C2 = 0;
2316       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2317         Constant *CP1 =
2318           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2319         return BinaryOperator::createMul(Op0, CP1);
2320       }
2321     }
2322   }
2323
2324   if (!Op0->getType()->isFPOrFPVector())
2325     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2326       if (Op0I->getOpcode() == Instruction::Add) {
2327         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2328           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2329         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2330           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2331       } else if (Op0I->getOpcode() == Instruction::Sub) {
2332         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2333           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2334       }
2335
2336   ConstantInt *C1;
2337   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2338     if (X == Op1) { // X*C - X --> X * (C-1)
2339       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2340       return BinaryOperator::createMul(Op1, CP1);
2341     }
2342
2343     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2344     if (X == dyn_castFoldableMul(Op1, C2))
2345       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2346   }
2347   return 0;
2348 }
2349
2350 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2351 /// really just returns true if the most significant (sign) bit is set.
2352 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2353   switch (pred) {
2354     case ICmpInst::ICMP_SLT: 
2355       // True if LHS s< RHS and RHS == 0
2356       return RHS->isNullValue();
2357     case ICmpInst::ICMP_SLE: 
2358       // True if LHS s<= RHS and RHS == -1
2359       return RHS->isAllOnesValue();
2360     case ICmpInst::ICMP_UGE: 
2361       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2362       return RHS->getZExtValue() == (1ULL << 
2363         (RHS->getType()->getPrimitiveSizeInBits()-1));
2364     case ICmpInst::ICMP_UGT:
2365       // True if LHS u> RHS and RHS == high-bit-mask - 1
2366       return RHS->getZExtValue() ==
2367         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2368     default:
2369       return false;
2370   }
2371 }
2372
2373 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2374   bool Changed = SimplifyCommutative(I);
2375   Value *Op0 = I.getOperand(0);
2376
2377   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2378     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2379
2380   // Simplify mul instructions with a constant RHS...
2381   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2382     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2383
2384       // ((X << C1)*C2) == (X * (C2 << C1))
2385       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2386         if (SI->getOpcode() == Instruction::Shl)
2387           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2388             return BinaryOperator::createMul(SI->getOperand(0),
2389                                              ConstantExpr::getShl(CI, ShOp));
2390
2391       if (CI->isNullValue())
2392         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2393       if (CI->equalsInt(1))                  // X * 1  == X
2394         return ReplaceInstUsesWith(I, Op0);
2395       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2396         return BinaryOperator::createNeg(Op0, I.getName());
2397
2398       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2399       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2400         uint64_t C = Log2_64(Val);
2401         return BinaryOperator::createShl(Op0,
2402                                       ConstantInt::get(Op0->getType(), C));
2403       }
2404     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2405       if (Op1F->isNullValue())
2406         return ReplaceInstUsesWith(I, Op1);
2407
2408       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2409       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2410       if (Op1F->getValue() == 1.0)
2411         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2412     }
2413     
2414     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2415       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2416           isa<ConstantInt>(Op0I->getOperand(1))) {
2417         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2418         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2419                                                      Op1, "tmp");
2420         InsertNewInstBefore(Add, I);
2421         Value *C1C2 = ConstantExpr::getMul(Op1, 
2422                                            cast<Constant>(Op0I->getOperand(1)));
2423         return BinaryOperator::createAdd(Add, C1C2);
2424         
2425       }
2426
2427     // Try to fold constant mul into select arguments.
2428     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2429       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2430         return R;
2431
2432     if (isa<PHINode>(Op0))
2433       if (Instruction *NV = FoldOpIntoPhi(I))
2434         return NV;
2435   }
2436
2437   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2438     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2439       return BinaryOperator::createMul(Op0v, Op1v);
2440
2441   // If one of the operands of the multiply is a cast from a boolean value, then
2442   // we know the bool is either zero or one, so this is a 'masking' multiply.
2443   // See if we can simplify things based on how the boolean was originally
2444   // formed.
2445   CastInst *BoolCast = 0;
2446   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2447     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2448       BoolCast = CI;
2449   if (!BoolCast)
2450     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2451       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2452         BoolCast = CI;
2453   if (BoolCast) {
2454     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2455       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2456       const Type *SCOpTy = SCIOp0->getType();
2457
2458       // If the icmp is true iff the sign bit of X is set, then convert this
2459       // multiply into a shift/and combination.
2460       if (isa<ConstantInt>(SCIOp1) &&
2461           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2462         // Shift the X value right to turn it into "all signbits".
2463         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2464                                           SCOpTy->getPrimitiveSizeInBits()-1);
2465         Value *V =
2466           InsertNewInstBefore(
2467             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2468                                             BoolCast->getOperand(0)->getName()+
2469                                             ".mask"), I);
2470
2471         // If the multiply type is not the same as the source type, sign extend
2472         // or truncate to the multiply type.
2473         if (I.getType() != V->getType()) {
2474           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2475           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2476           Instruction::CastOps opcode = 
2477             (SrcBits == DstBits ? Instruction::BitCast : 
2478              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2479           V = InsertCastBefore(opcode, V, I.getType(), I);
2480         }
2481
2482         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2483         return BinaryOperator::createAnd(V, OtherOp);
2484       }
2485     }
2486   }
2487
2488   return Changed ? &I : 0;
2489 }
2490
2491 /// This function implements the transforms on div instructions that work
2492 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2493 /// used by the visitors to those instructions.
2494 /// @brief Transforms common to all three div instructions
2495 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2496   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2497
2498   // undef / X -> 0
2499   if (isa<UndefValue>(Op0))
2500     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2501
2502   // X / undef -> undef
2503   if (isa<UndefValue>(Op1))
2504     return ReplaceInstUsesWith(I, Op1);
2505
2506   // Handle cases involving: div X, (select Cond, Y, Z)
2507   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2508     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2509     // same basic block, then we replace the select with Y, and the condition 
2510     // of the select with false (if the cond value is in the same BB).  If the
2511     // select has uses other than the div, this allows them to be simplified
2512     // also. Note that div X, Y is just as good as div X, 0 (undef)
2513     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2514       if (ST->isNullValue()) {
2515         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2516         if (CondI && CondI->getParent() == I.getParent())
2517           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2518         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2519           I.setOperand(1, SI->getOperand(2));
2520         else
2521           UpdateValueUsesWith(SI, SI->getOperand(2));
2522         return &I;
2523       }
2524
2525     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2526     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2527       if (ST->isNullValue()) {
2528         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2529         if (CondI && CondI->getParent() == I.getParent())
2530           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2531         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2532           I.setOperand(1, SI->getOperand(1));
2533         else
2534           UpdateValueUsesWith(SI, SI->getOperand(1));
2535         return &I;
2536       }
2537   }
2538
2539   return 0;
2540 }
2541
2542 /// This function implements the transforms common to both integer division
2543 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2544 /// division instructions.
2545 /// @brief Common integer divide transforms
2546 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2547   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2548
2549   if (Instruction *Common = commonDivTransforms(I))
2550     return Common;
2551
2552   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2553     // div X, 1 == X
2554     if (RHS->equalsInt(1))
2555       return ReplaceInstUsesWith(I, Op0);
2556
2557     // (X / C1) / C2  -> X / (C1*C2)
2558     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2559       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2560         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2561           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2562                                         ConstantExpr::getMul(RHS, LHSRHS));
2563         }
2564
2565     if (!RHS->isNullValue()) { // avoid X udiv 0
2566       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2567         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2568           return R;
2569       if (isa<PHINode>(Op0))
2570         if (Instruction *NV = FoldOpIntoPhi(I))
2571           return NV;
2572     }
2573   }
2574
2575   // 0 / X == 0, we don't need to preserve faults!
2576   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2577     if (LHS->equalsInt(0))
2578       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2579
2580   return 0;
2581 }
2582
2583 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2584   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2585
2586   // Handle the integer div common cases
2587   if (Instruction *Common = commonIDivTransforms(I))
2588     return Common;
2589
2590   // X udiv C^2 -> X >> C
2591   // Check to see if this is an unsigned division with an exact power of 2,
2592   // if so, convert to a right shift.
2593   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2594     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2595       if (isPowerOf2_64(Val)) {
2596         uint64_t ShiftAmt = Log2_64(Val);
2597         return BinaryOperator::createLShr(Op0, 
2598                                     ConstantInt::get(Op0->getType(), ShiftAmt));
2599       }
2600   }
2601
2602   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2603   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2604     if (RHSI->getOpcode() == Instruction::Shl &&
2605         isa<ConstantInt>(RHSI->getOperand(0))) {
2606       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2607       if (isPowerOf2_64(C1)) {
2608         Value *N = RHSI->getOperand(1);
2609         const Type *NTy = N->getType();
2610         if (uint64_t C2 = Log2_64(C1)) {
2611           Constant *C2V = ConstantInt::get(NTy, C2);
2612           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2613         }
2614         return BinaryOperator::createLShr(Op0, N);
2615       }
2616     }
2617   }
2618   
2619   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2620   // where C1&C2 are powers of two.
2621   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2622     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2623       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2624         uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2625         if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2626           // Compute the shift amounts
2627           unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2628           // Construct the "on true" case of the select
2629           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2630           Instruction *TSI = BinaryOperator::createLShr(
2631                                                  Op0, TC, SI->getName()+".t");
2632           TSI = InsertNewInstBefore(TSI, I);
2633   
2634           // Construct the "on false" case of the select
2635           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2636           Instruction *FSI = BinaryOperator::createLShr(
2637                                                  Op0, FC, SI->getName()+".f");
2638           FSI = InsertNewInstBefore(FSI, I);
2639
2640           // construct the select instruction and return it.
2641           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2642         }
2643       }
2644   return 0;
2645 }
2646
2647 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2648   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650   // Handle the integer div common cases
2651   if (Instruction *Common = commonIDivTransforms(I))
2652     return Common;
2653
2654   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2655     // sdiv X, -1 == -X
2656     if (RHS->isAllOnesValue())
2657       return BinaryOperator::createNeg(Op0);
2658
2659     // -X/C -> X/-C
2660     if (Value *LHSNeg = dyn_castNegVal(Op0))
2661       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2662   }
2663
2664   // If the sign bits of both operands are zero (i.e. we can prove they are
2665   // unsigned inputs), turn this into a udiv.
2666   if (I.getType()->isInteger()) {
2667     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2668     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2669       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2670     }
2671   }      
2672   
2673   return 0;
2674 }
2675
2676 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2677   return commonDivTransforms(I);
2678 }
2679
2680 /// GetFactor - If we can prove that the specified value is at least a multiple
2681 /// of some factor, return that factor.
2682 static Constant *GetFactor(Value *V) {
2683   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2684     return CI;
2685   
2686   // Unless we can be tricky, we know this is a multiple of 1.
2687   Constant *Result = ConstantInt::get(V->getType(), 1);
2688   
2689   Instruction *I = dyn_cast<Instruction>(V);
2690   if (!I) return Result;
2691   
2692   if (I->getOpcode() == Instruction::Mul) {
2693     // Handle multiplies by a constant, etc.
2694     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2695                                 GetFactor(I->getOperand(1)));
2696   } else if (I->getOpcode() == Instruction::Shl) {
2697     // (X<<C) -> X * (1 << C)
2698     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2699       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2700       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2701     }
2702   } else if (I->getOpcode() == Instruction::And) {
2703     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2704       // X & 0xFFF0 is known to be a multiple of 16.
2705       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2706       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2707         return ConstantExpr::getShl(Result, 
2708                                     ConstantInt::get(Result->getType(), Zeros));
2709     }
2710   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2711     // Only handle int->int casts.
2712     if (!CI->isIntegerCast())
2713       return Result;
2714     Value *Op = CI->getOperand(0);
2715     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2716   }    
2717   return Result;
2718 }
2719
2720 /// This function implements the transforms on rem instructions that work
2721 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2722 /// is used by the visitors to those instructions.
2723 /// @brief Transforms common to all three rem instructions
2724 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2725   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2726
2727   // 0 % X == 0, we don't need to preserve faults!
2728   if (Constant *LHS = dyn_cast<Constant>(Op0))
2729     if (LHS->isNullValue())
2730       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2731
2732   if (isa<UndefValue>(Op0))              // undef % X -> 0
2733     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2734   if (isa<UndefValue>(Op1))
2735     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2736
2737   // Handle cases involving: rem X, (select Cond, Y, Z)
2738   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2739     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2740     // the same basic block, then we replace the select with Y, and the
2741     // condition of the select with false (if the cond value is in the same
2742     // BB).  If the select has uses other than the div, this allows them to be
2743     // simplified also.
2744     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2745       if (ST->isNullValue()) {
2746         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2747         if (CondI && CondI->getParent() == I.getParent())
2748           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2749         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2750           I.setOperand(1, SI->getOperand(2));
2751         else
2752           UpdateValueUsesWith(SI, SI->getOperand(2));
2753         return &I;
2754       }
2755     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2756     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2757       if (ST->isNullValue()) {
2758         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2759         if (CondI && CondI->getParent() == I.getParent())
2760           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2761         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2762           I.setOperand(1, SI->getOperand(1));
2763         else
2764           UpdateValueUsesWith(SI, SI->getOperand(1));
2765         return &I;
2766       }
2767   }
2768
2769   return 0;
2770 }
2771
2772 /// This function implements the transforms common to both integer remainder
2773 /// instructions (urem and srem). It is called by the visitors to those integer
2774 /// remainder instructions.
2775 /// @brief Common integer remainder transforms
2776 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2777   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2778
2779   if (Instruction *common = commonRemTransforms(I))
2780     return common;
2781
2782   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2783     // X % 0 == undef, we don't need to preserve faults!
2784     if (RHS->equalsInt(0))
2785       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2786     
2787     if (RHS->equalsInt(1))  // X % 1 == 0
2788       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2789
2790     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2791       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2792         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2793           return R;
2794       } else if (isa<PHINode>(Op0I)) {
2795         if (Instruction *NV = FoldOpIntoPhi(I))
2796           return NV;
2797       }
2798       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2799       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2800         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2801     }
2802   }
2803
2804   return 0;
2805 }
2806
2807 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2808   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2809
2810   if (Instruction *common = commonIRemTransforms(I))
2811     return common;
2812   
2813   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2814     // X urem C^2 -> X and C
2815     // Check to see if this is an unsigned remainder with an exact power of 2,
2816     // if so, convert to a bitwise and.
2817     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2818       if (isPowerOf2_64(C->getZExtValue()))
2819         return BinaryOperator::createAnd(Op0, SubOne(C));
2820   }
2821
2822   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2823     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2824     if (RHSI->getOpcode() == Instruction::Shl &&
2825         isa<ConstantInt>(RHSI->getOperand(0))) {
2826       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2827       if (isPowerOf2_64(C1)) {
2828         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2829         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2830                                                                    "tmp"), I);
2831         return BinaryOperator::createAnd(Op0, Add);
2832       }
2833     }
2834   }
2835
2836   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2837   // where C1&C2 are powers of two.
2838   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2839     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2840       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2841         // STO == 0 and SFO == 0 handled above.
2842         if (isPowerOf2_64(STO->getZExtValue()) && 
2843             isPowerOf2_64(SFO->getZExtValue())) {
2844           Value *TrueAnd = InsertNewInstBefore(
2845             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2846           Value *FalseAnd = InsertNewInstBefore(
2847             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2848           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2849         }
2850       }
2851   }
2852   
2853   return 0;
2854 }
2855
2856 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
2859   if (Instruction *common = commonIRemTransforms(I))
2860     return common;
2861   
2862   if (Value *RHSNeg = dyn_castNegVal(Op1))
2863     if (!isa<ConstantInt>(RHSNeg) || 
2864         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2865       // X % -Y -> X % Y
2866       AddUsesToWorkList(I);
2867       I.setOperand(1, RHSNeg);
2868       return &I;
2869     }
2870  
2871   // If the top bits of both operands are zero (i.e. we can prove they are
2872   // unsigned inputs), turn this into a urem.
2873   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2874   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2875     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2876     return BinaryOperator::createURem(Op0, Op1, I.getName());
2877   }
2878
2879   return 0;
2880 }
2881
2882 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2883   return commonRemTransforms(I);
2884 }
2885
2886 // isMaxValueMinusOne - return true if this is Max-1
2887 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2888   if (isSigned) {
2889     // Calculate 0111111111..11111
2890     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2891     int64_t Val = INT64_MAX;             // All ones
2892     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2893     return C->getSExtValue() == Val-1;
2894   }
2895   return C->getZExtValue() == C->getType()->getBitMask()-1;
2896 }
2897
2898 // isMinValuePlusOne - return true if this is Min+1
2899 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2900   if (isSigned) {
2901     // Calculate 1111111111000000000000
2902     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2903     int64_t Val = -1;                    // All ones
2904     Val <<= TypeBits-1;                  // Shift over to the right spot
2905     return C->getSExtValue() == Val+1;
2906   }
2907   return C->getZExtValue() == 1; // unsigned
2908 }
2909
2910 // isOneBitSet - Return true if there is exactly one bit set in the specified
2911 // constant.
2912 static bool isOneBitSet(const ConstantInt *CI) {
2913   uint64_t V = CI->getZExtValue();
2914   return V && (V & (V-1)) == 0;
2915 }
2916
2917 #if 0   // Currently unused
2918 // isLowOnes - Return true if the constant is of the form 0+1+.
2919 static bool isLowOnes(const ConstantInt *CI) {
2920   uint64_t V = CI->getZExtValue();
2921
2922   // There won't be bits set in parts that the type doesn't contain.
2923   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2924
2925   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2926   return U && V && (U & V) == 0;
2927 }
2928 #endif
2929
2930 // isHighOnes - Return true if the constant is of the form 1+0+.
2931 // This is the same as lowones(~X).
2932 static bool isHighOnes(const ConstantInt *CI) {
2933   uint64_t V = ~CI->getZExtValue();
2934   if (~V == 0) return false;  // 0's does not match "1+"
2935
2936   // There won't be bits set in parts that the type doesn't contain.
2937   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2938
2939   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2940   return U && V && (U & V) == 0;
2941 }
2942
2943 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2944 /// are carefully arranged to allow folding of expressions such as:
2945 ///
2946 ///      (A < B) | (A > B) --> (A != B)
2947 ///
2948 /// Note that this is only valid if the first and second predicates have the
2949 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2950 ///
2951 /// Three bits are used to represent the condition, as follows:
2952 ///   0  A > B
2953 ///   1  A == B
2954 ///   2  A < B
2955 ///
2956 /// <=>  Value  Definition
2957 /// 000     0   Always false
2958 /// 001     1   A >  B
2959 /// 010     2   A == B
2960 /// 011     3   A >= B
2961 /// 100     4   A <  B
2962 /// 101     5   A != B
2963 /// 110     6   A <= B
2964 /// 111     7   Always true
2965 ///  
2966 static unsigned getICmpCode(const ICmpInst *ICI) {
2967   switch (ICI->getPredicate()) {
2968     // False -> 0
2969   case ICmpInst::ICMP_UGT: return 1;  // 001
2970   case ICmpInst::ICMP_SGT: return 1;  // 001
2971   case ICmpInst::ICMP_EQ:  return 2;  // 010
2972   case ICmpInst::ICMP_UGE: return 3;  // 011
2973   case ICmpInst::ICMP_SGE: return 3;  // 011
2974   case ICmpInst::ICMP_ULT: return 4;  // 100
2975   case ICmpInst::ICMP_SLT: return 4;  // 100
2976   case ICmpInst::ICMP_NE:  return 5;  // 101
2977   case ICmpInst::ICMP_ULE: return 6;  // 110
2978   case ICmpInst::ICMP_SLE: return 6;  // 110
2979     // True -> 7
2980   default:
2981     assert(0 && "Invalid ICmp predicate!");
2982     return 0;
2983   }
2984 }
2985
2986 /// getICmpValue - This is the complement of getICmpCode, which turns an
2987 /// opcode and two operands into either a constant true or false, or a brand 
2988 /// new /// ICmp instruction. The sign is passed in to determine which kind
2989 /// of predicate to use in new icmp instructions.
2990 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2991   switch (code) {
2992   default: assert(0 && "Illegal ICmp code!");
2993   case  0: return ConstantInt::getFalse();
2994   case  1: 
2995     if (sign)
2996       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2997     else
2998       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2999   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3000   case  3: 
3001     if (sign)
3002       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3003     else
3004       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3005   case  4: 
3006     if (sign)
3007       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3008     else
3009       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3010   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3011   case  6: 
3012     if (sign)
3013       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3014     else
3015       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3016   case  7: return ConstantInt::getTrue();
3017   }
3018 }
3019
3020 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3021   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3022     (ICmpInst::isSignedPredicate(p1) && 
3023      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3024     (ICmpInst::isSignedPredicate(p2) && 
3025      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3026 }
3027
3028 namespace { 
3029 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3030 struct FoldICmpLogical {
3031   InstCombiner &IC;
3032   Value *LHS, *RHS;
3033   ICmpInst::Predicate pred;
3034   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3035     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3036       pred(ICI->getPredicate()) {}
3037   bool shouldApply(Value *V) const {
3038     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3039       if (PredicatesFoldable(pred, ICI->getPredicate()))
3040         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3041                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3042     return false;
3043   }
3044   Instruction *apply(Instruction &Log) const {
3045     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3046     if (ICI->getOperand(0) != LHS) {
3047       assert(ICI->getOperand(1) == LHS);
3048       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3049     }
3050
3051     unsigned LHSCode = getICmpCode(ICI);
3052     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
3053     unsigned Code;
3054     switch (Log.getOpcode()) {
3055     case Instruction::And: Code = LHSCode & RHSCode; break;
3056     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3057     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3058     default: assert(0 && "Illegal logical opcode!"); return 0;
3059     }
3060
3061     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
3062     if (Instruction *I = dyn_cast<Instruction>(RV))
3063       return I;
3064     // Otherwise, it's a constant boolean value...
3065     return IC.ReplaceInstUsesWith(Log, RV);
3066   }
3067 };
3068 } // end anonymous namespace
3069
3070 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3071 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3072 // guaranteed to be a binary operator.
3073 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3074                                     ConstantInt *OpRHS,
3075                                     ConstantInt *AndRHS,
3076                                     BinaryOperator &TheAnd) {
3077   Value *X = Op->getOperand(0);
3078   Constant *Together = 0;
3079   if (!Op->isShift())
3080     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3081
3082   switch (Op->getOpcode()) {
3083   case Instruction::Xor:
3084     if (Op->hasOneUse()) {
3085       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3086       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3087       InsertNewInstBefore(And, TheAnd);
3088       And->takeName(Op);
3089       return BinaryOperator::createXor(And, Together);
3090     }
3091     break;
3092   case Instruction::Or:
3093     if (Together == AndRHS) // (X | C) & C --> C
3094       return ReplaceInstUsesWith(TheAnd, AndRHS);
3095
3096     if (Op->hasOneUse() && Together != OpRHS) {
3097       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3098       Instruction *Or = BinaryOperator::createOr(X, Together);
3099       InsertNewInstBefore(Or, TheAnd);
3100       Or->takeName(Op);
3101       return BinaryOperator::createAnd(Or, AndRHS);
3102     }
3103     break;
3104   case Instruction::Add:
3105     if (Op->hasOneUse()) {
3106       // Adding a one to a single bit bit-field should be turned into an XOR
3107       // of the bit.  First thing to check is to see if this AND is with a
3108       // single bit constant.
3109       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
3110
3111       // Clear bits that are not part of the constant.
3112       AndRHSV &= AndRHS->getType()->getBitMask();
3113
3114       // If there is only one bit set...
3115       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3116         // Ok, at this point, we know that we are masking the result of the
3117         // ADD down to exactly one bit.  If the constant we are adding has
3118         // no bits set below this bit, then we can eliminate the ADD.
3119         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
3120
3121         // Check to see if any bits below the one bit set in AndRHSV are set.
3122         if ((AddRHS & (AndRHSV-1)) == 0) {
3123           // If not, the only thing that can effect the output of the AND is
3124           // the bit specified by AndRHSV.  If that bit is set, the effect of
3125           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3126           // no effect.
3127           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3128             TheAnd.setOperand(0, X);
3129             return &TheAnd;
3130           } else {
3131             // Pull the XOR out of the AND.
3132             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3133             InsertNewInstBefore(NewAnd, TheAnd);
3134             NewAnd->takeName(Op);
3135             return BinaryOperator::createXor(NewAnd, AndRHS);
3136           }
3137         }
3138       }
3139     }
3140     break;
3141
3142   case Instruction::Shl: {
3143     // We know that the AND will not produce any of the bits shifted in, so if
3144     // the anded constant includes them, clear them now!
3145     //
3146     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3147     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3148     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
3149
3150     if (CI == ShlMask) {   // Masking out bits that the shift already masks
3151       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3152     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3153       TheAnd.setOperand(1, CI);
3154       return &TheAnd;
3155     }
3156     break;
3157   }
3158   case Instruction::LShr:
3159   {
3160     // We know that the AND will not produce any of the bits shifted in, so if
3161     // the anded constant includes them, clear them now!  This only applies to
3162     // unsigned shifts, because a signed shr may bring in set bits!
3163     //
3164     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3165     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3166     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
3167
3168     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
3169       return ReplaceInstUsesWith(TheAnd, Op);
3170     } else if (CI != AndRHS) {
3171       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3172       return &TheAnd;
3173     }
3174     break;
3175   }
3176   case Instruction::AShr:
3177     // Signed shr.
3178     // See if this is shifting in some sign extension, then masking it out
3179     // with an and.
3180     if (Op->hasOneUse()) {
3181       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3182       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3183       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3184       if (C == AndRHS) {          // Masking out bits shifted in.
3185         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3186         // Make the argument unsigned.
3187         Value *ShVal = Op->getOperand(0);
3188         ShVal = InsertNewInstBefore(
3189             BinaryOperator::createLShr(ShVal, OpRHS, 
3190                                    Op->getName()), TheAnd);
3191         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3192       }
3193     }
3194     break;
3195   }
3196   return 0;
3197 }
3198
3199
3200 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3201 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3202 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3203 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3204 /// insert new instructions.
3205 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3206                                            bool isSigned, bool Inside, 
3207                                            Instruction &IB) {
3208   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3209             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3210          "Lo is not <= Hi in range emission code!");
3211     
3212   if (Inside) {
3213     if (Lo == Hi)  // Trivially false.
3214       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3215
3216     // V >= Min && V < Hi --> V < Hi
3217     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3218     ICmpInst::Predicate pred = (isSigned ? 
3219         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3220       return new ICmpInst(pred, V, Hi);
3221     }
3222
3223     // Emit V-Lo <u Hi-Lo
3224     Constant *NegLo = ConstantExpr::getNeg(Lo);
3225     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3226     InsertNewInstBefore(Add, IB);
3227     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3228     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3229   }
3230
3231   if (Lo == Hi)  // Trivially true.
3232     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3233
3234   // V < Min || V >= Hi ->'V > Hi-1'
3235   Hi = SubOne(cast<ConstantInt>(Hi));
3236   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3237     ICmpInst::Predicate pred = (isSigned ? 
3238         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3239     return new ICmpInst(pred, V, Hi);
3240   }
3241
3242   // Emit V-Lo > Hi-1-Lo
3243   Constant *NegLo = ConstantExpr::getNeg(Lo);
3244   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3245   InsertNewInstBefore(Add, IB);
3246   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3247   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3248 }
3249
3250 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3251 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3252 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3253 // not, since all 1s are not contiguous.
3254 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3255   uint64_t V = Val->getZExtValue();
3256   if (!isShiftedMask_64(V)) return false;
3257
3258   // look for the first zero bit after the run of ones
3259   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3260   // look for the first non-zero bit
3261   ME = 64-CountLeadingZeros_64(V);
3262   return true;
3263 }
3264
3265
3266
3267 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3268 /// where isSub determines whether the operator is a sub.  If we can fold one of
3269 /// the following xforms:
3270 /// 
3271 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3272 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3273 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3274 ///
3275 /// return (A +/- B).
3276 ///
3277 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3278                                         ConstantInt *Mask, bool isSub,
3279                                         Instruction &I) {
3280   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3281   if (!LHSI || LHSI->getNumOperands() != 2 ||
3282       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3283
3284   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3285
3286   switch (LHSI->getOpcode()) {
3287   default: return 0;
3288   case Instruction::And:
3289     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3290       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3291       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3292         break;
3293
3294       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3295       // part, we don't need any explicit masks to take them out of A.  If that
3296       // is all N is, ignore it.
3297       unsigned MB, ME;
3298       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3299         uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3300         Mask >>= 64-MB+1;
3301         if (MaskedValueIsZero(RHS, Mask))
3302           break;
3303       }
3304     }
3305     return 0;
3306   case Instruction::Or:
3307   case Instruction::Xor:
3308     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3309     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3310         ConstantExpr::getAnd(N, Mask)->isNullValue())
3311       break;
3312     return 0;
3313   }
3314   
3315   Instruction *New;
3316   if (isSub)
3317     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3318   else
3319     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3320   return InsertNewInstBefore(New, I);
3321 }
3322
3323 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3324   bool Changed = SimplifyCommutative(I);
3325   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3326
3327   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3328     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3329
3330   // and X, X = X
3331   if (Op0 == Op1)
3332     return ReplaceInstUsesWith(I, Op1);
3333
3334   // See if we can simplify any instructions used by the instruction whose sole 
3335   // purpose is to compute bits we don't care about.
3336   uint64_t KnownZero, KnownOne;
3337   if (!isa<VectorType>(I.getType())) {
3338     if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3339                              KnownZero, KnownOne))
3340     return &I;
3341   } else {
3342     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3343       if (CP->isAllOnesValue())
3344         return ReplaceInstUsesWith(I, I.getOperand(0));
3345     }
3346   }
3347   
3348   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3349     uint64_t AndRHSMask = AndRHS->getZExtValue();
3350     uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3351     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3352
3353     // Optimize a variety of ((val OP C1) & C2) combinations...
3354     if (isa<BinaryOperator>(Op0)) {
3355       Instruction *Op0I = cast<Instruction>(Op0);
3356       Value *Op0LHS = Op0I->getOperand(0);
3357       Value *Op0RHS = Op0I->getOperand(1);
3358       switch (Op0I->getOpcode()) {
3359       case Instruction::Xor:
3360       case Instruction::Or:
3361         // If the mask is only needed on one incoming arm, push it up.
3362         if (Op0I->hasOneUse()) {
3363           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3364             // Not masking anything out for the LHS, move to RHS.
3365             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3366                                                    Op0RHS->getName()+".masked");
3367             InsertNewInstBefore(NewRHS, I);
3368             return BinaryOperator::create(
3369                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3370           }
3371           if (!isa<Constant>(Op0RHS) &&
3372               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3373             // Not masking anything out for the RHS, move to LHS.
3374             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3375                                                    Op0LHS->getName()+".masked");
3376             InsertNewInstBefore(NewLHS, I);
3377             return BinaryOperator::create(
3378                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3379           }
3380         }
3381
3382         break;
3383       case Instruction::Add:
3384         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3385         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3386         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3387         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3388           return BinaryOperator::createAnd(V, AndRHS);
3389         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3390           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3391         break;
3392
3393       case Instruction::Sub:
3394         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3395         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3396         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3397         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3398           return BinaryOperator::createAnd(V, AndRHS);
3399         break;
3400       }
3401
3402       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3403         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3404           return Res;
3405     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3406       // If this is an integer truncation or change from signed-to-unsigned, and
3407       // if the source is an and/or with immediate, transform it.  This
3408       // frequently occurs for bitfield accesses.
3409       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3410         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3411             CastOp->getNumOperands() == 2)
3412           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3413             if (CastOp->getOpcode() == Instruction::And) {
3414               // Change: and (cast (and X, C1) to T), C2
3415               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3416               // This will fold the two constants together, which may allow 
3417               // other simplifications.
3418               Instruction *NewCast = CastInst::createTruncOrBitCast(
3419                 CastOp->getOperand(0), I.getType(), 
3420                 CastOp->getName()+".shrunk");
3421               NewCast = InsertNewInstBefore(NewCast, I);
3422               // trunc_or_bitcast(C1)&C2
3423               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3424               C3 = ConstantExpr::getAnd(C3, AndRHS);
3425               return BinaryOperator::createAnd(NewCast, C3);
3426             } else if (CastOp->getOpcode() == Instruction::Or) {
3427               // Change: and (cast (or X, C1) to T), C2
3428               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3429               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3430               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3431                 return ReplaceInstUsesWith(I, AndRHS);
3432             }
3433       }
3434     }
3435
3436     // Try to fold constant and into select arguments.
3437     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3438       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3439         return R;
3440     if (isa<PHINode>(Op0))
3441       if (Instruction *NV = FoldOpIntoPhi(I))
3442         return NV;
3443   }
3444
3445   Value *Op0NotVal = dyn_castNotVal(Op0);
3446   Value *Op1NotVal = dyn_castNotVal(Op1);
3447
3448   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3449     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3450
3451   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3452   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3453     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3454                                                I.getName()+".demorgan");
3455     InsertNewInstBefore(Or, I);
3456     return BinaryOperator::createNot(Or);
3457   }
3458   
3459   {
3460     Value *A = 0, *B = 0;
3461     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3462       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3463         return ReplaceInstUsesWith(I, Op1);
3464     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3465       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3466         return ReplaceInstUsesWith(I, Op0);
3467     
3468     if (Op0->hasOneUse() &&
3469         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3470       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3471         I.swapOperands();     // Simplify below
3472         std::swap(Op0, Op1);
3473       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3474         cast<BinaryOperator>(Op0)->swapOperands();
3475         I.swapOperands();     // Simplify below
3476         std::swap(Op0, Op1);
3477       }
3478     }
3479     if (Op1->hasOneUse() &&
3480         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3481       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3482         cast<BinaryOperator>(Op1)->swapOperands();
3483         std::swap(A, B);
3484       }
3485       if (A == Op0) {                                // A&(A^B) -> A & ~B
3486         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3487         InsertNewInstBefore(NotB, I);
3488         return BinaryOperator::createAnd(A, NotB);
3489       }
3490     }
3491   }
3492   
3493   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3494     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3495     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3496       return R;
3497
3498     Value *LHSVal, *RHSVal;
3499     ConstantInt *LHSCst, *RHSCst;
3500     ICmpInst::Predicate LHSCC, RHSCC;
3501     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3502       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3503         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3504             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3505             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3506             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3507             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3508             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3509           // Ensure that the larger constant is on the RHS.
3510           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3511             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3512           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3513           ICmpInst *LHS = cast<ICmpInst>(Op0);
3514           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3515             std::swap(LHS, RHS);
3516             std::swap(LHSCst, RHSCst);
3517             std::swap(LHSCC, RHSCC);
3518           }
3519
3520           // At this point, we know we have have two icmp instructions
3521           // comparing a value against two constants and and'ing the result
3522           // together.  Because of the above check, we know that we only have
3523           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3524           // (from the FoldICmpLogical check above), that the two constants 
3525           // are not equal and that the larger constant is on the RHS
3526           assert(LHSCst != RHSCst && "Compares not folded above?");
3527
3528           switch (LHSCC) {
3529           default: assert(0 && "Unknown integer condition code!");
3530           case ICmpInst::ICMP_EQ:
3531             switch (RHSCC) {
3532             default: assert(0 && "Unknown integer condition code!");
3533             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3534             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3535             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3536               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3537             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3538             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3539             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3540               return ReplaceInstUsesWith(I, LHS);
3541             }
3542           case ICmpInst::ICMP_NE:
3543             switch (RHSCC) {
3544             default: assert(0 && "Unknown integer condition code!");
3545             case ICmpInst::ICMP_ULT:
3546               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3547                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3548               break;                        // (X != 13 & X u< 15) -> no change
3549             case ICmpInst::ICMP_SLT:
3550               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3551                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3552               break;                        // (X != 13 & X s< 15) -> no change
3553             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3554             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3555             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3556               return ReplaceInstUsesWith(I, RHS);
3557             case ICmpInst::ICMP_NE:
3558               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3559                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3560                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3561                                                       LHSVal->getName()+".off");
3562                 InsertNewInstBefore(Add, I);
3563                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3564                                     ConstantInt::get(Add->getType(), 1));
3565               }
3566               break;                        // (X != 13 & X != 15) -> no change
3567             }
3568             break;
3569           case ICmpInst::ICMP_ULT:
3570             switch (RHSCC) {
3571             default: assert(0 && "Unknown integer condition code!");
3572             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3573             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3574               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3575             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3576               break;
3577             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3578             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3579               return ReplaceInstUsesWith(I, LHS);
3580             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3581               break;
3582             }
3583             break;
3584           case ICmpInst::ICMP_SLT:
3585             switch (RHSCC) {
3586             default: assert(0 && "Unknown integer condition code!");
3587             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3588             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3589               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3590             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3591               break;
3592             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3593             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3594               return ReplaceInstUsesWith(I, LHS);
3595             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3596               break;
3597             }
3598             break;
3599           case ICmpInst::ICMP_UGT:
3600             switch (RHSCC) {
3601             default: assert(0 && "Unknown integer condition code!");
3602             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3603               return ReplaceInstUsesWith(I, LHS);
3604             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3605               return ReplaceInstUsesWith(I, RHS);
3606             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3607               break;
3608             case ICmpInst::ICMP_NE:
3609               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3610                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3611               break;                        // (X u> 13 & X != 15) -> no change
3612             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3613               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3614                                      true, I);
3615             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3616               break;
3617             }
3618             break;
3619           case ICmpInst::ICMP_SGT:
3620             switch (RHSCC) {
3621             default: assert(0 && "Unknown integer condition code!");
3622             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3623               return ReplaceInstUsesWith(I, LHS);
3624             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3625               return ReplaceInstUsesWith(I, RHS);
3626             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3627               break;
3628             case ICmpInst::ICMP_NE:
3629               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3630                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3631               break;                        // (X s> 13 & X != 15) -> no change
3632             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3633               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3634                                      true, I);
3635             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3636               break;
3637             }
3638             break;
3639           }
3640         }
3641   }
3642
3643   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3644   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3645     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3646       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3647         const Type *SrcTy = Op0C->getOperand(0)->getType();
3648         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3649             // Only do this if the casts both really cause code to be generated.
3650             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3651                               I.getType(), TD) &&
3652             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3653                               I.getType(), TD)) {
3654           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3655                                                          Op1C->getOperand(0),
3656                                                          I.getName());
3657           InsertNewInstBefore(NewOp, I);
3658           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3659         }
3660       }
3661     
3662   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3663   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3664     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3665       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3666           SI0->getOperand(1) == SI1->getOperand(1) &&
3667           (SI0->hasOneUse() || SI1->hasOneUse())) {
3668         Instruction *NewOp =
3669           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3670                                                         SI1->getOperand(0),
3671                                                         SI0->getName()), I);
3672         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3673                                       SI1->getOperand(1));
3674       }
3675   }
3676
3677   return Changed ? &I : 0;
3678 }
3679
3680 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3681 /// in the result.  If it does, and if the specified byte hasn't been filled in
3682 /// yet, fill it in and return false.
3683 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3684   Instruction *I = dyn_cast<Instruction>(V);
3685   if (I == 0) return true;
3686
3687   // If this is an or instruction, it is an inner node of the bswap.
3688   if (I->getOpcode() == Instruction::Or)
3689     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3690            CollectBSwapParts(I->getOperand(1), ByteValues);
3691   
3692   // If this is a shift by a constant int, and it is "24", then its operand
3693   // defines a byte.  We only handle unsigned types here.
3694   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3695     // Not shifting the entire input by N-1 bytes?
3696     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3697         8*(ByteValues.size()-1))
3698       return true;
3699     
3700     unsigned DestNo;
3701     if (I->getOpcode() == Instruction::Shl) {
3702       // X << 24 defines the top byte with the lowest of the input bytes.
3703       DestNo = ByteValues.size()-1;
3704     } else {
3705       // X >>u 24 defines the low byte with the highest of the input bytes.
3706       DestNo = 0;
3707     }
3708     
3709     // If the destination byte value is already defined, the values are or'd
3710     // together, which isn't a bswap (unless it's an or of the same bits).
3711     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3712       return true;
3713     ByteValues[DestNo] = I->getOperand(0);
3714     return false;
3715   }
3716   
3717   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3718   // don't have this.
3719   Value *Shift = 0, *ShiftLHS = 0;
3720   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3721   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3722       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3723     return true;
3724   Instruction *SI = cast<Instruction>(Shift);
3725
3726   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3727   if (ShiftAmt->getZExtValue() & 7 ||
3728       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3729     return true;
3730   
3731   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3732   unsigned DestByte;
3733   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3734     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3735       break;
3736   // Unknown mask for bswap.
3737   if (DestByte == ByteValues.size()) return true;
3738   
3739   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3740   unsigned SrcByte;
3741   if (SI->getOpcode() == Instruction::Shl)
3742     SrcByte = DestByte - ShiftBytes;
3743   else
3744     SrcByte = DestByte + ShiftBytes;
3745   
3746   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3747   if (SrcByte != ByteValues.size()-DestByte-1)
3748     return true;
3749   
3750   // If the destination byte value is already defined, the values are or'd
3751   // together, which isn't a bswap (unless it's an or of the same bits).
3752   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3753     return true;
3754   ByteValues[DestByte] = SI->getOperand(0);
3755   return false;
3756 }
3757
3758 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3759 /// If so, insert the new bswap intrinsic and return it.
3760 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3761   // We cannot bswap one byte.
3762   if (I.getType() == Type::Int8Ty)
3763     return 0;
3764   
3765   /// ByteValues - For each byte of the result, we keep track of which value
3766   /// defines each byte.
3767   SmallVector<Value*, 8> ByteValues;
3768   ByteValues.resize(TD->getTypeSize(I.getType()));
3769     
3770   // Try to find all the pieces corresponding to the bswap.
3771   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3772       CollectBSwapParts(I.getOperand(1), ByteValues))
3773     return 0;
3774   
3775   // Check to see if all of the bytes come from the same value.
3776   Value *V = ByteValues[0];
3777   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3778   
3779   // Check to make sure that all of the bytes come from the same value.
3780   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3781     if (ByteValues[i] != V)
3782       return 0;
3783     
3784   // If they do then *success* we can turn this into a bswap.  Figure out what
3785   // bswap to make it into.
3786   Module *M = I.getParent()->getParent()->getParent();
3787   const char *FnName = 0;
3788   if (I.getType() == Type::Int16Ty)
3789     FnName = "llvm.bswap.i16";
3790   else if (I.getType() == Type::Int32Ty)
3791     FnName = "llvm.bswap.i32";
3792   else if (I.getType() == Type::Int64Ty)
3793     FnName = "llvm.bswap.i64";
3794   else
3795     assert(0 && "Unknown integer type!");
3796   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3797   return new CallInst(F, V);
3798 }
3799
3800
3801 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3802   bool Changed = SimplifyCommutative(I);
3803   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3804
3805   if (isa<UndefValue>(Op1))
3806     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3807                                ConstantInt::getAllOnesValue(I.getType()));
3808
3809   // or X, X = X
3810   if (Op0 == Op1)
3811     return ReplaceInstUsesWith(I, Op0);
3812
3813   // See if we can simplify any instructions used by the instruction whose sole 
3814   // purpose is to compute bits we don't care about.
3815   uint64_t KnownZero, KnownOne;
3816   if (!isa<VectorType>(I.getType()) &&
3817       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3818                            KnownZero, KnownOne))
3819     return &I;
3820   
3821   // or X, -1 == -1
3822   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3823     ConstantInt *C1 = 0; Value *X = 0;
3824     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3825     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3826       Instruction *Or = BinaryOperator::createOr(X, RHS);
3827       InsertNewInstBefore(Or, I);
3828       Or->takeName(Op0);
3829       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3830     }
3831
3832     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3833     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3834       Instruction *Or = BinaryOperator::createOr(X, RHS);
3835       InsertNewInstBefore(Or, I);
3836       Or->takeName(Op0);
3837       return BinaryOperator::createXor(Or,
3838                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3839     }
3840
3841     // Try to fold constant and into select arguments.
3842     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3843       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3844         return R;
3845     if (isa<PHINode>(Op0))
3846       if (Instruction *NV = FoldOpIntoPhi(I))
3847         return NV;
3848   }
3849
3850   Value *A = 0, *B = 0;
3851   ConstantInt *C1 = 0, *C2 = 0;
3852
3853   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3854     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3855       return ReplaceInstUsesWith(I, Op1);
3856   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3857     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3858       return ReplaceInstUsesWith(I, Op0);
3859
3860   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3861   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3862   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3863       match(Op1, m_Or(m_Value(), m_Value())) ||
3864       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3865        match(Op1, m_Shift(m_Value(), m_Value())))) {
3866     if (Instruction *BSwap = MatchBSwap(I))
3867       return BSwap;
3868   }
3869   
3870   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3871   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3872       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3873     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3874     InsertNewInstBefore(NOr, I);
3875     NOr->takeName(Op0);
3876     return BinaryOperator::createXor(NOr, C1);
3877   }
3878
3879   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3880   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3881       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3882     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3883     InsertNewInstBefore(NOr, I);
3884     NOr->takeName(Op0);
3885     return BinaryOperator::createXor(NOr, C1);
3886   }
3887
3888   // (A & C1)|(B & C2)
3889   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3890       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3891
3892     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3893       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3894
3895
3896     // If we have: ((V + N) & C1) | (V & C2)
3897     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3898     // replace with V+N.
3899     if (C1 == ConstantExpr::getNot(C2)) {
3900       Value *V1 = 0, *V2 = 0;
3901       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3902           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3903         // Add commutes, try both ways.
3904         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3905           return ReplaceInstUsesWith(I, A);
3906         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3907           return ReplaceInstUsesWith(I, A);
3908       }
3909       // Or commutes, try both ways.
3910       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3911           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3912         // Add commutes, try both ways.
3913         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3914           return ReplaceInstUsesWith(I, B);
3915         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3916           return ReplaceInstUsesWith(I, B);
3917       }
3918     }
3919   }
3920   
3921   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3922   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3923     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3924       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3925           SI0->getOperand(1) == SI1->getOperand(1) &&
3926           (SI0->hasOneUse() || SI1->hasOneUse())) {
3927         Instruction *NewOp =
3928         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3929                                                      SI1->getOperand(0),
3930                                                      SI0->getName()), I);
3931         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3932                                       SI1->getOperand(1));
3933       }
3934   }
3935
3936   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3937     if (A == Op1)   // ~A | A == -1
3938       return ReplaceInstUsesWith(I,
3939                                 ConstantInt::getAllOnesValue(I.getType()));
3940   } else {
3941     A = 0;
3942   }
3943   // Note, A is still live here!
3944   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3945     if (Op0 == B)
3946       return ReplaceInstUsesWith(I,
3947                                 ConstantInt::getAllOnesValue(I.getType()));
3948
3949     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3950     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3951       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3952                                               I.getName()+".demorgan"), I);
3953       return BinaryOperator::createNot(And);
3954     }
3955   }
3956
3957   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3958   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3959     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3960       return R;
3961
3962     Value *LHSVal, *RHSVal;
3963     ConstantInt *LHSCst, *RHSCst;
3964     ICmpInst::Predicate LHSCC, RHSCC;
3965     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3966       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3967         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3968             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3969             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3970             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3971             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3972             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3973           // Ensure that the larger constant is on the RHS.
3974           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3975             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3976           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3977           ICmpInst *LHS = cast<ICmpInst>(Op0);
3978           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3979             std::swap(LHS, RHS);
3980             std::swap(LHSCst, RHSCst);
3981             std::swap(LHSCC, RHSCC);
3982           }
3983
3984           // At this point, we know we have have two icmp instructions
3985           // comparing a value against two constants and or'ing the result
3986           // together.  Because of the above check, we know that we only have
3987           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3988           // FoldICmpLogical check above), that the two constants are not
3989           // equal.
3990           assert(LHSCst != RHSCst && "Compares not folded above?");
3991
3992           switch (LHSCC) {
3993           default: assert(0 && "Unknown integer condition code!");
3994           case ICmpInst::ICMP_EQ:
3995             switch (RHSCC) {
3996             default: assert(0 && "Unknown integer condition code!");
3997             case ICmpInst::ICMP_EQ:
3998               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3999                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4000                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4001                                                       LHSVal->getName()+".off");
4002                 InsertNewInstBefore(Add, I);
4003                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4004                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4005               }
4006               break;                         // (X == 13 | X == 15) -> no change
4007             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4008             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4009               break;
4010             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4011             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4012             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4013               return ReplaceInstUsesWith(I, RHS);
4014             }
4015             break;
4016           case ICmpInst::ICMP_NE:
4017             switch (RHSCC) {
4018             default: assert(0 && "Unknown integer condition code!");
4019             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4020             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4021             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4022               return ReplaceInstUsesWith(I, LHS);
4023             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4024             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4025             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4026               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4027             }
4028             break;
4029           case ICmpInst::ICMP_ULT:
4030             switch (RHSCC) {
4031             default: assert(0 && "Unknown integer condition code!");
4032             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4033               break;
4034             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4035               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4036                                      false, I);
4037             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4038               break;
4039             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4040             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4041               return ReplaceInstUsesWith(I, RHS);
4042             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4043               break;
4044             }
4045             break;
4046           case ICmpInst::ICMP_SLT:
4047             switch (RHSCC) {
4048             default: assert(0 && "Unknown integer condition code!");
4049             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4050               break;
4051             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4052               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4053                                      false, I);
4054             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4055               break;
4056             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4057             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4058               return ReplaceInstUsesWith(I, RHS);
4059             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4060               break;
4061             }
4062             break;
4063           case ICmpInst::ICMP_UGT:
4064             switch (RHSCC) {
4065             default: assert(0 && "Unknown integer condition code!");
4066             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4067             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4068               return ReplaceInstUsesWith(I, LHS);
4069             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4070               break;
4071             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4072             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4073               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4074             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4075               break;
4076             }
4077             break;
4078           case ICmpInst::ICMP_SGT:
4079             switch (RHSCC) {
4080             default: assert(0 && "Unknown integer condition code!");
4081             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4082             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4083               return ReplaceInstUsesWith(I, LHS);
4084             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4085               break;
4086             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4087             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4088               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4089             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4090               break;
4091             }
4092             break;
4093           }
4094         }
4095   }
4096     
4097   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4098   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4099     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4100       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4101         const Type *SrcTy = Op0C->getOperand(0)->getType();
4102         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4103             // Only do this if the casts both really cause code to be generated.
4104             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4105                               I.getType(), TD) &&
4106             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4107                               I.getType(), TD)) {
4108           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4109                                                         Op1C->getOperand(0),
4110                                                         I.getName());
4111           InsertNewInstBefore(NewOp, I);
4112           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4113         }
4114       }
4115       
4116
4117   return Changed ? &I : 0;
4118 }
4119
4120 // XorSelf - Implements: X ^ X --> 0
4121 struct XorSelf {
4122   Value *RHS;
4123   XorSelf(Value *rhs) : RHS(rhs) {}
4124   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4125   Instruction *apply(BinaryOperator &Xor) const {
4126     return &Xor;
4127   }
4128 };
4129
4130
4131 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4132   bool Changed = SimplifyCommutative(I);
4133   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4134
4135   if (isa<UndefValue>(Op1))
4136     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4137
4138   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4139   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4140     assert(Result == &I && "AssociativeOpt didn't work?");
4141     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4142   }
4143   
4144   // See if we can simplify any instructions used by the instruction whose sole 
4145   // purpose is to compute bits we don't care about.
4146   uint64_t KnownZero, KnownOne;
4147   if (!isa<VectorType>(I.getType()) &&
4148       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
4149                            KnownZero, KnownOne))
4150     return &I;
4151
4152   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4153     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4154     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4155       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4156         return new ICmpInst(ICI->getInversePredicate(),
4157                             ICI->getOperand(0), ICI->getOperand(1));
4158
4159     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4160       // ~(c-X) == X-c-1 == X+(-c-1)
4161       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4162         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4163           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4164           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4165                                               ConstantInt::get(I.getType(), 1));
4166           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4167         }
4168
4169       // ~(~X & Y) --> (X | ~Y)
4170       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4171         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4172         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4173           Instruction *NotY =
4174             BinaryOperator::createNot(Op0I->getOperand(1),
4175                                       Op0I->getOperand(1)->getName()+".not");
4176           InsertNewInstBefore(NotY, I);
4177           return BinaryOperator::createOr(Op0NotVal, NotY);
4178         }
4179       }
4180
4181       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4182         if (Op0I->getOpcode() == Instruction::Add) {
4183           // ~(X-c) --> (-c-1)-X
4184           if (RHS->isAllOnesValue()) {
4185             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4186             return BinaryOperator::createSub(
4187                            ConstantExpr::getSub(NegOp0CI,
4188                                              ConstantInt::get(I.getType(), 1)),
4189                                           Op0I->getOperand(0));
4190           }
4191         } else if (Op0I->getOpcode() == Instruction::Or) {
4192           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4193           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4194             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4195             // Anything in both C1 and C2 is known to be zero, remove it from
4196             // NewRHS.
4197             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4198             NewRHS = ConstantExpr::getAnd(NewRHS, 
4199                                           ConstantExpr::getNot(CommonBits));
4200             AddToWorkList(Op0I);
4201             I.setOperand(0, Op0I->getOperand(0));
4202             I.setOperand(1, NewRHS);
4203             return &I;
4204           }
4205         }
4206     }
4207
4208     // Try to fold constant and into select arguments.
4209     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4210       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4211         return R;
4212     if (isa<PHINode>(Op0))
4213       if (Instruction *NV = FoldOpIntoPhi(I))
4214         return NV;
4215   }
4216
4217   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4218     if (X == Op1)
4219       return ReplaceInstUsesWith(I,
4220                                 ConstantInt::getAllOnesValue(I.getType()));
4221
4222   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4223     if (X == Op0)
4224       return ReplaceInstUsesWith(I,
4225                                 ConstantInt::getAllOnesValue(I.getType()));
4226
4227   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
4228     if (Op1I->getOpcode() == Instruction::Or) {
4229       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
4230         Op1I->swapOperands();
4231         I.swapOperands();
4232         std::swap(Op0, Op1);
4233       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
4234         I.swapOperands();     // Simplified below.
4235         std::swap(Op0, Op1);
4236       }
4237     } else if (Op1I->getOpcode() == Instruction::Xor) {
4238       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
4239         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4240       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
4241         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
4242     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4243       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
4244         Op1I->swapOperands();
4245       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
4246         I.swapOperands();     // Simplified below.
4247         std::swap(Op0, Op1);
4248       }
4249     }
4250
4251   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4252     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4253       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4254         Op0I->swapOperands();
4255       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4256         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4257         InsertNewInstBefore(NotB, I);
4258         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4259       }
4260     } else if (Op0I->getOpcode() == Instruction::Xor) {
4261       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4262         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4263       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4264         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4265     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4266       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4267         Op0I->swapOperands();
4268       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4269           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4270         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4271         InsertNewInstBefore(N, I);
4272         return BinaryOperator::createAnd(N, Op1);
4273       }
4274     }
4275
4276   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4277   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4278     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4279       return R;
4280
4281   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4282   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4283     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4284       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4285         const Type *SrcTy = Op0C->getOperand(0)->getType();
4286         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4287             // Only do this if the casts both really cause code to be generated.
4288             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4289                               I.getType(), TD) &&
4290             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4291                               I.getType(), TD)) {
4292           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4293                                                          Op1C->getOperand(0),
4294                                                          I.getName());
4295           InsertNewInstBefore(NewOp, I);
4296           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4297         }
4298       }
4299
4300   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4301   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4302     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4303       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4304           SI0->getOperand(1) == SI1->getOperand(1) &&
4305           (SI0->hasOneUse() || SI1->hasOneUse())) {
4306         Instruction *NewOp =
4307         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4308                                                       SI1->getOperand(0),
4309                                                       SI0->getName()), I);
4310         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4311                                       SI1->getOperand(1));
4312       }
4313   }
4314     
4315   return Changed ? &I : 0;
4316 }
4317
4318 static bool isPositive(ConstantInt *C) {
4319   return C->getSExtValue() >= 0;
4320 }
4321
4322 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4323 /// overflowed for this type.
4324 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4325                             ConstantInt *In2) {
4326   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4327
4328   return cast<ConstantInt>(Result)->getZExtValue() <
4329          cast<ConstantInt>(In1)->getZExtValue();
4330 }
4331
4332 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4333 /// code necessary to compute the offset from the base pointer (without adding
4334 /// in the base pointer).  Return the result as a signed integer of intptr size.
4335 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4336   TargetData &TD = IC.getTargetData();
4337   gep_type_iterator GTI = gep_type_begin(GEP);
4338   const Type *IntPtrTy = TD.getIntPtrType();
4339   Value *Result = Constant::getNullValue(IntPtrTy);
4340
4341   // Build a mask for high order bits.
4342   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4343
4344   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4345     Value *Op = GEP->getOperand(i);
4346     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4347     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4348     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4349       if (!OpC->isNullValue()) {
4350         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4351         Scale = ConstantExpr::getMul(OpC, Scale);
4352         if (Constant *RC = dyn_cast<Constant>(Result))
4353           Result = ConstantExpr::getAdd(RC, Scale);
4354         else {
4355           // Emit an add instruction.
4356           Result = IC.InsertNewInstBefore(
4357              BinaryOperator::createAdd(Result, Scale,
4358                                        GEP->getName()+".offs"), I);
4359         }
4360       }
4361     } else {
4362       // Convert to correct type.
4363       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4364                                                Op->getName()+".c"), I);
4365       if (Size != 1)
4366         // We'll let instcombine(mul) convert this to a shl if possible.
4367         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4368                                                     GEP->getName()+".idx"), I);
4369
4370       // Emit an add instruction.
4371       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4372                                                     GEP->getName()+".offs"), I);
4373     }
4374   }
4375   return Result;
4376 }
4377
4378 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4379 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4380 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4381                                        ICmpInst::Predicate Cond,
4382                                        Instruction &I) {
4383   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4384
4385   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4386     if (isa<PointerType>(CI->getOperand(0)->getType()))
4387       RHS = CI->getOperand(0);
4388
4389   Value *PtrBase = GEPLHS->getOperand(0);
4390   if (PtrBase == RHS) {
4391     // As an optimization, we don't actually have to compute the actual value of
4392     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4393     // each index is zero or not.
4394     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4395       Instruction *InVal = 0;
4396       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4397       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4398         bool EmitIt = true;
4399         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4400           if (isa<UndefValue>(C))  // undef index -> undef.
4401             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4402           if (C->isNullValue())
4403             EmitIt = false;
4404           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4405             EmitIt = false;  // This is indexing into a zero sized array?
4406           } else if (isa<ConstantInt>(C))
4407             return ReplaceInstUsesWith(I, // No comparison is needed here.
4408                                  ConstantInt::get(Type::Int1Ty, 
4409                                                   Cond == ICmpInst::ICMP_NE));
4410         }
4411
4412         if (EmitIt) {
4413           Instruction *Comp =
4414             new ICmpInst(Cond, GEPLHS->getOperand(i),
4415                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4416           if (InVal == 0)
4417             InVal = Comp;
4418           else {
4419             InVal = InsertNewInstBefore(InVal, I);
4420             InsertNewInstBefore(Comp, I);
4421             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4422               InVal = BinaryOperator::createOr(InVal, Comp);
4423             else                              // True if all are equal
4424               InVal = BinaryOperator::createAnd(InVal, Comp);
4425           }
4426         }
4427       }
4428
4429       if (InVal)
4430         return InVal;
4431       else
4432         // No comparison is needed here, all indexes = 0
4433         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4434                                                 Cond == ICmpInst::ICMP_EQ));
4435     }
4436
4437     // Only lower this if the icmp is the only user of the GEP or if we expect
4438     // the result to fold to a constant!
4439     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4440       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4441       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4442       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4443                           Constant::getNullValue(Offset->getType()));
4444     }
4445   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4446     // If the base pointers are different, but the indices are the same, just
4447     // compare the base pointer.
4448     if (PtrBase != GEPRHS->getOperand(0)) {
4449       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4450       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4451                         GEPRHS->getOperand(0)->getType();
4452       if (IndicesTheSame)
4453         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4454           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4455             IndicesTheSame = false;
4456             break;
4457           }
4458
4459       // If all indices are the same, just compare the base pointers.
4460       if (IndicesTheSame)
4461         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4462                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4463
4464       // Otherwise, the base pointers are different and the indices are
4465       // different, bail out.
4466       return 0;
4467     }
4468
4469     // If one of the GEPs has all zero indices, recurse.
4470     bool AllZeros = true;
4471     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4472       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4473           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4474         AllZeros = false;
4475         break;
4476       }
4477     if (AllZeros)
4478       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4479                           ICmpInst::getSwappedPredicate(Cond), I);
4480
4481     // If the other GEP has all zero indices, recurse.
4482     AllZeros = true;
4483     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4484       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4485           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4486         AllZeros = false;
4487         break;
4488       }
4489     if (AllZeros)
4490       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4491
4492     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4493       // If the GEPs only differ by one index, compare it.
4494       unsigned NumDifferences = 0;  // Keep track of # differences.
4495       unsigned DiffOperand = 0;     // The operand that differs.
4496       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4497         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4498           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4499                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4500             // Irreconcilable differences.
4501             NumDifferences = 2;
4502             break;
4503           } else {
4504             if (NumDifferences++) break;
4505             DiffOperand = i;
4506           }
4507         }
4508
4509       if (NumDifferences == 0)   // SAME GEP?
4510         return ReplaceInstUsesWith(I, // No comparison is needed here.
4511                                    ConstantInt::get(Type::Int1Ty, 
4512                                                     Cond == ICmpInst::ICMP_EQ));
4513       else if (NumDifferences == 1) {
4514         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4515         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4516         // Make sure we do a signed comparison here.
4517         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4518       }
4519     }
4520
4521     // Only lower this if the icmp is the only user of the GEP or if we expect
4522     // the result to fold to a constant!
4523     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4524         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4525       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4526       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4527       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4528       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4529     }
4530   }
4531   return 0;
4532 }
4533
4534 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4535   bool Changed = SimplifyCompare(I);
4536   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4537
4538   // Fold trivial predicates.
4539   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4540     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4541   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4542     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4543   
4544   // Simplify 'fcmp pred X, X'
4545   if (Op0 == Op1) {
4546     switch (I.getPredicate()) {
4547     default: assert(0 && "Unknown predicate!");
4548     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4549     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4550     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4551       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4552     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4553     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4554     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4555       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4556       
4557     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4558     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4559     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4560     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4561       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4562       I.setPredicate(FCmpInst::FCMP_UNO);
4563       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4564       return &I;
4565       
4566     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4567     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4568     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4569     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4570       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4571       I.setPredicate(FCmpInst::FCMP_ORD);
4572       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4573       return &I;
4574     }
4575   }
4576     
4577   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4578     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4579
4580   // Handle fcmp with constant RHS
4581   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4582     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4583       switch (LHSI->getOpcode()) {
4584       case Instruction::PHI:
4585         if (Instruction *NV = FoldOpIntoPhi(I))
4586           return NV;
4587         break;
4588       case Instruction::Select:
4589         // If either operand of the select is a constant, we can fold the
4590         // comparison into the select arms, which will cause one to be
4591         // constant folded and the select turned into a bitwise or.
4592         Value *Op1 = 0, *Op2 = 0;
4593         if (LHSI->hasOneUse()) {
4594           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4595             // Fold the known value into the constant operand.
4596             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4597             // Insert a new FCmp of the other select operand.
4598             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4599                                                       LHSI->getOperand(2), RHSC,
4600                                                       I.getName()), I);
4601           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4602             // Fold the known value into the constant operand.
4603             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4604             // Insert a new FCmp of the other select operand.
4605             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4606                                                       LHSI->getOperand(1), RHSC,
4607                                                       I.getName()), I);
4608           }
4609         }
4610
4611         if (Op1)
4612           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4613         break;
4614       }
4615   }
4616
4617   return Changed ? &I : 0;
4618 }
4619
4620 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4621   bool Changed = SimplifyCompare(I);
4622   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4623   const Type *Ty = Op0->getType();
4624
4625   // icmp X, X
4626   if (Op0 == Op1)
4627     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4628                                                    isTrueWhenEqual(I)));
4629
4630   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4631     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4632
4633   // icmp of GlobalValues can never equal each other as long as they aren't
4634   // external weak linkage type.
4635   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4636     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4637       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4638         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4639                                                        !isTrueWhenEqual(I)));
4640
4641   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4642   // addresses never equal each other!  We already know that Op0 != Op1.
4643   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4644        isa<ConstantPointerNull>(Op0)) &&
4645       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4646        isa<ConstantPointerNull>(Op1)))
4647     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4648                                                    !isTrueWhenEqual(I)));
4649
4650   // icmp's with boolean values can always be turned into bitwise operations
4651   if (Ty == Type::Int1Ty) {
4652     switch (I.getPredicate()) {
4653     default: assert(0 && "Invalid icmp instruction!");
4654     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4655       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4656       InsertNewInstBefore(Xor, I);
4657       return BinaryOperator::createNot(Xor);
4658     }
4659     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4660       return BinaryOperator::createXor(Op0, Op1);
4661
4662     case ICmpInst::ICMP_UGT:
4663     case ICmpInst::ICMP_SGT:
4664       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4665       // FALL THROUGH
4666     case ICmpInst::ICMP_ULT:
4667     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4668       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4669       InsertNewInstBefore(Not, I);
4670       return BinaryOperator::createAnd(Not, Op1);
4671     }
4672     case ICmpInst::ICMP_UGE:
4673     case ICmpInst::ICMP_SGE:
4674       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4675       // FALL THROUGH
4676     case ICmpInst::ICMP_ULE:
4677     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4678       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4679       InsertNewInstBefore(Not, I);
4680       return BinaryOperator::createOr(Not, Op1);
4681     }
4682     }
4683   }
4684
4685   // See if we are doing a comparison between a constant and an instruction that
4686   // can be folded into the comparison.
4687   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4688     switch (I.getPredicate()) {
4689     default: break;
4690     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4691       if (CI->isMinValue(false))
4692         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4693       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4694         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4695       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4696         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4697       break;
4698
4699     case ICmpInst::ICMP_SLT:
4700       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4701         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4702       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4703         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4704       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4705         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4706       break;
4707
4708     case ICmpInst::ICMP_UGT:
4709       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4710         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4711       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4712         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4713       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4714         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4715       break;
4716
4717     case ICmpInst::ICMP_SGT:
4718       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4719         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4720       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4721         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4722       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4723         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4724       break;
4725
4726     case ICmpInst::ICMP_ULE:
4727       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4728         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4729       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4730         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4731       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4732         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4733       break;
4734
4735     case ICmpInst::ICMP_SLE:
4736       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4737         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4738       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4739         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4740       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4741         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4742       break;
4743
4744     case ICmpInst::ICMP_UGE:
4745       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4746         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4747       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4748         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4749       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4750         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4751       break;
4752
4753     case ICmpInst::ICMP_SGE:
4754       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4755         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4756       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4757         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4758       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4759         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4760       break;
4761     }
4762
4763     // If we still have a icmp le or icmp ge instruction, turn it into the
4764     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4765     // already been handled above, this requires little checking.
4766     //
4767     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4768       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4769     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4770       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4771     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4772       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4773     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4774       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4775     
4776     // See if we can fold the comparison based on bits known to be zero or one
4777     // in the input.
4778     uint64_t KnownZero, KnownOne;
4779     if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
4780                              KnownZero, KnownOne, 0))
4781       return &I;
4782         
4783     // Given the known and unknown bits, compute a range that the LHS could be
4784     // in.
4785     if (KnownOne | KnownZero) {
4786       // Compute the Min, Max and RHS values based on the known bits. For the
4787       // EQ and NE we use unsigned values.
4788       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4789       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4790       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4791         SRHSVal = CI->getSExtValue();
4792         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4793                                                SMax);
4794       } else {
4795         URHSVal = CI->getZExtValue();
4796         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4797                                                  UMax);
4798       }
4799       switch (I.getPredicate()) {  // LE/GE have been folded already.
4800       default: assert(0 && "Unknown icmp opcode!");
4801       case ICmpInst::ICMP_EQ:
4802         if (UMax < URHSVal || UMin > URHSVal)
4803           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4804         break;
4805       case ICmpInst::ICMP_NE:
4806         if (UMax < URHSVal || UMin > URHSVal)
4807           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4808         break;
4809       case ICmpInst::ICMP_ULT:
4810         if (UMax < URHSVal)
4811           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4812         if (UMin > URHSVal)
4813           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4814         break;
4815       case ICmpInst::ICMP_UGT:
4816         if (UMin > URHSVal)
4817           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4818         if (UMax < URHSVal)
4819           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4820         break;
4821       case ICmpInst::ICMP_SLT:
4822         if (SMax < SRHSVal)
4823           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4824         if (SMin > SRHSVal)
4825           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4826         break;
4827       case ICmpInst::ICMP_SGT: 
4828         if (SMin > SRHSVal)
4829           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4830         if (SMax < SRHSVal)
4831           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4832         break;
4833       }
4834     }
4835           
4836     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4837     // instruction, see if that instruction also has constants so that the 
4838     // instruction can be folded into the icmp 
4839     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4840       switch (LHSI->getOpcode()) {
4841       case Instruction::And:
4842         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4843             LHSI->getOperand(0)->hasOneUse()) {
4844           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4845
4846           // If the LHS is an AND of a truncating cast, we can widen the
4847           // and/compare to be the input width without changing the value
4848           // produced, eliminating a cast.
4849           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4850             // We can do this transformation if either the AND constant does not
4851             // have its sign bit set or if it is an equality comparison. 
4852             // Extending a relational comparison when we're checking the sign
4853             // bit would not work.
4854             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4855                 (I.isEquality() ||
4856                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4857                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4858               ConstantInt *NewCST;
4859               ConstantInt *NewCI;
4860               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4861                                          AndCST->getZExtValue());
4862               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4863                                         CI->getZExtValue());
4864               Instruction *NewAnd = 
4865                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4866                                           LHSI->getName());
4867               InsertNewInstBefore(NewAnd, I);
4868               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4869             }
4870           }
4871           
4872           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4873           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4874           // happens a LOT in code produced by the C front-end, for bitfield
4875           // access.
4876           BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4877           if (Shift && !Shift->isShift())
4878             Shift = 0;
4879
4880           ConstantInt *ShAmt;
4881           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4882           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4883           const Type *AndTy = AndCST->getType();          // Type of the and.
4884
4885           // We can fold this as long as we can't shift unknown bits
4886           // into the mask.  This can only happen with signed shift
4887           // rights, as they sign-extend.
4888           if (ShAmt) {
4889             bool CanFold = Shift->isLogicalShift();
4890             if (!CanFold) {
4891               // To test for the bad case of the signed shr, see if any
4892               // of the bits shifted in could be tested after the mask.
4893               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4894               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4895
4896               Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
4897               Constant *ShVal =
4898                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4899                                      OShAmt);
4900               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4901                 CanFold = true;
4902             }
4903
4904             if (CanFold) {
4905               Constant *NewCst;
4906               if (Shift->getOpcode() == Instruction::Shl)
4907                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4908               else
4909                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4910
4911               // Check to see if we are shifting out any of the bits being
4912               // compared.
4913               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4914                 // If we shifted bits out, the fold is not going to work out.
4915                 // As a special case, check to see if this means that the
4916                 // result is always true or false now.
4917                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4918                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4919                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4920                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4921               } else {
4922                 I.setOperand(1, NewCst);
4923                 Constant *NewAndCST;
4924                 if (Shift->getOpcode() == Instruction::Shl)
4925                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4926                 else
4927                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4928                 LHSI->setOperand(1, NewAndCST);
4929                 LHSI->setOperand(0, Shift->getOperand(0));
4930                 AddToWorkList(Shift); // Shift is dead.
4931                 AddUsesToWorkList(I);
4932                 return &I;
4933               }
4934             }
4935           }
4936           
4937           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4938           // preferable because it allows the C<<Y expression to be hoisted out
4939           // of a loop if Y is invariant and X is not.
4940           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4941               I.isEquality() && !Shift->isArithmeticShift() &&
4942               isa<Instruction>(Shift->getOperand(0))) {
4943             // Compute C << Y.
4944             Value *NS;
4945             if (Shift->getOpcode() == Instruction::LShr) {
4946               NS = BinaryOperator::createShl(AndCST, 
4947                                           Shift->getOperand(1), "tmp");
4948             } else {
4949               // Insert a logical shift.
4950               NS = BinaryOperator::createLShr(AndCST,
4951                                           Shift->getOperand(1), "tmp");
4952             }
4953             InsertNewInstBefore(cast<Instruction>(NS), I);
4954
4955             // Compute X & (C << Y).
4956             Instruction *NewAnd = BinaryOperator::createAnd(
4957                 Shift->getOperand(0), NS, LHSI->getName());
4958             InsertNewInstBefore(NewAnd, I);
4959             
4960             I.setOperand(0, NewAnd);
4961             return &I;
4962           }
4963         }
4964         break;
4965
4966       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4967         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4968           if (I.isEquality()) {
4969             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4970
4971             // Check that the shift amount is in range.  If not, don't perform
4972             // undefined shifts.  When the shift is visited it will be
4973             // simplified.
4974             if (ShAmt->getZExtValue() >= TypeBits)
4975               break;
4976
4977             // If we are comparing against bits always shifted out, the
4978             // comparison cannot succeed.
4979             Constant *Comp =
4980               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4981             if (Comp != CI) {// Comparing against a bit that we know is zero.
4982               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4983               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4984               return ReplaceInstUsesWith(I, Cst);
4985             }
4986
4987             if (LHSI->hasOneUse()) {
4988               // Otherwise strength reduce the shift into an and.
4989               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4990               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4991               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4992
4993               Instruction *AndI =
4994                 BinaryOperator::createAnd(LHSI->getOperand(0),
4995                                           Mask, LHSI->getName()+".mask");
4996               Value *And = InsertNewInstBefore(AndI, I);
4997               return new ICmpInst(I.getPredicate(), And,
4998                                      ConstantExpr::getLShr(CI, ShAmt));
4999             }
5000           }
5001         }
5002         break;
5003
5004       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5005       case Instruction::AShr:
5006         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5007           if (I.isEquality()) {
5008             // Check that the shift amount is in range.  If not, don't perform
5009             // undefined shifts.  When the shift is visited it will be
5010             // simplified.
5011             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5012             if (ShAmt->getZExtValue() >= TypeBits)
5013               break;
5014
5015             // If we are comparing against bits always shifted out, the
5016             // comparison cannot succeed.
5017             Constant *Comp;
5018             if (LHSI->getOpcode() == Instruction::LShr) 
5019               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
5020                                            ShAmt);
5021             else
5022               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
5023                                            ShAmt);
5024
5025             if (Comp != CI) {// Comparing against a bit that we know is zero.
5026               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5027               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5028               return ReplaceInstUsesWith(I, Cst);
5029             }
5030
5031             if (LHSI->hasOneUse() || CI->isNullValue()) {
5032               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
5033
5034               // Otherwise strength reduce the shift into an and.
5035               uint64_t Val = ~0ULL;          // All ones.
5036               Val <<= ShAmtVal;              // Shift over to the right spot.
5037               Val &= ~0ULL >> (64-TypeBits);
5038               Constant *Mask = ConstantInt::get(CI->getType(), Val);
5039
5040               Instruction *AndI =
5041                 BinaryOperator::createAnd(LHSI->getOperand(0),
5042                                           Mask, LHSI->getName()+".mask");
5043               Value *And = InsertNewInstBefore(AndI, I);
5044               return new ICmpInst(I.getPredicate(), And,
5045                                      ConstantExpr::getShl(CI, ShAmt));
5046             }
5047           }
5048         }
5049         break;
5050
5051       case Instruction::SDiv:
5052       case Instruction::UDiv:
5053         // Fold: icmp pred ([us]div X, C1), C2 -> range test
5054         // Fold this div into the comparison, producing a range check. 
5055         // Determine, based on the divide type, what the range is being 
5056         // checked.  If there is an overflow on the low or high side, remember 
5057         // it, otherwise compute the range [low, hi) bounding the new value.
5058         // See: InsertRangeTest above for the kinds of replacements possible.
5059         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5060           // FIXME: If the operand types don't match the type of the divide 
5061           // then don't attempt this transform. The code below doesn't have the
5062           // logic to deal with a signed divide and an unsigned compare (and
5063           // vice versa). This is because (x /s C1) <s C2  produces different 
5064           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5065           // (x /u C1) <u C2.  Simply casting the operands and result won't 
5066           // work. :(  The if statement below tests that condition and bails 
5067           // if it finds it. 
5068           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5069           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
5070             break;
5071
5072           // Initialize the variables that will indicate the nature of the
5073           // range check.
5074           bool LoOverflow = false, HiOverflow = false;
5075           ConstantInt *LoBound = 0, *HiBound = 0;
5076
5077           // Compute Prod = CI * DivRHS. We are essentially solving an equation
5078           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5079           // C2 (CI). By solving for X we can turn this into a range check 
5080           // instead of computing a divide. 
5081           ConstantInt *Prod = 
5082             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
5083
5084           // Determine if the product overflows by seeing if the product is
5085           // not equal to the divide. Make sure we do the same kind of divide
5086           // as in the LHS instruction that we're folding. 
5087           bool ProdOV = !DivRHS->isNullValue() && 
5088             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
5089               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5090
5091           // Get the ICmp opcode
5092           ICmpInst::Predicate predicate = I.getPredicate();
5093
5094           if (DivRHS->isNullValue()) {  
5095             // Don't hack on divide by zeros!
5096           } else if (!DivIsSigned) {  // udiv
5097             LoBound = Prod;
5098             LoOverflow = ProdOV;
5099             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
5100           } else if (isPositive(DivRHS)) { // Divisor is > 0.
5101             if (CI->isNullValue()) {       // (X / pos) op 0
5102               // Can't overflow.
5103               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5104               HiBound = DivRHS;
5105             } else if (isPositive(CI)) {   // (X / pos) op pos
5106               LoBound = Prod;
5107               LoOverflow = ProdOV;
5108               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5109             } else {                       // (X / pos) op neg
5110               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5111               LoOverflow = AddWithOverflow(LoBound, Prod,
5112                                            cast<ConstantInt>(DivRHSH));
5113               HiBound = Prod;
5114               HiOverflow = ProdOV;
5115             }
5116           } else {                         // Divisor is < 0.
5117             if (CI->isNullValue()) {       // (X / neg) op 0
5118               LoBound = AddOne(DivRHS);
5119               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5120               if (HiBound == DivRHS)
5121                 LoBound = 0;               // - INTMIN = INTMIN
5122             } else if (isPositive(CI)) {   // (X / neg) op pos
5123               HiOverflow = LoOverflow = ProdOV;
5124               if (!LoOverflow)
5125                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5126               HiBound = AddOne(Prod);
5127             } else {                       // (X / neg) op neg
5128               LoBound = Prod;
5129               LoOverflow = HiOverflow = ProdOV;
5130               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5131             }
5132
5133             // Dividing by a negate swaps the condition.
5134             predicate = ICmpInst::getSwappedPredicate(predicate);
5135           }
5136
5137           if (LoBound) {
5138             Value *X = LHSI->getOperand(0);
5139             switch (predicate) {
5140             default: assert(0 && "Unhandled icmp opcode!");
5141             case ICmpInst::ICMP_EQ:
5142               if (LoOverflow && HiOverflow)
5143                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5144               else if (HiOverflow)
5145                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
5146                                     ICmpInst::ICMP_UGE, X, LoBound);
5147               else if (LoOverflow)
5148                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5149                                     ICmpInst::ICMP_ULT, X, HiBound);
5150               else
5151                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5152                                        true, I);
5153             case ICmpInst::ICMP_NE:
5154               if (LoOverflow && HiOverflow)
5155                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5156               else if (HiOverflow)
5157                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
5158                                     ICmpInst::ICMP_ULT, X, LoBound);
5159               else if (LoOverflow)
5160                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5161                                     ICmpInst::ICMP_UGE, X, HiBound);
5162               else
5163                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5164                                        false, I);
5165             case ICmpInst::ICMP_ULT:
5166             case ICmpInst::ICMP_SLT:
5167               if (LoOverflow)
5168                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5169               return new ICmpInst(predicate, X, LoBound);
5170             case ICmpInst::ICMP_UGT:
5171             case ICmpInst::ICMP_SGT:
5172               if (HiOverflow)
5173                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5174               if (predicate == ICmpInst::ICMP_UGT)
5175                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5176               else
5177                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5178             }
5179           }
5180         }
5181         break;
5182       }
5183
5184     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5185     if (I.isEquality()) {
5186       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5187
5188       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5189       // the second operand is a constant, simplify a bit.
5190       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5191         switch (BO->getOpcode()) {
5192         case Instruction::SRem:
5193           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5194           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5195               BO->hasOneUse()) {
5196             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5197             if (V > 1 && isPowerOf2_64(V)) {
5198               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5199                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
5200               return new ICmpInst(I.getPredicate(), NewRem, 
5201                                   Constant::getNullValue(BO->getType()));
5202             }
5203           }
5204           break;
5205         case Instruction::Add:
5206           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5207           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5208             if (BO->hasOneUse())
5209               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5210                                   ConstantExpr::getSub(CI, BOp1C));
5211           } else if (CI->isNullValue()) {
5212             // Replace ((add A, B) != 0) with (A != -B) if A or B is
5213             // efficiently invertible, or if the add has just this one use.
5214             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5215
5216             if (Value *NegVal = dyn_castNegVal(BOp1))
5217               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
5218             else if (Value *NegVal = dyn_castNegVal(BOp0))
5219               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
5220             else if (BO->hasOneUse()) {
5221               Instruction *Neg = BinaryOperator::createNeg(BOp1);
5222               InsertNewInstBefore(Neg, I);
5223               Neg->takeName(BO);
5224               return new ICmpInst(I.getPredicate(), BOp0, Neg);
5225             }
5226           }
5227           break;
5228         case Instruction::Xor:
5229           // For the xor case, we can xor two constants together, eliminating
5230           // the explicit xor.
5231           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5232             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
5233                                 ConstantExpr::getXor(CI, BOC));
5234
5235           // FALLTHROUGH
5236         case Instruction::Sub:
5237           // Replace (([sub|xor] A, B) != 0) with (A != B)
5238           if (CI->isNullValue())
5239             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5240                                 BO->getOperand(1));
5241           break;
5242
5243         case Instruction::Or:
5244           // If bits are being or'd in that are not present in the constant we
5245           // are comparing against, then the comparison could never succeed!
5246           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5247             Constant *NotCI = ConstantExpr::getNot(CI);
5248             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5249               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5250                                                              isICMP_NE));
5251           }
5252           break;
5253
5254         case Instruction::And:
5255           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5256             // If bits are being compared against that are and'd out, then the
5257             // comparison can never succeed!
5258             if (!ConstantExpr::getAnd(CI,
5259                                       ConstantExpr::getNot(BOC))->isNullValue())
5260               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5261                                                              isICMP_NE));
5262
5263             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5264             if (CI == BOC && isOneBitSet(CI))
5265               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5266                                   ICmpInst::ICMP_NE, Op0,
5267                                   Constant::getNullValue(CI->getType()));
5268
5269             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5270             if (isSignBit(BOC)) {
5271               Value *X = BO->getOperand(0);
5272               Constant *Zero = Constant::getNullValue(X->getType());
5273               ICmpInst::Predicate pred = isICMP_NE ? 
5274                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5275               return new ICmpInst(pred, X, Zero);
5276             }
5277
5278             // ((X & ~7) == 0) --> X < 8
5279             if (CI->isNullValue() && isHighOnes(BOC)) {
5280               Value *X = BO->getOperand(0);
5281               Constant *NegX = ConstantExpr::getNeg(BOC);
5282               ICmpInst::Predicate pred = isICMP_NE ? 
5283                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5284               return new ICmpInst(pred, X, NegX);
5285             }
5286
5287           }
5288         default: break;
5289         }
5290       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5291         // Handle set{eq|ne} <intrinsic>, intcst.
5292         switch (II->getIntrinsicID()) {
5293         default: break;
5294         case Intrinsic::bswap_i16: 
5295           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5296           AddToWorkList(II);  // Dead?
5297           I.setOperand(0, II->getOperand(1));
5298           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5299                                            ByteSwap_16(CI->getZExtValue())));
5300           return &I;
5301         case Intrinsic::bswap_i32:   
5302           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5303           AddToWorkList(II);  // Dead?
5304           I.setOperand(0, II->getOperand(1));
5305           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5306                                            ByteSwap_32(CI->getZExtValue())));
5307           return &I;
5308         case Intrinsic::bswap_i64:   
5309           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5310           AddToWorkList(II);  // Dead?
5311           I.setOperand(0, II->getOperand(1));
5312           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5313                                            ByteSwap_64(CI->getZExtValue())));
5314           return &I;
5315         }
5316       }
5317     } else {  // Not a ICMP_EQ/ICMP_NE
5318       // If the LHS is a cast from an integral value of the same size, then 
5319       // since we know the RHS is a constant, try to simlify.
5320       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5321         Value *CastOp = Cast->getOperand(0);
5322         const Type *SrcTy = CastOp->getType();
5323         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5324         if (SrcTy->isInteger() && 
5325             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5326           // If this is an unsigned comparison, try to make the comparison use
5327           // smaller constant values.
5328           switch (I.getPredicate()) {
5329             default: break;
5330             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5331               ConstantInt *CUI = cast<ConstantInt>(CI);
5332               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5333                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5334                                     ConstantInt::get(SrcTy, -1ULL));
5335               break;
5336             }
5337             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5338               ConstantInt *CUI = cast<ConstantInt>(CI);
5339               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5340                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5341                                     Constant::getNullValue(SrcTy));
5342               break;
5343             }
5344           }
5345
5346         }
5347       }
5348     }
5349   }
5350
5351   // Handle icmp with constant RHS
5352   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5353     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5354       switch (LHSI->getOpcode()) {
5355       case Instruction::GetElementPtr:
5356         if (RHSC->isNullValue()) {
5357           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5358           bool isAllZeros = true;
5359           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5360             if (!isa<Constant>(LHSI->getOperand(i)) ||
5361                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5362               isAllZeros = false;
5363               break;
5364             }
5365           if (isAllZeros)
5366             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5367                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5368         }
5369         break;
5370
5371       case Instruction::PHI:
5372         if (Instruction *NV = FoldOpIntoPhi(I))
5373           return NV;
5374         break;
5375       case Instruction::Select:
5376         // If either operand of the select is a constant, we can fold the
5377         // comparison into the select arms, which will cause one to be
5378         // constant folded and the select turned into a bitwise or.
5379         Value *Op1 = 0, *Op2 = 0;
5380         if (LHSI->hasOneUse()) {
5381           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5382             // Fold the known value into the constant operand.
5383             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5384             // Insert a new ICmp of the other select operand.
5385             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5386                                                    LHSI->getOperand(2), RHSC,
5387                                                    I.getName()), I);
5388           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5389             // Fold the known value into the constant operand.
5390             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5391             // Insert a new ICmp of the other select operand.
5392             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5393                                                    LHSI->getOperand(1), RHSC,
5394                                                    I.getName()), I);
5395           }
5396         }
5397
5398         if (Op1)
5399           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5400         break;
5401       }
5402   }
5403
5404   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5405   if (User *GEP = dyn_castGetElementPtr(Op0))
5406     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5407       return NI;
5408   if (User *GEP = dyn_castGetElementPtr(Op1))
5409     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5410                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5411       return NI;
5412
5413   // Test to see if the operands of the icmp are casted versions of other
5414   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5415   // now.
5416   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5417     if (isa<PointerType>(Op0->getType()) && 
5418         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5419       // We keep moving the cast from the left operand over to the right
5420       // operand, where it can often be eliminated completely.
5421       Op0 = CI->getOperand(0);
5422
5423       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5424       // so eliminate it as well.
5425       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5426         Op1 = CI2->getOperand(0);
5427
5428       // If Op1 is a constant, we can fold the cast into the constant.
5429       if (Op0->getType() != Op1->getType())
5430         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5431           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5432         } else {
5433           // Otherwise, cast the RHS right before the icmp
5434           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5435         }
5436       return new ICmpInst(I.getPredicate(), Op0, Op1);
5437     }
5438   }
5439   
5440   if (isa<CastInst>(Op0)) {
5441     // Handle the special case of: icmp (cast bool to X), <cst>
5442     // This comes up when you have code like
5443     //   int X = A < B;
5444     //   if (X) ...
5445     // For generality, we handle any zero-extension of any operand comparison
5446     // with a constant or another cast from the same type.
5447     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5448       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5449         return R;
5450   }
5451   
5452   if (I.isEquality()) {
5453     Value *A, *B, *C, *D;
5454     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5455       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5456         Value *OtherVal = A == Op1 ? B : A;
5457         return new ICmpInst(I.getPredicate(), OtherVal,
5458                             Constant::getNullValue(A->getType()));
5459       }
5460
5461       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5462         // A^c1 == C^c2 --> A == C^(c1^c2)
5463         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5464           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5465             if (Op1->hasOneUse()) {
5466               Constant *NC = ConstantExpr::getXor(C1, C2);
5467               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5468               return new ICmpInst(I.getPredicate(), A,
5469                                   InsertNewInstBefore(Xor, I));
5470             }
5471         
5472         // A^B == A^D -> B == D
5473         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5474         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5475         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5476         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5477       }
5478     }
5479     
5480     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5481         (A == Op0 || B == Op0)) {
5482       // A == (A^B)  ->  B == 0
5483       Value *OtherVal = A == Op0 ? B : A;
5484       return new ICmpInst(I.getPredicate(), OtherVal,
5485                           Constant::getNullValue(A->getType()));
5486     }
5487     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5488       // (A-B) == A  ->  B == 0
5489       return new ICmpInst(I.getPredicate(), B,
5490                           Constant::getNullValue(B->getType()));
5491     }
5492     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5493       // A == (A-B)  ->  B == 0
5494       return new ICmpInst(I.getPredicate(), B,
5495                           Constant::getNullValue(B->getType()));
5496     }
5497     
5498     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5499     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5500         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5501         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5502       Value *X = 0, *Y = 0, *Z = 0;
5503       
5504       if (A == C) {
5505         X = B; Y = D; Z = A;
5506       } else if (A == D) {
5507         X = B; Y = C; Z = A;
5508       } else if (B == C) {
5509         X = A; Y = D; Z = B;
5510       } else if (B == D) {
5511         X = A; Y = C; Z = B;
5512       }
5513       
5514       if (X) {   // Build (X^Y) & Z
5515         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5516         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5517         I.setOperand(0, Op1);
5518         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5519         return &I;
5520       }
5521     }
5522   }
5523   return Changed ? &I : 0;
5524 }
5525
5526 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5527 // We only handle extending casts so far.
5528 //
5529 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5530   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5531   Value *LHSCIOp        = LHSCI->getOperand(0);
5532   const Type *SrcTy     = LHSCIOp->getType();
5533   const Type *DestTy    = LHSCI->getType();
5534   Value *RHSCIOp;
5535
5536   // We only handle extension cast instructions, so far. Enforce this.
5537   if (LHSCI->getOpcode() != Instruction::ZExt &&
5538       LHSCI->getOpcode() != Instruction::SExt)
5539     return 0;
5540
5541   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5542   bool isSignedCmp = ICI.isSignedPredicate();
5543
5544   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5545     // Not an extension from the same type?
5546     RHSCIOp = CI->getOperand(0);
5547     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5548       return 0;
5549     
5550     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5551     // and the other is a zext), then we can't handle this.
5552     if (CI->getOpcode() != LHSCI->getOpcode())
5553       return 0;
5554
5555     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5556     // then we can't handle this.
5557     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5558       return 0;
5559     
5560     // Okay, just insert a compare of the reduced operands now!
5561     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5562   }
5563
5564   // If we aren't dealing with a constant on the RHS, exit early
5565   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5566   if (!CI)
5567     return 0;
5568
5569   // Compute the constant that would happen if we truncated to SrcTy then
5570   // reextended to DestTy.
5571   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5572   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5573
5574   // If the re-extended constant didn't change...
5575   if (Res2 == CI) {
5576     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5577     // For example, we might have:
5578     //    %A = sext short %X to uint
5579     //    %B = icmp ugt uint %A, 1330
5580     // It is incorrect to transform this into 
5581     //    %B = icmp ugt short %X, 1330 
5582     // because %A may have negative value. 
5583     //
5584     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5585     // OR operation is EQ/NE.
5586     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5587       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5588     else
5589       return 0;
5590   }
5591
5592   // The re-extended constant changed so the constant cannot be represented 
5593   // in the shorter type. Consequently, we cannot emit a simple comparison.
5594
5595   // First, handle some easy cases. We know the result cannot be equal at this
5596   // point so handle the ICI.isEquality() cases
5597   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5598     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5599   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5600     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5601
5602   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5603   // should have been folded away previously and not enter in here.
5604   Value *Result;
5605   if (isSignedCmp) {
5606     // We're performing a signed comparison.
5607     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5608       Result = ConstantInt::getFalse();          // X < (small) --> false
5609     else
5610       Result = ConstantInt::getTrue();           // X < (large) --> true
5611   } else {
5612     // We're performing an unsigned comparison.
5613     if (isSignedExt) {
5614       // We're performing an unsigned comp with a sign extended value.
5615       // This is true if the input is >= 0. [aka >s -1]
5616       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5617       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5618                                    NegOne, ICI.getName()), ICI);
5619     } else {
5620       // Unsigned extend & unsigned compare -> always true.
5621       Result = ConstantInt::getTrue();
5622     }
5623   }
5624
5625   // Finally, return the value computed.
5626   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5627       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5628     return ReplaceInstUsesWith(ICI, Result);
5629   } else {
5630     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5631             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5632            "ICmp should be folded!");
5633     if (Constant *CI = dyn_cast<Constant>(Result))
5634       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5635     else
5636       return BinaryOperator::createNot(Result);
5637   }
5638 }
5639
5640 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5641   return commonShiftTransforms(I);
5642 }
5643
5644 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5645   return commonShiftTransforms(I);
5646 }
5647
5648 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5649   return commonShiftTransforms(I);
5650 }
5651
5652 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5653   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5654   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5655
5656   // shl X, 0 == X and shr X, 0 == X
5657   // shl 0, X == 0 and shr 0, X == 0
5658   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5659       Op0 == Constant::getNullValue(Op0->getType()))
5660     return ReplaceInstUsesWith(I, Op0);
5661   
5662   if (isa<UndefValue>(Op0)) {            
5663     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5664       return ReplaceInstUsesWith(I, Op0);
5665     else                                    // undef << X -> 0, undef >>u X -> 0
5666       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5667   }
5668   if (isa<UndefValue>(Op1)) {
5669     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5670       return ReplaceInstUsesWith(I, Op0);          
5671     else                                     // X << undef, X >>u undef -> 0
5672       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5673   }
5674
5675   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5676   if (I.getOpcode() == Instruction::AShr)
5677     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5678       if (CSI->isAllOnesValue())
5679         return ReplaceInstUsesWith(I, CSI);
5680
5681   // Try to fold constant and into select arguments.
5682   if (isa<Constant>(Op0))
5683     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5684       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5685         return R;
5686
5687   // See if we can turn a signed shr into an unsigned shr.
5688   if (I.isArithmeticShift()) {
5689     if (MaskedValueIsZero(Op0,
5690                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5691       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5692     }
5693   }
5694
5695   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5696     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5697       return Res;
5698   return 0;
5699 }
5700
5701 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5702                                                BinaryOperator &I) {
5703   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5704
5705   // See if we can simplify any instructions used by the instruction whose sole 
5706   // purpose is to compute bits we don't care about.
5707   uint64_t KnownZero, KnownOne;
5708   if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
5709                            KnownZero, KnownOne))
5710     return &I;
5711   
5712   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5713   // of a signed value.
5714   //
5715   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5716   if (Op1->getZExtValue() >= TypeBits) {
5717     if (I.getOpcode() != Instruction::AShr)
5718       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5719     else {
5720       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5721       return &I;
5722     }
5723   }
5724   
5725   // ((X*C1) << C2) == (X * (C1 << C2))
5726   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5727     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5728       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5729         return BinaryOperator::createMul(BO->getOperand(0),
5730                                          ConstantExpr::getShl(BOOp, Op1));
5731   
5732   // Try to fold constant and into select arguments.
5733   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5734     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5735       return R;
5736   if (isa<PHINode>(Op0))
5737     if (Instruction *NV = FoldOpIntoPhi(I))
5738       return NV;
5739   
5740   if (Op0->hasOneUse()) {
5741     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5742       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5743       Value *V1, *V2;
5744       ConstantInt *CC;
5745       switch (Op0BO->getOpcode()) {
5746         default: break;
5747         case Instruction::Add:
5748         case Instruction::And:
5749         case Instruction::Or:
5750         case Instruction::Xor: {
5751           // These operators commute.
5752           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5753           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5754               match(Op0BO->getOperand(1),
5755                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5756             Instruction *YS = BinaryOperator::createShl(
5757                                             Op0BO->getOperand(0), Op1,
5758                                             Op0BO->getName());
5759             InsertNewInstBefore(YS, I); // (Y << C)
5760             Instruction *X = 
5761               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5762                                      Op0BO->getOperand(1)->getName());
5763             InsertNewInstBefore(X, I);  // (X + (Y << C))
5764             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5765             C2 = ConstantExpr::getShl(C2, Op1);
5766             return BinaryOperator::createAnd(X, C2);
5767           }
5768           
5769           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5770           Value *Op0BOOp1 = Op0BO->getOperand(1);
5771           if (isLeftShift && Op0BOOp1->hasOneUse() &&
5772               match(Op0BOOp1, 
5773                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5774               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5775               V2 == Op1) {
5776             Instruction *YS = BinaryOperator::createShl(
5777                                                      Op0BO->getOperand(0), Op1,
5778                                                      Op0BO->getName());
5779             InsertNewInstBefore(YS, I); // (Y << C)
5780             Instruction *XM =
5781               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5782                                         V1->getName()+".mask");
5783             InsertNewInstBefore(XM, I); // X & (CC << C)
5784             
5785             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5786           }
5787         }
5788           
5789         // FALL THROUGH.
5790         case Instruction::Sub: {
5791           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5792           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5793               match(Op0BO->getOperand(0),
5794                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5795             Instruction *YS = BinaryOperator::createShl(
5796                                                      Op0BO->getOperand(1), Op1,
5797                                                      Op0BO->getName());
5798             InsertNewInstBefore(YS, I); // (Y << C)
5799             Instruction *X =
5800               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5801                                      Op0BO->getOperand(0)->getName());
5802             InsertNewInstBefore(X, I);  // (X + (Y << C))
5803             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5804             C2 = ConstantExpr::getShl(C2, Op1);
5805             return BinaryOperator::createAnd(X, C2);
5806           }
5807           
5808           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5809           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5810               match(Op0BO->getOperand(0),
5811                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5812                           m_ConstantInt(CC))) && V2 == Op1 &&
5813               cast<BinaryOperator>(Op0BO->getOperand(0))
5814                   ->getOperand(0)->hasOneUse()) {
5815             Instruction *YS = BinaryOperator::createShl(
5816                                                      Op0BO->getOperand(1), Op1,
5817                                                      Op0BO->getName());
5818             InsertNewInstBefore(YS, I); // (Y << C)
5819             Instruction *XM =
5820               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5821                                         V1->getName()+".mask");
5822             InsertNewInstBefore(XM, I); // X & (CC << C)
5823             
5824             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5825           }
5826           
5827           break;
5828         }
5829       }
5830       
5831       
5832       // If the operand is an bitwise operator with a constant RHS, and the
5833       // shift is the only use, we can pull it out of the shift.
5834       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5835         bool isValid = true;     // Valid only for And, Or, Xor
5836         bool highBitSet = false; // Transform if high bit of constant set?
5837         
5838         switch (Op0BO->getOpcode()) {
5839           default: isValid = false; break;   // Do not perform transform!
5840           case Instruction::Add:
5841             isValid = isLeftShift;
5842             break;
5843           case Instruction::Or:
5844           case Instruction::Xor:
5845             highBitSet = false;
5846             break;
5847           case Instruction::And:
5848             highBitSet = true;
5849             break;
5850         }
5851         
5852         // If this is a signed shift right, and the high bit is modified
5853         // by the logical operation, do not perform the transformation.
5854         // The highBitSet boolean indicates the value of the high bit of
5855         // the constant which would cause it to be modified for this
5856         // operation.
5857         //
5858         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
5859           uint64_t Val = Op0C->getZExtValue();
5860           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5861         }
5862         
5863         if (isValid) {
5864           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5865           
5866           Instruction *NewShift =
5867             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
5868           InsertNewInstBefore(NewShift, I);
5869           NewShift->takeName(Op0BO);
5870           
5871           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5872                                         NewRHS);
5873         }
5874       }
5875     }
5876   }
5877   
5878   // Find out if this is a shift of a shift by a constant.
5879   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5880   if (ShiftOp && !ShiftOp->isShift())
5881     ShiftOp = 0;
5882   
5883   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5884     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5885     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5886     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5887     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5888     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
5889     Value *X = ShiftOp->getOperand(0);
5890     
5891     unsigned AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5892     if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5893       AmtSum = I.getType()->getPrimitiveSizeInBits();
5894     
5895     const IntegerType *Ty = cast<IntegerType>(I.getType());
5896     
5897     // Check for (X << c1) << c2  and  (X >> c1) >> c2
5898     if (I.getOpcode() == ShiftOp->getOpcode()) {
5899       return BinaryOperator::create(I.getOpcode(), X,
5900                                     ConstantInt::get(Ty, AmtSum));
5901     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5902                I.getOpcode() == Instruction::AShr) {
5903       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
5904       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5905     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5906                I.getOpcode() == Instruction::LShr) {
5907       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5908       Instruction *Shift =
5909         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5910       InsertNewInstBefore(Shift, I);
5911
5912       uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5913       return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5914     }
5915     
5916     // Okay, if we get here, one shift must be left, and the other shift must be
5917     // right.  See if the amounts are equal.
5918     if (ShiftAmt1 == ShiftAmt2) {
5919       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5920       if (I.getOpcode() == Instruction::Shl) {
5921         uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
5922         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5923       }
5924       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5925       if (I.getOpcode() == Instruction::LShr) {
5926         uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
5927         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5928       }
5929       // We can simplify ((X << C) >>s C) into a trunc + sext.
5930       // NOTE: we could do this for any C, but that would make 'unusual' integer
5931       // types.  For now, just stick to ones well-supported by the code
5932       // generators.
5933       const Type *SExtType = 0;
5934       switch (Ty->getBitWidth() - ShiftAmt1) {
5935       case 8 : SExtType = Type::Int8Ty; break;
5936       case 16: SExtType = Type::Int16Ty; break;
5937       case 32: SExtType = Type::Int32Ty; break;
5938       default: break;
5939       }
5940       if (SExtType) {
5941         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5942         InsertNewInstBefore(NewTrunc, I);
5943         return new SExtInst(NewTrunc, Ty);
5944       }
5945       // Otherwise, we can't handle it yet.
5946     } else if (ShiftAmt1 < ShiftAmt2) {
5947       unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
5948       
5949       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
5950       if (I.getOpcode() == Instruction::Shl) {
5951         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5952                ShiftOp->getOpcode() == Instruction::AShr);
5953         Instruction *Shift =
5954           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5955         InsertNewInstBefore(Shift, I);
5956         
5957         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5958         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5959       }
5960       
5961       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
5962       if (I.getOpcode() == Instruction::LShr) {
5963         assert(ShiftOp->getOpcode() == Instruction::Shl);
5964         Instruction *Shift =
5965           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5966         InsertNewInstBefore(Shift, I);
5967         
5968         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5969         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5970       }
5971       
5972       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5973     } else {
5974       assert(ShiftAmt2 < ShiftAmt1);
5975       unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5976
5977       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
5978       if (I.getOpcode() == Instruction::Shl) {
5979         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5980                ShiftOp->getOpcode() == Instruction::AShr);
5981         Instruction *Shift =
5982           BinaryOperator::create(ShiftOp->getOpcode(), X,
5983                                  ConstantInt::get(Ty, ShiftDiff));
5984         InsertNewInstBefore(Shift, I);
5985         
5986         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5987         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5988       }
5989       
5990       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
5991       if (I.getOpcode() == Instruction::LShr) {
5992         assert(ShiftOp->getOpcode() == Instruction::Shl);
5993         Instruction *Shift =
5994           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5995         InsertNewInstBefore(Shift, I);
5996         
5997         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5998         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5999       }
6000       
6001       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6002     }
6003   }
6004   return 0;
6005 }
6006
6007
6008 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6009 /// expression.  If so, decompose it, returning some value X, such that Val is
6010 /// X*Scale+Offset.
6011 ///
6012 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6013                                         unsigned &Offset) {
6014   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6015   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6016     Offset = CI->getZExtValue();
6017     Scale  = 1;
6018     return ConstantInt::get(Type::Int32Ty, 0);
6019   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6020     if (I->getNumOperands() == 2) {
6021       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6022         if (I->getOpcode() == Instruction::Shl) {
6023           // This is a value scaled by '1 << the shift amt'.
6024           Scale = 1U << CUI->getZExtValue();
6025           Offset = 0;
6026           return I->getOperand(0);
6027         } else if (I->getOpcode() == Instruction::Mul) {
6028           // This value is scaled by 'CUI'.
6029           Scale = CUI->getZExtValue();
6030           Offset = 0;
6031           return I->getOperand(0);
6032         } else if (I->getOpcode() == Instruction::Add) {
6033           // We have X+C.  Check to see if we really have (X*C2)+C1, 
6034           // where C1 is divisible by C2.
6035           unsigned SubScale;
6036           Value *SubVal = 
6037             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6038           Offset += CUI->getZExtValue();
6039           if (SubScale > 1 && (Offset % SubScale == 0)) {
6040             Scale = SubScale;
6041             return SubVal;
6042           }
6043         }
6044       }
6045     }
6046   }
6047
6048   // Otherwise, we can't look past this.
6049   Scale = 1;
6050   Offset = 0;
6051   return Val;
6052 }
6053
6054
6055 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6056 /// try to eliminate the cast by moving the type information into the alloc.
6057 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6058                                                    AllocationInst &AI) {
6059   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
6060   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
6061   
6062   // Remove any uses of AI that are dead.
6063   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6064   
6065   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6066     Instruction *User = cast<Instruction>(*UI++);
6067     if (isInstructionTriviallyDead(User)) {
6068       while (UI != E && *UI == User)
6069         ++UI; // If this instruction uses AI more than once, don't break UI.
6070       
6071       ++NumDeadInst;
6072       DOUT << "IC: DCE: " << *User;
6073       EraseInstFromFunction(*User);
6074     }
6075   }
6076   
6077   // Get the type really allocated and the type casted to.
6078   const Type *AllocElTy = AI.getAllocatedType();
6079   const Type *CastElTy = PTy->getElementType();
6080   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6081
6082   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6083   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6084   if (CastElTyAlign < AllocElTyAlign) return 0;
6085
6086   // If the allocation has multiple uses, only promote it if we are strictly
6087   // increasing the alignment of the resultant allocation.  If we keep it the
6088   // same, we open the door to infinite loops of various kinds.
6089   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6090
6091   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6092   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6093   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6094
6095   // See if we can satisfy the modulus by pulling a scale out of the array
6096   // size argument.
6097   unsigned ArraySizeScale, ArrayOffset;
6098   Value *NumElements = // See if the array size is a decomposable linear expr.
6099     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6100  
6101   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6102   // do the xform.
6103   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6104       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6105
6106   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6107   Value *Amt = 0;
6108   if (Scale == 1) {
6109     Amt = NumElements;
6110   } else {
6111     // If the allocation size is constant, form a constant mul expression
6112     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6113     if (isa<ConstantInt>(NumElements))
6114       Amt = ConstantExpr::getMul(
6115               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6116     // otherwise multiply the amount and the number of elements
6117     else if (Scale != 1) {
6118       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6119       Amt = InsertNewInstBefore(Tmp, AI);
6120     }
6121   }
6122   
6123   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6124     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
6125     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6126     Amt = InsertNewInstBefore(Tmp, AI);
6127   }
6128   
6129   AllocationInst *New;
6130   if (isa<MallocInst>(AI))
6131     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6132   else
6133     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6134   InsertNewInstBefore(New, AI);
6135   New->takeName(&AI);
6136   
6137   // If the allocation has multiple uses, insert a cast and change all things
6138   // that used it to use the new cast.  This will also hack on CI, but it will
6139   // die soon.
6140   if (!AI.hasOneUse()) {
6141     AddUsesToWorkList(AI);
6142     // New is the allocation instruction, pointer typed. AI is the original
6143     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6144     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6145     InsertNewInstBefore(NewCast, AI);
6146     AI.replaceAllUsesWith(NewCast);
6147   }
6148   return ReplaceInstUsesWith(CI, New);
6149 }
6150
6151 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6152 /// and return it as type Ty without inserting any new casts and without
6153 /// changing the computed value.  This is used by code that tries to decide
6154 /// whether promoting or shrinking integer operations to wider or smaller types
6155 /// will allow us to eliminate a truncate or extend.
6156 ///
6157 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6158 /// extension operation if Ty is larger.
6159 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6160                                        int &NumCastsRemoved) {
6161   // We can always evaluate constants in another type.
6162   if (isa<ConstantInt>(V))
6163     return true;
6164   
6165   Instruction *I = dyn_cast<Instruction>(V);
6166   if (!I) return false;
6167   
6168   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6169   
6170   switch (I->getOpcode()) {
6171   case Instruction::Add:
6172   case Instruction::Sub:
6173   case Instruction::And:
6174   case Instruction::Or:
6175   case Instruction::Xor:
6176     if (!I->hasOneUse()) return false;
6177     // These operators can all arbitrarily be extended or truncated.
6178     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6179            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6180
6181   case Instruction::Shl:
6182     if (!I->hasOneUse()) return false;
6183     // If we are truncating the result of this SHL, and if it's a shift of a
6184     // constant amount, we can always perform a SHL in a smaller type.
6185     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6186       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6187           CI->getZExtValue() < Ty->getBitWidth())
6188         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6189     }
6190     break;
6191   case Instruction::LShr:
6192     if (!I->hasOneUse()) return false;
6193     // If this is a truncate of a logical shr, we can truncate it to a smaller
6194     // lshr iff we know that the bits we would otherwise be shifting in are
6195     // already zeros.
6196     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6197       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6198           MaskedValueIsZero(I->getOperand(0),
6199                             OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6200           CI->getZExtValue() < Ty->getBitWidth()) {
6201         return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6202       }
6203     }
6204     break;
6205   case Instruction::Trunc:
6206   case Instruction::ZExt:
6207   case Instruction::SExt:
6208     // If this is a cast from the destination type, we can trivially eliminate
6209     // it, and this will remove a cast overall.
6210     if (I->getOperand(0)->getType() == Ty) {
6211       // If the first operand is itself a cast, and is eliminable, do not count
6212       // this as an eliminable cast.  We would prefer to eliminate those two
6213       // casts first.
6214       if (isa<CastInst>(I->getOperand(0)))
6215         return true;
6216       
6217       ++NumCastsRemoved;
6218       return true;
6219     }
6220     break;
6221   default:
6222     // TODO: Can handle more cases here.
6223     break;
6224   }
6225   
6226   return false;
6227 }
6228
6229 /// EvaluateInDifferentType - Given an expression that 
6230 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6231 /// evaluate the expression.
6232 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6233                                              bool isSigned) {
6234   if (Constant *C = dyn_cast<Constant>(V))
6235     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6236
6237   // Otherwise, it must be an instruction.
6238   Instruction *I = cast<Instruction>(V);
6239   Instruction *Res = 0;
6240   switch (I->getOpcode()) {
6241   case Instruction::Add:
6242   case Instruction::Sub:
6243   case Instruction::And:
6244   case Instruction::Or:
6245   case Instruction::Xor:
6246   case Instruction::AShr:
6247   case Instruction::LShr:
6248   case Instruction::Shl: {
6249     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6250     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6251     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6252                                  LHS, RHS, I->getName());
6253     break;
6254   }    
6255   case Instruction::Trunc:
6256   case Instruction::ZExt:
6257   case Instruction::SExt:
6258   case Instruction::BitCast:
6259     // If the source type of the cast is the type we're trying for then we can
6260     // just return the source. There's no need to insert it because its not new.
6261     if (I->getOperand(0)->getType() == Ty)
6262       return I->getOperand(0);
6263     
6264     // Some other kind of cast, which shouldn't happen, so just ..
6265     // FALL THROUGH
6266   default: 
6267     // TODO: Can handle more cases here.
6268     assert(0 && "Unreachable!");
6269     break;
6270   }
6271   
6272   return InsertNewInstBefore(Res, *I);
6273 }
6274
6275 /// @brief Implement the transforms common to all CastInst visitors.
6276 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6277   Value *Src = CI.getOperand(0);
6278
6279   // Casting undef to anything results in undef so might as just replace it and
6280   // get rid of the cast.
6281   if (isa<UndefValue>(Src))   // cast undef -> undef
6282     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6283
6284   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6285   // eliminate it now.
6286   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6287     if (Instruction::CastOps opc = 
6288         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6289       // The first cast (CSrc) is eliminable so we need to fix up or replace
6290       // the second cast (CI). CSrc will then have a good chance of being dead.
6291       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6292     }
6293   }
6294
6295   // If casting the result of a getelementptr instruction with no offset, turn
6296   // this into a cast of the original pointer!
6297   //
6298   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6299     bool AllZeroOperands = true;
6300     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6301       if (!isa<Constant>(GEP->getOperand(i)) ||
6302           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6303         AllZeroOperands = false;
6304         break;
6305       }
6306     if (AllZeroOperands) {
6307       // Changing the cast operand is usually not a good idea but it is safe
6308       // here because the pointer operand is being replaced with another 
6309       // pointer operand so the opcode doesn't need to change.
6310       CI.setOperand(0, GEP->getOperand(0));
6311       return &CI;
6312     }
6313   }
6314     
6315   // If we are casting a malloc or alloca to a pointer to a type of the same
6316   // size, rewrite the allocation instruction to allocate the "right" type.
6317   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6318     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6319       return V;
6320
6321   // If we are casting a select then fold the cast into the select
6322   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6323     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6324       return NV;
6325
6326   // If we are casting a PHI then fold the cast into the PHI
6327   if (isa<PHINode>(Src))
6328     if (Instruction *NV = FoldOpIntoPhi(CI))
6329       return NV;
6330   
6331   return 0;
6332 }
6333
6334 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6335 /// integer types. This function implements the common transforms for all those
6336 /// cases.
6337 /// @brief Implement the transforms common to CastInst with integer operands
6338 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6339   if (Instruction *Result = commonCastTransforms(CI))
6340     return Result;
6341
6342   Value *Src = CI.getOperand(0);
6343   const Type *SrcTy = Src->getType();
6344   const Type *DestTy = CI.getType();
6345   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6346   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6347
6348   // See if we can simplify any instructions used by the LHS whose sole 
6349   // purpose is to compute bits we don't care about.
6350   uint64_t KnownZero = 0, KnownOne = 0;
6351   if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6352                            KnownZero, KnownOne))
6353     return &CI;
6354
6355   // If the source isn't an instruction or has more than one use then we
6356   // can't do anything more. 
6357   Instruction *SrcI = dyn_cast<Instruction>(Src);
6358   if (!SrcI || !Src->hasOneUse())
6359     return 0;
6360
6361   // Attempt to propagate the cast into the instruction for int->int casts.
6362   int NumCastsRemoved = 0;
6363   if (!isa<BitCastInst>(CI) &&
6364       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6365                                  NumCastsRemoved)) {
6366     // If this cast is a truncate, evaluting in a different type always
6367     // eliminates the cast, so it is always a win.  If this is a noop-cast
6368     // this just removes a noop cast which isn't pointful, but simplifies
6369     // the code.  If this is a zero-extension, we need to do an AND to
6370     // maintain the clear top-part of the computation, so we require that
6371     // the input have eliminated at least one cast.  If this is a sign
6372     // extension, we insert two new casts (to do the extension) so we
6373     // require that two casts have been eliminated.
6374     bool DoXForm;
6375     switch (CI.getOpcode()) {
6376     default:
6377       // All the others use floating point so we shouldn't actually 
6378       // get here because of the check above.
6379       assert(0 && "Unknown cast type");
6380     case Instruction::Trunc:
6381       DoXForm = true;
6382       break;
6383     case Instruction::ZExt:
6384       DoXForm = NumCastsRemoved >= 1;
6385       break;
6386     case Instruction::SExt:
6387       DoXForm = NumCastsRemoved >= 2;
6388       break;
6389     case Instruction::BitCast:
6390       DoXForm = false;
6391       break;
6392     }
6393     
6394     if (DoXForm) {
6395       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6396                                            CI.getOpcode() == Instruction::SExt);
6397       assert(Res->getType() == DestTy);
6398       switch (CI.getOpcode()) {
6399       default: assert(0 && "Unknown cast type!");
6400       case Instruction::Trunc:
6401       case Instruction::BitCast:
6402         // Just replace this cast with the result.
6403         return ReplaceInstUsesWith(CI, Res);
6404       case Instruction::ZExt: {
6405         // We need to emit an AND to clear the high bits.
6406         assert(SrcBitSize < DestBitSize && "Not a zext?");
6407         Constant *C = 
6408           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6409         if (DestBitSize < 64)
6410           C = ConstantExpr::getTrunc(C, DestTy);
6411         return BinaryOperator::createAnd(Res, C);
6412       }
6413       case Instruction::SExt:
6414         // We need to emit a cast to truncate, then a cast to sext.
6415         return CastInst::create(Instruction::SExt,
6416             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6417                              CI), DestTy);
6418       }
6419     }
6420   }
6421   
6422   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6423   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6424
6425   switch (SrcI->getOpcode()) {
6426   case Instruction::Add:
6427   case Instruction::Mul:
6428   case Instruction::And:
6429   case Instruction::Or:
6430   case Instruction::Xor:
6431     // If we are discarding information, or just changing the sign, 
6432     // rewrite.
6433     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6434       // Don't insert two casts if they cannot be eliminated.  We allow 
6435       // two casts to be inserted if the sizes are the same.  This could 
6436       // only be converting signedness, which is a noop.
6437       if (DestBitSize == SrcBitSize || 
6438           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6439           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6440         Instruction::CastOps opcode = CI.getOpcode();
6441         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6442         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6443         return BinaryOperator::create(
6444             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6445       }
6446     }
6447
6448     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6449     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6450         SrcI->getOpcode() == Instruction::Xor &&
6451         Op1 == ConstantInt::getTrue() &&
6452         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6453       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6454       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6455     }
6456     break;
6457   case Instruction::SDiv:
6458   case Instruction::UDiv:
6459   case Instruction::SRem:
6460   case Instruction::URem:
6461     // If we are just changing the sign, rewrite.
6462     if (DestBitSize == SrcBitSize) {
6463       // Don't insert two casts if they cannot be eliminated.  We allow 
6464       // two casts to be inserted if the sizes are the same.  This could 
6465       // only be converting signedness, which is a noop.
6466       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6467           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6468         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6469                                               Op0, DestTy, SrcI);
6470         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6471                                               Op1, DestTy, SrcI);
6472         return BinaryOperator::create(
6473           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6474       }
6475     }
6476     break;
6477
6478   case Instruction::Shl:
6479     // Allow changing the sign of the source operand.  Do not allow 
6480     // changing the size of the shift, UNLESS the shift amount is a 
6481     // constant.  We must not change variable sized shifts to a smaller 
6482     // size, because it is undefined to shift more bits out than exist 
6483     // in the value.
6484     if (DestBitSize == SrcBitSize ||
6485         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6486       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6487           Instruction::BitCast : Instruction::Trunc);
6488       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6489       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6490       return BinaryOperator::createShl(Op0c, Op1c);
6491     }
6492     break;
6493   case Instruction::AShr:
6494     // If this is a signed shr, and if all bits shifted in are about to be
6495     // truncated off, turn it into an unsigned shr to allow greater
6496     // simplifications.
6497     if (DestBitSize < SrcBitSize &&
6498         isa<ConstantInt>(Op1)) {
6499       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6500       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6501         // Insert the new logical shift right.
6502         return BinaryOperator::createLShr(Op0, Op1);
6503       }
6504     }
6505     break;
6506
6507   case Instruction::ICmp:
6508     // If we are just checking for a icmp eq of a single bit and casting it
6509     // to an integer, then shift the bit to the appropriate place and then
6510     // cast to integer to avoid the comparison.
6511     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6512       uint64_t Op1CV = Op1C->getZExtValue();
6513       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6514       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6515       // cast (X == 1) to int --> X        iff X has only the low bit set.
6516       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6517       // cast (X != 0) to int --> X        iff X has only the low bit set.
6518       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6519       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6520       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6521       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6522         // If Op1C some other power of two, convert:
6523         uint64_t KnownZero, KnownOne;
6524         uint64_t TypeMask = Op1C->getType()->getBitMask();
6525         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6526
6527         // This only works for EQ and NE
6528         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6529         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6530           break;
6531         
6532         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6533           bool isNE = pred == ICmpInst::ICMP_NE;
6534           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6535             // (X&4) == 2 --> false
6536             // (X&4) != 2 --> true
6537             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6538             Res = ConstantExpr::getZExt(Res, CI.getType());
6539             return ReplaceInstUsesWith(CI, Res);
6540           }
6541           
6542           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6543           Value *In = Op0;
6544           if (ShiftAmt) {
6545             // Perform a logical shr by shiftamt.
6546             // Insert the shift to put the result in the low bit.
6547             In = InsertNewInstBefore(
6548               BinaryOperator::createLShr(In,
6549                                      ConstantInt::get(In->getType(), ShiftAmt),
6550                                      In->getName()+".lobit"), CI);
6551           }
6552           
6553           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6554             Constant *One = ConstantInt::get(In->getType(), 1);
6555             In = BinaryOperator::createXor(In, One, "tmp");
6556             InsertNewInstBefore(cast<Instruction>(In), CI);
6557           }
6558           
6559           if (CI.getType() == In->getType())
6560             return ReplaceInstUsesWith(CI, In);
6561           else
6562             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6563         }
6564       }
6565     }
6566     break;
6567   }
6568   return 0;
6569 }
6570
6571 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6572   if (Instruction *Result = commonIntCastTransforms(CI))
6573     return Result;
6574   
6575   Value *Src = CI.getOperand(0);
6576   const Type *Ty = CI.getType();
6577   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6578   
6579   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6580     switch (SrcI->getOpcode()) {
6581     default: break;
6582     case Instruction::LShr:
6583       // We can shrink lshr to something smaller if we know the bits shifted in
6584       // are already zeros.
6585       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6586         unsigned ShAmt = ShAmtV->getZExtValue();
6587         
6588         // Get a mask for the bits shifting in.
6589         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6590         Value* SrcIOp0 = SrcI->getOperand(0);
6591         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6592           if (ShAmt >= DestBitWidth)        // All zeros.
6593             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6594
6595           // Okay, we can shrink this.  Truncate the input, then return a new
6596           // shift.
6597           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6598           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6599                                        Ty, CI);
6600           return BinaryOperator::createLShr(V1, V2);
6601         }
6602       } else {     // This is a variable shr.
6603         
6604         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6605         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6606         // loop-invariant and CSE'd.
6607         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6608           Value *One = ConstantInt::get(SrcI->getType(), 1);
6609
6610           Value *V = InsertNewInstBefore(
6611               BinaryOperator::createShl(One, SrcI->getOperand(1),
6612                                      "tmp"), CI);
6613           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6614                                                             SrcI->getOperand(0),
6615                                                             "tmp"), CI);
6616           Value *Zero = Constant::getNullValue(V->getType());
6617           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6618         }
6619       }
6620       break;
6621     }
6622   }
6623   
6624   return 0;
6625 }
6626
6627 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6628   // If one of the common conversion will work ..
6629   if (Instruction *Result = commonIntCastTransforms(CI))
6630     return Result;
6631
6632   Value *Src = CI.getOperand(0);
6633
6634   // If this is a cast of a cast
6635   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6636     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6637     // types and if the sizes are just right we can convert this into a logical
6638     // 'and' which will be much cheaper than the pair of casts.
6639     if (isa<TruncInst>(CSrc)) {
6640       // Get the sizes of the types involved
6641       Value *A = CSrc->getOperand(0);
6642       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6643       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6644       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6645       // If we're actually extending zero bits and the trunc is a no-op
6646       if (MidSize < DstSize && SrcSize == DstSize) {
6647         // Replace both of the casts with an And of the type mask.
6648         uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
6649         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6650         Instruction *And = 
6651           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6652         // Unfortunately, if the type changed, we need to cast it back.
6653         if (And->getType() != CI.getType()) {
6654           And->setName(CSrc->getName()+".mask");
6655           InsertNewInstBefore(And, CI);
6656           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6657         }
6658         return And;
6659       }
6660     }
6661   }
6662
6663   return 0;
6664 }
6665
6666 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6667   return commonIntCastTransforms(CI);
6668 }
6669
6670 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6671   return commonCastTransforms(CI);
6672 }
6673
6674 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6675   return commonCastTransforms(CI);
6676 }
6677
6678 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6679   return commonCastTransforms(CI);
6680 }
6681
6682 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6683   return commonCastTransforms(CI);
6684 }
6685
6686 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6687   return commonCastTransforms(CI);
6688 }
6689
6690 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6691   return commonCastTransforms(CI);
6692 }
6693
6694 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6695   return commonCastTransforms(CI);
6696 }
6697
6698 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6699   return commonCastTransforms(CI);
6700 }
6701
6702 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6703
6704   // If the operands are integer typed then apply the integer transforms,
6705   // otherwise just apply the common ones.
6706   Value *Src = CI.getOperand(0);
6707   const Type *SrcTy = Src->getType();
6708   const Type *DestTy = CI.getType();
6709
6710   if (SrcTy->isInteger() && DestTy->isInteger()) {
6711     if (Instruction *Result = commonIntCastTransforms(CI))
6712       return Result;
6713   } else {
6714     if (Instruction *Result = commonCastTransforms(CI))
6715       return Result;
6716   }
6717
6718
6719   // Get rid of casts from one type to the same type. These are useless and can
6720   // be replaced by the operand.
6721   if (DestTy == Src->getType())
6722     return ReplaceInstUsesWith(CI, Src);
6723
6724   // If the source and destination are pointers, and this cast is equivalent to
6725   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6726   // This can enhance SROA and other transforms that want type-safe pointers.
6727   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6728     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6729       const Type *DstElTy = DstPTy->getElementType();
6730       const Type *SrcElTy = SrcPTy->getElementType();
6731       
6732       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6733       unsigned NumZeros = 0;
6734       while (SrcElTy != DstElTy && 
6735              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6736              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6737         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6738         ++NumZeros;
6739       }
6740
6741       // If we found a path from the src to dest, create the getelementptr now.
6742       if (SrcElTy == DstElTy) {
6743         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6744         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6745       }
6746     }
6747   }
6748
6749   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6750     if (SVI->hasOneUse()) {
6751       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6752       // a bitconvert to a vector with the same # elts.
6753       if (isa<VectorType>(DestTy) && 
6754           cast<VectorType>(DestTy)->getNumElements() == 
6755                 SVI->getType()->getNumElements()) {
6756         CastInst *Tmp;
6757         // If either of the operands is a cast from CI.getType(), then
6758         // evaluating the shuffle in the casted destination's type will allow
6759         // us to eliminate at least one cast.
6760         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6761              Tmp->getOperand(0)->getType() == DestTy) ||
6762             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6763              Tmp->getOperand(0)->getType() == DestTy)) {
6764           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6765                                                SVI->getOperand(0), DestTy, &CI);
6766           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6767                                                SVI->getOperand(1), DestTy, &CI);
6768           // Return a new shuffle vector.  Use the same element ID's, as we
6769           // know the vector types match #elts.
6770           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6771         }
6772       }
6773     }
6774   }
6775   return 0;
6776 }
6777
6778 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6779 ///   %C = or %A, %B
6780 ///   %D = select %cond, %C, %A
6781 /// into:
6782 ///   %C = select %cond, %B, 0
6783 ///   %D = or %A, %C
6784 ///
6785 /// Assuming that the specified instruction is an operand to the select, return
6786 /// a bitmask indicating which operands of this instruction are foldable if they
6787 /// equal the other incoming value of the select.
6788 ///
6789 static unsigned GetSelectFoldableOperands(Instruction *I) {
6790   switch (I->getOpcode()) {
6791   case Instruction::Add:
6792   case Instruction::Mul:
6793   case Instruction::And:
6794   case Instruction::Or:
6795   case Instruction::Xor:
6796     return 3;              // Can fold through either operand.
6797   case Instruction::Sub:   // Can only fold on the amount subtracted.
6798   case Instruction::Shl:   // Can only fold on the shift amount.
6799   case Instruction::LShr:
6800   case Instruction::AShr:
6801     return 1;
6802   default:
6803     return 0;              // Cannot fold
6804   }
6805 }
6806
6807 /// GetSelectFoldableConstant - For the same transformation as the previous
6808 /// function, return the identity constant that goes into the select.
6809 static Constant *GetSelectFoldableConstant(Instruction *I) {
6810   switch (I->getOpcode()) {
6811   default: assert(0 && "This cannot happen!"); abort();
6812   case Instruction::Add:
6813   case Instruction::Sub:
6814   case Instruction::Or:
6815   case Instruction::Xor:
6816   case Instruction::Shl:
6817   case Instruction::LShr:
6818   case Instruction::AShr:
6819     return Constant::getNullValue(I->getType());
6820   case Instruction::And:
6821     return ConstantInt::getAllOnesValue(I->getType());
6822   case Instruction::Mul:
6823     return ConstantInt::get(I->getType(), 1);
6824   }
6825 }
6826
6827 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6828 /// have the same opcode and only one use each.  Try to simplify this.
6829 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6830                                           Instruction *FI) {
6831   if (TI->getNumOperands() == 1) {
6832     // If this is a non-volatile load or a cast from the same type,
6833     // merge.
6834     if (TI->isCast()) {
6835       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6836         return 0;
6837     } else {
6838       return 0;  // unknown unary op.
6839     }
6840
6841     // Fold this by inserting a select from the input values.
6842     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6843                                        FI->getOperand(0), SI.getName()+".v");
6844     InsertNewInstBefore(NewSI, SI);
6845     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6846                             TI->getType());
6847   }
6848
6849   // Only handle binary operators here.
6850   if (!isa<BinaryOperator>(TI))
6851     return 0;
6852
6853   // Figure out if the operations have any operands in common.
6854   Value *MatchOp, *OtherOpT, *OtherOpF;
6855   bool MatchIsOpZero;
6856   if (TI->getOperand(0) == FI->getOperand(0)) {
6857     MatchOp  = TI->getOperand(0);
6858     OtherOpT = TI->getOperand(1);
6859     OtherOpF = FI->getOperand(1);
6860     MatchIsOpZero = true;
6861   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6862     MatchOp  = TI->getOperand(1);
6863     OtherOpT = TI->getOperand(0);
6864     OtherOpF = FI->getOperand(0);
6865     MatchIsOpZero = false;
6866   } else if (!TI->isCommutative()) {
6867     return 0;
6868   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6869     MatchOp  = TI->getOperand(0);
6870     OtherOpT = TI->getOperand(1);
6871     OtherOpF = FI->getOperand(0);
6872     MatchIsOpZero = true;
6873   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6874     MatchOp  = TI->getOperand(1);
6875     OtherOpT = TI->getOperand(0);
6876     OtherOpF = FI->getOperand(1);
6877     MatchIsOpZero = true;
6878   } else {
6879     return 0;
6880   }
6881
6882   // If we reach here, they do have operations in common.
6883   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6884                                      OtherOpF, SI.getName()+".v");
6885   InsertNewInstBefore(NewSI, SI);
6886
6887   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6888     if (MatchIsOpZero)
6889       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6890     else
6891       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6892   }
6893   assert(0 && "Shouldn't get here");
6894   return 0;
6895 }
6896
6897 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6898   Value *CondVal = SI.getCondition();
6899   Value *TrueVal = SI.getTrueValue();
6900   Value *FalseVal = SI.getFalseValue();
6901
6902   // select true, X, Y  -> X
6903   // select false, X, Y -> Y
6904   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6905     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6906
6907   // select C, X, X -> X
6908   if (TrueVal == FalseVal)
6909     return ReplaceInstUsesWith(SI, TrueVal);
6910
6911   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6912     return ReplaceInstUsesWith(SI, FalseVal);
6913   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6914     return ReplaceInstUsesWith(SI, TrueVal);
6915   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6916     if (isa<Constant>(TrueVal))
6917       return ReplaceInstUsesWith(SI, TrueVal);
6918     else
6919       return ReplaceInstUsesWith(SI, FalseVal);
6920   }
6921
6922   if (SI.getType() == Type::Int1Ty) {
6923     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6924       if (C->getZExtValue()) {
6925         // Change: A = select B, true, C --> A = or B, C
6926         return BinaryOperator::createOr(CondVal, FalseVal);
6927       } else {
6928         // Change: A = select B, false, C --> A = and !B, C
6929         Value *NotCond =
6930           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6931                                              "not."+CondVal->getName()), SI);
6932         return BinaryOperator::createAnd(NotCond, FalseVal);
6933       }
6934     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6935       if (C->getZExtValue() == false) {
6936         // Change: A = select B, C, false --> A = and B, C
6937         return BinaryOperator::createAnd(CondVal, TrueVal);
6938       } else {
6939         // Change: A = select B, C, true --> A = or !B, C
6940         Value *NotCond =
6941           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6942                                              "not."+CondVal->getName()), SI);
6943         return BinaryOperator::createOr(NotCond, TrueVal);
6944       }
6945     }
6946   }
6947
6948   // Selecting between two integer constants?
6949   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6950     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6951       // select C, 1, 0 -> cast C to int
6952       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6953         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6954       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6955         // select C, 0, 1 -> cast !C to int
6956         Value *NotCond =
6957           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6958                                                "not."+CondVal->getName()), SI);
6959         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6960       }
6961
6962       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6963
6964         // (x <s 0) ? -1 : 0 -> ashr x, 31
6965         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6966         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6967           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6968             bool CanXForm = false;
6969             if (IC->isSignedPredicate())
6970               CanXForm = CmpCst->isNullValue() && 
6971                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6972             else {
6973               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6974               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6975                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6976             }
6977             
6978             if (CanXForm) {
6979               // The comparison constant and the result are not neccessarily the
6980               // same width. Make an all-ones value by inserting a AShr.
6981               Value *X = IC->getOperand(0);
6982               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6983               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6984               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6985                                                         ShAmt, "ones");
6986               InsertNewInstBefore(SRA, SI);
6987               
6988               // Finally, convert to the type of the select RHS.  We figure out
6989               // if this requires a SExt, Trunc or BitCast based on the sizes.
6990               Instruction::CastOps opc = Instruction::BitCast;
6991               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6992               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6993               if (SRASize < SISize)
6994                 opc = Instruction::SExt;
6995               else if (SRASize > SISize)
6996                 opc = Instruction::Trunc;
6997               return CastInst::create(opc, SRA, SI.getType());
6998             }
6999           }
7000
7001
7002         // If one of the constants is zero (we know they can't both be) and we
7003         // have a fcmp instruction with zero, and we have an 'and' with the
7004         // non-constant value, eliminate this whole mess.  This corresponds to
7005         // cases like this: ((X & 27) ? 27 : 0)
7006         if (TrueValC->isNullValue() || FalseValC->isNullValue())
7007           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7008               cast<Constant>(IC->getOperand(1))->isNullValue())
7009             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7010               if (ICA->getOpcode() == Instruction::And &&
7011                   isa<ConstantInt>(ICA->getOperand(1)) &&
7012                   (ICA->getOperand(1) == TrueValC ||
7013                    ICA->getOperand(1) == FalseValC) &&
7014                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7015                 // Okay, now we know that everything is set up, we just don't
7016                 // know whether we have a icmp_ne or icmp_eq and whether the 
7017                 // true or false val is the zero.
7018                 bool ShouldNotVal = !TrueValC->isNullValue();
7019                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7020                 Value *V = ICA;
7021                 if (ShouldNotVal)
7022                   V = InsertNewInstBefore(BinaryOperator::create(
7023                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7024                 return ReplaceInstUsesWith(SI, V);
7025               }
7026       }
7027     }
7028
7029   // See if we are selecting two values based on a comparison of the two values.
7030   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7031     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7032       // Transform (X == Y) ? X : Y  -> Y
7033       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7034         return ReplaceInstUsesWith(SI, FalseVal);
7035       // Transform (X != Y) ? X : Y  -> X
7036       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7037         return ReplaceInstUsesWith(SI, TrueVal);
7038       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7039
7040     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7041       // Transform (X == Y) ? Y : X  -> X
7042       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7043         return ReplaceInstUsesWith(SI, FalseVal);
7044       // Transform (X != Y) ? Y : X  -> Y
7045       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7046         return ReplaceInstUsesWith(SI, TrueVal);
7047       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7048     }
7049   }
7050
7051   // See if we are selecting two values based on a comparison of the two values.
7052   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7053     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7054       // Transform (X == Y) ? X : Y  -> Y
7055       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7056         return ReplaceInstUsesWith(SI, FalseVal);
7057       // Transform (X != Y) ? X : Y  -> X
7058       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7059         return ReplaceInstUsesWith(SI, TrueVal);
7060       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7061
7062     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7063       // Transform (X == Y) ? Y : X  -> X
7064       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7065         return ReplaceInstUsesWith(SI, FalseVal);
7066       // Transform (X != Y) ? Y : X  -> Y
7067       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7068         return ReplaceInstUsesWith(SI, TrueVal);
7069       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7070     }
7071   }
7072
7073   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7074     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7075       if (TI->hasOneUse() && FI->hasOneUse()) {
7076         Instruction *AddOp = 0, *SubOp = 0;
7077
7078         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7079         if (TI->getOpcode() == FI->getOpcode())
7080           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7081             return IV;
7082
7083         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7084         // even legal for FP.
7085         if (TI->getOpcode() == Instruction::Sub &&
7086             FI->getOpcode() == Instruction::Add) {
7087           AddOp = FI; SubOp = TI;
7088         } else if (FI->getOpcode() == Instruction::Sub &&
7089                    TI->getOpcode() == Instruction::Add) {
7090           AddOp = TI; SubOp = FI;
7091         }
7092
7093         if (AddOp) {
7094           Value *OtherAddOp = 0;
7095           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7096             OtherAddOp = AddOp->getOperand(1);
7097           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7098             OtherAddOp = AddOp->getOperand(0);
7099           }
7100
7101           if (OtherAddOp) {
7102             // So at this point we know we have (Y -> OtherAddOp):
7103             //        select C, (add X, Y), (sub X, Z)
7104             Value *NegVal;  // Compute -Z
7105             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7106               NegVal = ConstantExpr::getNeg(C);
7107             } else {
7108               NegVal = InsertNewInstBefore(
7109                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7110             }
7111
7112             Value *NewTrueOp = OtherAddOp;
7113             Value *NewFalseOp = NegVal;
7114             if (AddOp != TI)
7115               std::swap(NewTrueOp, NewFalseOp);
7116             Instruction *NewSel =
7117               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7118
7119             NewSel = InsertNewInstBefore(NewSel, SI);
7120             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7121           }
7122         }
7123       }
7124
7125   // See if we can fold the select into one of our operands.
7126   if (SI.getType()->isInteger()) {
7127     // See the comment above GetSelectFoldableOperands for a description of the
7128     // transformation we are doing here.
7129     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7130       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7131           !isa<Constant>(FalseVal))
7132         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7133           unsigned OpToFold = 0;
7134           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7135             OpToFold = 1;
7136           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7137             OpToFold = 2;
7138           }
7139
7140           if (OpToFold) {
7141             Constant *C = GetSelectFoldableConstant(TVI);
7142             Instruction *NewSel =
7143               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7144             InsertNewInstBefore(NewSel, SI);
7145             NewSel->takeName(TVI);
7146             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7147               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7148             else {
7149               assert(0 && "Unknown instruction!!");
7150             }
7151           }
7152         }
7153
7154     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7155       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7156           !isa<Constant>(TrueVal))
7157         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7158           unsigned OpToFold = 0;
7159           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7160             OpToFold = 1;
7161           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7162             OpToFold = 2;
7163           }
7164
7165           if (OpToFold) {
7166             Constant *C = GetSelectFoldableConstant(FVI);
7167             Instruction *NewSel =
7168               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7169             InsertNewInstBefore(NewSel, SI);
7170             NewSel->takeName(FVI);
7171             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7172               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7173             else
7174               assert(0 && "Unknown instruction!!");
7175           }
7176         }
7177   }
7178
7179   if (BinaryOperator::isNot(CondVal)) {
7180     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7181     SI.setOperand(1, FalseVal);
7182     SI.setOperand(2, TrueVal);
7183     return &SI;
7184   }
7185
7186   return 0;
7187 }
7188
7189 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7190 /// determine, return it, otherwise return 0.
7191 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7192   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7193     unsigned Align = GV->getAlignment();
7194     if (Align == 0 && TD) 
7195       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7196     return Align;
7197   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7198     unsigned Align = AI->getAlignment();
7199     if (Align == 0 && TD) {
7200       if (isa<AllocaInst>(AI))
7201         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7202       else if (isa<MallocInst>(AI)) {
7203         // Malloc returns maximally aligned memory.
7204         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7205         Align =
7206           std::max(Align,
7207                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7208         Align =
7209           std::max(Align,
7210                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7211       }
7212     }
7213     return Align;
7214   } else if (isa<BitCastInst>(V) ||
7215              (isa<ConstantExpr>(V) && 
7216               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7217     User *CI = cast<User>(V);
7218     if (isa<PointerType>(CI->getOperand(0)->getType()))
7219       return GetKnownAlignment(CI->getOperand(0), TD);
7220     return 0;
7221   } else if (isa<GetElementPtrInst>(V) ||
7222              (isa<ConstantExpr>(V) && 
7223               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7224     User *GEPI = cast<User>(V);
7225     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7226     if (BaseAlignment == 0) return 0;
7227     
7228     // If all indexes are zero, it is just the alignment of the base pointer.
7229     bool AllZeroOperands = true;
7230     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7231       if (!isa<Constant>(GEPI->getOperand(i)) ||
7232           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7233         AllZeroOperands = false;
7234         break;
7235       }
7236     if (AllZeroOperands)
7237       return BaseAlignment;
7238     
7239     // Otherwise, if the base alignment is >= the alignment we expect for the
7240     // base pointer type, then we know that the resultant pointer is aligned at
7241     // least as much as its type requires.
7242     if (!TD) return 0;
7243
7244     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7245     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7246     if (TD->getABITypeAlignment(PtrTy->getElementType())
7247         <= BaseAlignment) {
7248       const Type *GEPTy = GEPI->getType();
7249       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7250       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7251     }
7252     return 0;
7253   }
7254   return 0;
7255 }
7256
7257
7258 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7259 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7260 /// the heavy lifting.
7261 ///
7262 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7263   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7264   if (!II) return visitCallSite(&CI);
7265   
7266   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7267   // visitCallSite.
7268   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7269     bool Changed = false;
7270
7271     // memmove/cpy/set of zero bytes is a noop.
7272     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7273       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7274
7275       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7276         if (CI->getZExtValue() == 1) {
7277           // Replace the instruction with just byte operations.  We would
7278           // transform other cases to loads/stores, but we don't know if
7279           // alignment is sufficient.
7280         }
7281     }
7282
7283     // If we have a memmove and the source operation is a constant global,
7284     // then the source and dest pointers can't alias, so we can change this
7285     // into a call to memcpy.
7286     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7287       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7288         if (GVSrc->isConstant()) {
7289           Module *M = CI.getParent()->getParent()->getParent();
7290           const char *Name;
7291           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7292               Type::Int32Ty)
7293             Name = "llvm.memcpy.i32";
7294           else
7295             Name = "llvm.memcpy.i64";
7296           Constant *MemCpy = M->getOrInsertFunction(Name,
7297                                      CI.getCalledFunction()->getFunctionType());
7298           CI.setOperand(0, MemCpy);
7299           Changed = true;
7300         }
7301     }
7302
7303     // If we can determine a pointer alignment that is bigger than currently
7304     // set, update the alignment.
7305     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7306       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7307       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7308       unsigned Align = std::min(Alignment1, Alignment2);
7309       if (MI->getAlignment()->getZExtValue() < Align) {
7310         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7311         Changed = true;
7312       }
7313     } else if (isa<MemSetInst>(MI)) {
7314       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7315       if (MI->getAlignment()->getZExtValue() < Alignment) {
7316         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7317         Changed = true;
7318       }
7319     }
7320           
7321     if (Changed) return II;
7322   } else {
7323     switch (II->getIntrinsicID()) {
7324     default: break;
7325     case Intrinsic::ppc_altivec_lvx:
7326     case Intrinsic::ppc_altivec_lvxl:
7327     case Intrinsic::x86_sse_loadu_ps:
7328     case Intrinsic::x86_sse2_loadu_pd:
7329     case Intrinsic::x86_sse2_loadu_dq:
7330       // Turn PPC lvx     -> load if the pointer is known aligned.
7331       // Turn X86 loadups -> load if the pointer is known aligned.
7332       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7333         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7334                                       PointerType::get(II->getType()), CI);
7335         return new LoadInst(Ptr);
7336       }
7337       break;
7338     case Intrinsic::ppc_altivec_stvx:
7339     case Intrinsic::ppc_altivec_stvxl:
7340       // Turn stvx -> store if the pointer is known aligned.
7341       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7342         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7343         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7344                                       OpPtrTy, CI);
7345         return new StoreInst(II->getOperand(1), Ptr);
7346       }
7347       break;
7348     case Intrinsic::x86_sse_storeu_ps:
7349     case Intrinsic::x86_sse2_storeu_pd:
7350     case Intrinsic::x86_sse2_storeu_dq:
7351     case Intrinsic::x86_sse2_storel_dq:
7352       // Turn X86 storeu -> store if the pointer is known aligned.
7353       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7354         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7355         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7356                                       OpPtrTy, CI);
7357         return new StoreInst(II->getOperand(2), Ptr);
7358       }
7359       break;
7360       
7361     case Intrinsic::x86_sse_cvttss2si: {
7362       // These intrinsics only demands the 0th element of its input vector.  If
7363       // we can simplify the input based on that, do so now.
7364       uint64_t UndefElts;
7365       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7366                                                 UndefElts)) {
7367         II->setOperand(1, V);
7368         return II;
7369       }
7370       break;
7371     }
7372       
7373     case Intrinsic::ppc_altivec_vperm:
7374       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7375       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7376         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7377         
7378         // Check that all of the elements are integer constants or undefs.
7379         bool AllEltsOk = true;
7380         for (unsigned i = 0; i != 16; ++i) {
7381           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7382               !isa<UndefValue>(Mask->getOperand(i))) {
7383             AllEltsOk = false;
7384             break;
7385           }
7386         }
7387         
7388         if (AllEltsOk) {
7389           // Cast the input vectors to byte vectors.
7390           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7391                                         II->getOperand(1), Mask->getType(), CI);
7392           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7393                                         II->getOperand(2), Mask->getType(), CI);
7394           Value *Result = UndefValue::get(Op0->getType());
7395           
7396           // Only extract each element once.
7397           Value *ExtractedElts[32];
7398           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7399           
7400           for (unsigned i = 0; i != 16; ++i) {
7401             if (isa<UndefValue>(Mask->getOperand(i)))
7402               continue;
7403             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7404             Idx &= 31;  // Match the hardware behavior.
7405             
7406             if (ExtractedElts[Idx] == 0) {
7407               Instruction *Elt = 
7408                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7409               InsertNewInstBefore(Elt, CI);
7410               ExtractedElts[Idx] = Elt;
7411             }
7412           
7413             // Insert this value into the result vector.
7414             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7415             InsertNewInstBefore(cast<Instruction>(Result), CI);
7416           }
7417           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7418         }
7419       }
7420       break;
7421
7422     case Intrinsic::stackrestore: {
7423       // If the save is right next to the restore, remove the restore.  This can
7424       // happen when variable allocas are DCE'd.
7425       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7426         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7427           BasicBlock::iterator BI = SS;
7428           if (&*++BI == II)
7429             return EraseInstFromFunction(CI);
7430         }
7431       }
7432       
7433       // If the stack restore is in a return/unwind block and if there are no
7434       // allocas or calls between the restore and the return, nuke the restore.
7435       TerminatorInst *TI = II->getParent()->getTerminator();
7436       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7437         BasicBlock::iterator BI = II;
7438         bool CannotRemove = false;
7439         for (++BI; &*BI != TI; ++BI) {
7440           if (isa<AllocaInst>(BI) ||
7441               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7442             CannotRemove = true;
7443             break;
7444           }
7445         }
7446         if (!CannotRemove)
7447           return EraseInstFromFunction(CI);
7448       }
7449       break;
7450     }
7451     }
7452   }
7453
7454   return visitCallSite(II);
7455 }
7456
7457 // InvokeInst simplification
7458 //
7459 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7460   return visitCallSite(&II);
7461 }
7462
7463 // visitCallSite - Improvements for call and invoke instructions.
7464 //
7465 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7466   bool Changed = false;
7467
7468   // If the callee is a constexpr cast of a function, attempt to move the cast
7469   // to the arguments of the call/invoke.
7470   if (transformConstExprCastCall(CS)) return 0;
7471
7472   Value *Callee = CS.getCalledValue();
7473
7474   if (Function *CalleeF = dyn_cast<Function>(Callee))
7475     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7476       Instruction *OldCall = CS.getInstruction();
7477       // If the call and callee calling conventions don't match, this call must
7478       // be unreachable, as the call is undefined.
7479       new StoreInst(ConstantInt::getTrue(),
7480                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7481       if (!OldCall->use_empty())
7482         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7483       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7484         return EraseInstFromFunction(*OldCall);
7485       return 0;
7486     }
7487
7488   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7489     // This instruction is not reachable, just remove it.  We insert a store to
7490     // undef so that we know that this code is not reachable, despite the fact
7491     // that we can't modify the CFG here.
7492     new StoreInst(ConstantInt::getTrue(),
7493                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7494                   CS.getInstruction());
7495
7496     if (!CS.getInstruction()->use_empty())
7497       CS.getInstruction()->
7498         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7499
7500     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7501       // Don't break the CFG, insert a dummy cond branch.
7502       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7503                      ConstantInt::getTrue(), II);
7504     }
7505     return EraseInstFromFunction(*CS.getInstruction());
7506   }
7507
7508   const PointerType *PTy = cast<PointerType>(Callee->getType());
7509   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7510   if (FTy->isVarArg()) {
7511     // See if we can optimize any arguments passed through the varargs area of
7512     // the call.
7513     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7514            E = CS.arg_end(); I != E; ++I)
7515       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7516         // If this cast does not effect the value passed through the varargs
7517         // area, we can eliminate the use of the cast.
7518         Value *Op = CI->getOperand(0);
7519         if (CI->isLosslessCast()) {
7520           *I = Op;
7521           Changed = true;
7522         }
7523       }
7524   }
7525
7526   return Changed ? CS.getInstruction() : 0;
7527 }
7528
7529 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7530 // attempt to move the cast to the arguments of the call/invoke.
7531 //
7532 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7533   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7534   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7535   if (CE->getOpcode() != Instruction::BitCast || 
7536       !isa<Function>(CE->getOperand(0)))
7537     return false;
7538   Function *Callee = cast<Function>(CE->getOperand(0));
7539   Instruction *Caller = CS.getInstruction();
7540
7541   // Okay, this is a cast from a function to a different type.  Unless doing so
7542   // would cause a type conversion of one of our arguments, change this call to
7543   // be a direct call with arguments casted to the appropriate types.
7544   //
7545   const FunctionType *FT = Callee->getFunctionType();
7546   const Type *OldRetTy = Caller->getType();
7547
7548   // Check to see if we are changing the return type...
7549   if (OldRetTy != FT->getReturnType()) {
7550     if (Callee->isDeclaration() && !Caller->use_empty() && 
7551         OldRetTy != FT->getReturnType() &&
7552         // Conversion is ok if changing from pointer to int of same size.
7553         !(isa<PointerType>(FT->getReturnType()) &&
7554           TD->getIntPtrType() == OldRetTy))
7555       return false;   // Cannot transform this return value.
7556
7557     // If the callsite is an invoke instruction, and the return value is used by
7558     // a PHI node in a successor, we cannot change the return type of the call
7559     // because there is no place to put the cast instruction (without breaking
7560     // the critical edge).  Bail out in this case.
7561     if (!Caller->use_empty())
7562       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7563         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7564              UI != E; ++UI)
7565           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7566             if (PN->getParent() == II->getNormalDest() ||
7567                 PN->getParent() == II->getUnwindDest())
7568               return false;
7569   }
7570
7571   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7572   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7573
7574   CallSite::arg_iterator AI = CS.arg_begin();
7575   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7576     const Type *ParamTy = FT->getParamType(i);
7577     const Type *ActTy = (*AI)->getType();
7578     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7579     //Either we can cast directly, or we can upconvert the argument
7580     bool isConvertible = ActTy == ParamTy ||
7581       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7582       (ParamTy->isInteger() && ActTy->isInteger() &&
7583        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7584       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7585        && c->getSExtValue() > 0);
7586     if (Callee->isDeclaration() && !isConvertible) return false;
7587   }
7588
7589   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7590       Callee->isDeclaration())
7591     return false;   // Do not delete arguments unless we have a function body...
7592
7593   // Okay, we decided that this is a safe thing to do: go ahead and start
7594   // inserting cast instructions as necessary...
7595   std::vector<Value*> Args;
7596   Args.reserve(NumActualArgs);
7597
7598   AI = CS.arg_begin();
7599   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7600     const Type *ParamTy = FT->getParamType(i);
7601     if ((*AI)->getType() == ParamTy) {
7602       Args.push_back(*AI);
7603     } else {
7604       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7605           false, ParamTy, false);
7606       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7607       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7608     }
7609   }
7610
7611   // If the function takes more arguments than the call was taking, add them
7612   // now...
7613   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7614     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7615
7616   // If we are removing arguments to the function, emit an obnoxious warning...
7617   if (FT->getNumParams() < NumActualArgs)
7618     if (!FT->isVarArg()) {
7619       cerr << "WARNING: While resolving call to function '"
7620            << Callee->getName() << "' arguments were dropped!\n";
7621     } else {
7622       // Add all of the arguments in their promoted form to the arg list...
7623       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7624         const Type *PTy = getPromotedType((*AI)->getType());
7625         if (PTy != (*AI)->getType()) {
7626           // Must promote to pass through va_arg area!
7627           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7628                                                                 PTy, false);
7629           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7630           InsertNewInstBefore(Cast, *Caller);
7631           Args.push_back(Cast);
7632         } else {
7633           Args.push_back(*AI);
7634         }
7635       }
7636     }
7637
7638   if (FT->getReturnType() == Type::VoidTy)
7639     Caller->setName("");   // Void type should not have a name.
7640
7641   Instruction *NC;
7642   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7643     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7644                         &Args[0], Args.size(), Caller->getName(), Caller);
7645     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7646   } else {
7647     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
7648     if (cast<CallInst>(Caller)->isTailCall())
7649       cast<CallInst>(NC)->setTailCall();
7650    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7651   }
7652
7653   // Insert a cast of the return type as necessary.
7654   Value *NV = NC;
7655   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7656     if (NV->getType() != Type::VoidTy) {
7657       const Type *CallerTy = Caller->getType();
7658       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7659                                                             CallerTy, false);
7660       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7661
7662       // If this is an invoke instruction, we should insert it after the first
7663       // non-phi, instruction in the normal successor block.
7664       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7665         BasicBlock::iterator I = II->getNormalDest()->begin();
7666         while (isa<PHINode>(I)) ++I;
7667         InsertNewInstBefore(NC, *I);
7668       } else {
7669         // Otherwise, it's a call, just insert cast right after the call instr
7670         InsertNewInstBefore(NC, *Caller);
7671       }
7672       AddUsersToWorkList(*Caller);
7673     } else {
7674       NV = UndefValue::get(Caller->getType());
7675     }
7676   }
7677
7678   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7679     Caller->replaceAllUsesWith(NV);
7680   Caller->eraseFromParent();
7681   RemoveFromWorkList(Caller);
7682   return true;
7683 }
7684
7685 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7686 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7687 /// and a single binop.
7688 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7689   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7690   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7691          isa<CmpInst>(FirstInst));
7692   unsigned Opc = FirstInst->getOpcode();
7693   Value *LHSVal = FirstInst->getOperand(0);
7694   Value *RHSVal = FirstInst->getOperand(1);
7695     
7696   const Type *LHSType = LHSVal->getType();
7697   const Type *RHSType = RHSVal->getType();
7698   
7699   // Scan to see if all operands are the same opcode, all have one use, and all
7700   // kill their operands (i.e. the operands have one use).
7701   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7702     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7703     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7704         // Verify type of the LHS matches so we don't fold cmp's of different
7705         // types or GEP's with different index types.
7706         I->getOperand(0)->getType() != LHSType ||
7707         I->getOperand(1)->getType() != RHSType)
7708       return 0;
7709
7710     // If they are CmpInst instructions, check their predicates
7711     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7712       if (cast<CmpInst>(I)->getPredicate() !=
7713           cast<CmpInst>(FirstInst)->getPredicate())
7714         return 0;
7715     
7716     // Keep track of which operand needs a phi node.
7717     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7718     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7719   }
7720   
7721   // Otherwise, this is safe to transform, determine if it is profitable.
7722
7723   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7724   // Indexes are often folded into load/store instructions, so we don't want to
7725   // hide them behind a phi.
7726   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7727     return 0;
7728   
7729   Value *InLHS = FirstInst->getOperand(0);
7730   Value *InRHS = FirstInst->getOperand(1);
7731   PHINode *NewLHS = 0, *NewRHS = 0;
7732   if (LHSVal == 0) {
7733     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7734     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7735     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7736     InsertNewInstBefore(NewLHS, PN);
7737     LHSVal = NewLHS;
7738   }
7739   
7740   if (RHSVal == 0) {
7741     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7742     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7743     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7744     InsertNewInstBefore(NewRHS, PN);
7745     RHSVal = NewRHS;
7746   }
7747   
7748   // Add all operands to the new PHIs.
7749   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7750     if (NewLHS) {
7751       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7752       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7753     }
7754     if (NewRHS) {
7755       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7756       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7757     }
7758   }
7759     
7760   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7761     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7762   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7763     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7764                            RHSVal);
7765   else {
7766     assert(isa<GetElementPtrInst>(FirstInst));
7767     return new GetElementPtrInst(LHSVal, RHSVal);
7768   }
7769 }
7770
7771 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7772 /// of the block that defines it.  This means that it must be obvious the value
7773 /// of the load is not changed from the point of the load to the end of the
7774 /// block it is in.
7775 ///
7776 /// Finally, it is safe, but not profitable, to sink a load targetting a
7777 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
7778 /// to a register.
7779 static bool isSafeToSinkLoad(LoadInst *L) {
7780   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7781   
7782   for (++BBI; BBI != E; ++BBI)
7783     if (BBI->mayWriteToMemory())
7784       return false;
7785   
7786   // Check for non-address taken alloca.  If not address-taken already, it isn't
7787   // profitable to do this xform.
7788   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7789     bool isAddressTaken = false;
7790     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7791          UI != E; ++UI) {
7792       if (isa<LoadInst>(UI)) continue;
7793       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7794         // If storing TO the alloca, then the address isn't taken.
7795         if (SI->getOperand(1) == AI) continue;
7796       }
7797       isAddressTaken = true;
7798       break;
7799     }
7800     
7801     if (!isAddressTaken)
7802       return false;
7803   }
7804   
7805   return true;
7806 }
7807
7808
7809 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7810 // operator and they all are only used by the PHI, PHI together their
7811 // inputs, and do the operation once, to the result of the PHI.
7812 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7813   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7814
7815   // Scan the instruction, looking for input operations that can be folded away.
7816   // If all input operands to the phi are the same instruction (e.g. a cast from
7817   // the same type or "+42") we can pull the operation through the PHI, reducing
7818   // code size and simplifying code.
7819   Constant *ConstantOp = 0;
7820   const Type *CastSrcTy = 0;
7821   bool isVolatile = false;
7822   if (isa<CastInst>(FirstInst)) {
7823     CastSrcTy = FirstInst->getOperand(0)->getType();
7824   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
7825     // Can fold binop, compare or shift here if the RHS is a constant, 
7826     // otherwise call FoldPHIArgBinOpIntoPHI.
7827     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7828     if (ConstantOp == 0)
7829       return FoldPHIArgBinOpIntoPHI(PN);
7830   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7831     isVolatile = LI->isVolatile();
7832     // We can't sink the load if the loaded value could be modified between the
7833     // load and the PHI.
7834     if (LI->getParent() != PN.getIncomingBlock(0) ||
7835         !isSafeToSinkLoad(LI))
7836       return 0;
7837   } else if (isa<GetElementPtrInst>(FirstInst)) {
7838     if (FirstInst->getNumOperands() == 2)
7839       return FoldPHIArgBinOpIntoPHI(PN);
7840     // Can't handle general GEPs yet.
7841     return 0;
7842   } else {
7843     return 0;  // Cannot fold this operation.
7844   }
7845
7846   // Check to see if all arguments are the same operation.
7847   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7848     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7849     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7850     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7851       return 0;
7852     if (CastSrcTy) {
7853       if (I->getOperand(0)->getType() != CastSrcTy)
7854         return 0;  // Cast operation must match.
7855     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7856       // We can't sink the load if the loaded value could be modified between 
7857       // the load and the PHI.
7858       if (LI->isVolatile() != isVolatile ||
7859           LI->getParent() != PN.getIncomingBlock(i) ||
7860           !isSafeToSinkLoad(LI))
7861         return 0;
7862     } else if (I->getOperand(1) != ConstantOp) {
7863       return 0;
7864     }
7865   }
7866
7867   // Okay, they are all the same operation.  Create a new PHI node of the
7868   // correct type, and PHI together all of the LHS's of the instructions.
7869   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7870                                PN.getName()+".in");
7871   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7872
7873   Value *InVal = FirstInst->getOperand(0);
7874   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7875
7876   // Add all operands to the new PHI.
7877   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7878     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7879     if (NewInVal != InVal)
7880       InVal = 0;
7881     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7882   }
7883
7884   Value *PhiVal;
7885   if (InVal) {
7886     // The new PHI unions all of the same values together.  This is really
7887     // common, so we handle it intelligently here for compile-time speed.
7888     PhiVal = InVal;
7889     delete NewPN;
7890   } else {
7891     InsertNewInstBefore(NewPN, PN);
7892     PhiVal = NewPN;
7893   }
7894
7895   // Insert and return the new operation.
7896   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7897     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7898   else if (isa<LoadInst>(FirstInst))
7899     return new LoadInst(PhiVal, "", isVolatile);
7900   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7901     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7902   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7903     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7904                            PhiVal, ConstantOp);
7905   else
7906     assert(0 && "Unknown operation");
7907   return 0;
7908 }
7909
7910 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7911 /// that is dead.
7912 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7913   if (PN->use_empty()) return true;
7914   if (!PN->hasOneUse()) return false;
7915
7916   // Remember this node, and if we find the cycle, return.
7917   if (!PotentiallyDeadPHIs.insert(PN).second)
7918     return true;
7919
7920   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7921     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7922
7923   return false;
7924 }
7925
7926 // PHINode simplification
7927 //
7928 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7929   // If LCSSA is around, don't mess with Phi nodes
7930   if (MustPreserveLCSSA) return 0;
7931   
7932   if (Value *V = PN.hasConstantValue())
7933     return ReplaceInstUsesWith(PN, V);
7934
7935   // If all PHI operands are the same operation, pull them through the PHI,
7936   // reducing code size.
7937   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7938       PN.getIncomingValue(0)->hasOneUse())
7939     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7940       return Result;
7941
7942   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7943   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7944   // PHI)... break the cycle.
7945   if (PN.hasOneUse()) {
7946     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7947     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7948       std::set<PHINode*> PotentiallyDeadPHIs;
7949       PotentiallyDeadPHIs.insert(&PN);
7950       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7951         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7952     }
7953    
7954     // If this phi has a single use, and if that use just computes a value for
7955     // the next iteration of a loop, delete the phi.  This occurs with unused
7956     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7957     // common case here is good because the only other things that catch this
7958     // are induction variable analysis (sometimes) and ADCE, which is only run
7959     // late.
7960     if (PHIUser->hasOneUse() &&
7961         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7962         PHIUser->use_back() == &PN) {
7963       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7964     }
7965   }
7966
7967   return 0;
7968 }
7969
7970 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7971                                    Instruction *InsertPoint,
7972                                    InstCombiner *IC) {
7973   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7974   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7975   // We must cast correctly to the pointer type. Ensure that we
7976   // sign extend the integer value if it is smaller as this is
7977   // used for address computation.
7978   Instruction::CastOps opcode = 
7979      (VTySize < PtrSize ? Instruction::SExt :
7980       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7981   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7982 }
7983
7984
7985 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7986   Value *PtrOp = GEP.getOperand(0);
7987   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7988   // If so, eliminate the noop.
7989   if (GEP.getNumOperands() == 1)
7990     return ReplaceInstUsesWith(GEP, PtrOp);
7991
7992   if (isa<UndefValue>(GEP.getOperand(0)))
7993     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7994
7995   bool HasZeroPointerIndex = false;
7996   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7997     HasZeroPointerIndex = C->isNullValue();
7998
7999   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8000     return ReplaceInstUsesWith(GEP, PtrOp);
8001
8002   // Eliminate unneeded casts for indices.
8003   bool MadeChange = false;
8004   gep_type_iterator GTI = gep_type_begin(GEP);
8005   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8006     if (isa<SequentialType>(*GTI)) {
8007       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8008         if (CI->getOpcode() == Instruction::ZExt ||
8009             CI->getOpcode() == Instruction::SExt) {
8010           const Type *SrcTy = CI->getOperand(0)->getType();
8011           // We can eliminate a cast from i32 to i64 iff the target 
8012           // is a 32-bit pointer target.
8013           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8014             MadeChange = true;
8015             GEP.setOperand(i, CI->getOperand(0));
8016           }
8017         }
8018       }
8019       // If we are using a wider index than needed for this platform, shrink it
8020       // to what we need.  If the incoming value needs a cast instruction,
8021       // insert it.  This explicit cast can make subsequent optimizations more
8022       // obvious.
8023       Value *Op = GEP.getOperand(i);
8024       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8025         if (Constant *C = dyn_cast<Constant>(Op)) {
8026           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8027           MadeChange = true;
8028         } else {
8029           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8030                                 GEP);
8031           GEP.setOperand(i, Op);
8032           MadeChange = true;
8033         }
8034     }
8035   if (MadeChange) return &GEP;
8036
8037   // Combine Indices - If the source pointer to this getelementptr instruction
8038   // is a getelementptr instruction, combine the indices of the two
8039   // getelementptr instructions into a single instruction.
8040   //
8041   SmallVector<Value*, 8> SrcGEPOperands;
8042   if (User *Src = dyn_castGetElementPtr(PtrOp))
8043     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8044
8045   if (!SrcGEPOperands.empty()) {
8046     // Note that if our source is a gep chain itself that we wait for that
8047     // chain to be resolved before we perform this transformation.  This
8048     // avoids us creating a TON of code in some cases.
8049     //
8050     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8051         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8052       return 0;   // Wait until our source is folded to completion.
8053
8054     SmallVector<Value*, 8> Indices;
8055
8056     // Find out whether the last index in the source GEP is a sequential idx.
8057     bool EndsWithSequential = false;
8058     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8059            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8060       EndsWithSequential = !isa<StructType>(*I);
8061
8062     // Can we combine the two pointer arithmetics offsets?
8063     if (EndsWithSequential) {
8064       // Replace: gep (gep %P, long B), long A, ...
8065       // With:    T = long A+B; gep %P, T, ...
8066       //
8067       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8068       if (SO1 == Constant::getNullValue(SO1->getType())) {
8069         Sum = GO1;
8070       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8071         Sum = SO1;
8072       } else {
8073         // If they aren't the same type, convert both to an integer of the
8074         // target's pointer size.
8075         if (SO1->getType() != GO1->getType()) {
8076           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8077             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8078           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8079             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8080           } else {
8081             unsigned PS = TD->getPointerSize();
8082             if (TD->getTypeSize(SO1->getType()) == PS) {
8083               // Convert GO1 to SO1's type.
8084               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8085
8086             } else if (TD->getTypeSize(GO1->getType()) == PS) {
8087               // Convert SO1 to GO1's type.
8088               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8089             } else {
8090               const Type *PT = TD->getIntPtrType();
8091               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8092               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8093             }
8094           }
8095         }
8096         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8097           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8098         else {
8099           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8100           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8101         }
8102       }
8103
8104       // Recycle the GEP we already have if possible.
8105       if (SrcGEPOperands.size() == 2) {
8106         GEP.setOperand(0, SrcGEPOperands[0]);
8107         GEP.setOperand(1, Sum);
8108         return &GEP;
8109       } else {
8110         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8111                        SrcGEPOperands.end()-1);
8112         Indices.push_back(Sum);
8113         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8114       }
8115     } else if (isa<Constant>(*GEP.idx_begin()) &&
8116                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8117                SrcGEPOperands.size() != 1) {
8118       // Otherwise we can do the fold if the first index of the GEP is a zero
8119       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8120                      SrcGEPOperands.end());
8121       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8122     }
8123
8124     if (!Indices.empty())
8125       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8126                                    Indices.size(), GEP.getName());
8127
8128   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8129     // GEP of global variable.  If all of the indices for this GEP are
8130     // constants, we can promote this to a constexpr instead of an instruction.
8131
8132     // Scan for nonconstants...
8133     SmallVector<Constant*, 8> Indices;
8134     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8135     for (; I != E && isa<Constant>(*I); ++I)
8136       Indices.push_back(cast<Constant>(*I));
8137
8138     if (I == E) {  // If they are all constants...
8139       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8140                                                     &Indices[0],Indices.size());
8141
8142       // Replace all uses of the GEP with the new constexpr...
8143       return ReplaceInstUsesWith(GEP, CE);
8144     }
8145   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8146     if (!isa<PointerType>(X->getType())) {
8147       // Not interesting.  Source pointer must be a cast from pointer.
8148     } else if (HasZeroPointerIndex) {
8149       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8150       // into     : GEP [10 x ubyte]* X, long 0, ...
8151       //
8152       // This occurs when the program declares an array extern like "int X[];"
8153       //
8154       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8155       const PointerType *XTy = cast<PointerType>(X->getType());
8156       if (const ArrayType *XATy =
8157           dyn_cast<ArrayType>(XTy->getElementType()))
8158         if (const ArrayType *CATy =
8159             dyn_cast<ArrayType>(CPTy->getElementType()))
8160           if (CATy->getElementType() == XATy->getElementType()) {
8161             // At this point, we know that the cast source type is a pointer
8162             // to an array of the same type as the destination pointer
8163             // array.  Because the array type is never stepped over (there
8164             // is a leading zero) we can fold the cast into this GEP.
8165             GEP.setOperand(0, X);
8166             return &GEP;
8167           }
8168     } else if (GEP.getNumOperands() == 2) {
8169       // Transform things like:
8170       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8171       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8172       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8173       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8174       if (isa<ArrayType>(SrcElTy) &&
8175           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8176           TD->getTypeSize(ResElTy)) {
8177         Value *V = InsertNewInstBefore(
8178                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8179                                      GEP.getOperand(1), GEP.getName()), GEP);
8180         // V and GEP are both pointer types --> BitCast
8181         return new BitCastInst(V, GEP.getType());
8182       }
8183       
8184       // Transform things like:
8185       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8186       //   (where tmp = 8*tmp2) into:
8187       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8188       
8189       if (isa<ArrayType>(SrcElTy) &&
8190           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8191         uint64_t ArrayEltSize =
8192             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8193         
8194         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
8195         // allow either a mul, shift, or constant here.
8196         Value *NewIdx = 0;
8197         ConstantInt *Scale = 0;
8198         if (ArrayEltSize == 1) {
8199           NewIdx = GEP.getOperand(1);
8200           Scale = ConstantInt::get(NewIdx->getType(), 1);
8201         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8202           NewIdx = ConstantInt::get(CI->getType(), 1);
8203           Scale = CI;
8204         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8205           if (Inst->getOpcode() == Instruction::Shl &&
8206               isa<ConstantInt>(Inst->getOperand(1))) {
8207             unsigned ShAmt =
8208               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
8209             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
8210             NewIdx = Inst->getOperand(0);
8211           } else if (Inst->getOpcode() == Instruction::Mul &&
8212                      isa<ConstantInt>(Inst->getOperand(1))) {
8213             Scale = cast<ConstantInt>(Inst->getOperand(1));
8214             NewIdx = Inst->getOperand(0);
8215           }
8216         }
8217
8218         // If the index will be to exactly the right offset with the scale taken
8219         // out, perform the transformation.
8220         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8221           if (isa<ConstantInt>(Scale))
8222             Scale = ConstantInt::get(Scale->getType(),
8223                                       Scale->getZExtValue() / ArrayEltSize);
8224           if (Scale->getZExtValue() != 1) {
8225             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8226                                                        true /*SExt*/);
8227             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8228             NewIdx = InsertNewInstBefore(Sc, GEP);
8229           }
8230
8231           // Insert the new GEP instruction.
8232           Instruction *NewGEP =
8233             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8234                                   NewIdx, GEP.getName());
8235           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8236           // The NewGEP must be pointer typed, so must the old one -> BitCast
8237           return new BitCastInst(NewGEP, GEP.getType());
8238         }
8239       }
8240     }
8241   }
8242
8243   return 0;
8244 }
8245
8246 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8247   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8248   if (AI.isArrayAllocation())    // Check C != 1
8249     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8250       const Type *NewTy = 
8251         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8252       AllocationInst *New = 0;
8253
8254       // Create and insert the replacement instruction...
8255       if (isa<MallocInst>(AI))
8256         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8257       else {
8258         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8259         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8260       }
8261
8262       InsertNewInstBefore(New, AI);
8263
8264       // Scan to the end of the allocation instructions, to skip over a block of
8265       // allocas if possible...
8266       //
8267       BasicBlock::iterator It = New;
8268       while (isa<AllocationInst>(*It)) ++It;
8269
8270       // Now that I is pointing to the first non-allocation-inst in the block,
8271       // insert our getelementptr instruction...
8272       //
8273       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8274       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8275                                        New->getName()+".sub", It);
8276
8277       // Now make everything use the getelementptr instead of the original
8278       // allocation.
8279       return ReplaceInstUsesWith(AI, V);
8280     } else if (isa<UndefValue>(AI.getArraySize())) {
8281       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8282     }
8283
8284   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8285   // Note that we only do this for alloca's, because malloc should allocate and
8286   // return a unique pointer, even for a zero byte allocation.
8287   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8288       TD->getTypeSize(AI.getAllocatedType()) == 0)
8289     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8290
8291   return 0;
8292 }
8293
8294 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8295   Value *Op = FI.getOperand(0);
8296
8297   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8298   if (CastInst *CI = dyn_cast<CastInst>(Op))
8299     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8300       FI.setOperand(0, CI->getOperand(0));
8301       return &FI;
8302     }
8303
8304   // free undef -> unreachable.
8305   if (isa<UndefValue>(Op)) {
8306     // Insert a new store to null because we cannot modify the CFG here.
8307     new StoreInst(ConstantInt::getTrue(),
8308                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8309     return EraseInstFromFunction(FI);
8310   }
8311
8312   // If we have 'free null' delete the instruction.  This can happen in stl code
8313   // when lots of inlining happens.
8314   if (isa<ConstantPointerNull>(Op))
8315     return EraseInstFromFunction(FI);
8316
8317   return 0;
8318 }
8319
8320
8321 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8322 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8323   User *CI = cast<User>(LI.getOperand(0));
8324   Value *CastOp = CI->getOperand(0);
8325
8326   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8327   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8328     const Type *SrcPTy = SrcTy->getElementType();
8329
8330     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8331          isa<VectorType>(DestPTy)) {
8332       // If the source is an array, the code below will not succeed.  Check to
8333       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8334       // constants.
8335       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8336         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8337           if (ASrcTy->getNumElements() != 0) {
8338             Value *Idxs[2];
8339             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8340             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8341             SrcTy = cast<PointerType>(CastOp->getType());
8342             SrcPTy = SrcTy->getElementType();
8343           }
8344
8345       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8346             isa<VectorType>(SrcPTy)) &&
8347           // Do not allow turning this into a load of an integer, which is then
8348           // casted to a pointer, this pessimizes pointer analysis a lot.
8349           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8350           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8351                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8352
8353         // Okay, we are casting from one integer or pointer type to another of
8354         // the same size.  Instead of casting the pointer before the load, cast
8355         // the result of the loaded value.
8356         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8357                                                              CI->getName(),
8358                                                          LI.isVolatile()),LI);
8359         // Now cast the result of the load.
8360         return new BitCastInst(NewLoad, LI.getType());
8361       }
8362     }
8363   }
8364   return 0;
8365 }
8366
8367 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8368 /// from this value cannot trap.  If it is not obviously safe to load from the
8369 /// specified pointer, we do a quick local scan of the basic block containing
8370 /// ScanFrom, to determine if the address is already accessed.
8371 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8372   // If it is an alloca or global variable, it is always safe to load from.
8373   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8374
8375   // Otherwise, be a little bit agressive by scanning the local block where we
8376   // want to check to see if the pointer is already being loaded or stored
8377   // from/to.  If so, the previous load or store would have already trapped,
8378   // so there is no harm doing an extra load (also, CSE will later eliminate
8379   // the load entirely).
8380   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8381
8382   while (BBI != E) {
8383     --BBI;
8384
8385     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8386       if (LI->getOperand(0) == V) return true;
8387     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8388       if (SI->getOperand(1) == V) return true;
8389
8390   }
8391   return false;
8392 }
8393
8394 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8395   Value *Op = LI.getOperand(0);
8396
8397   // load (cast X) --> cast (load X) iff safe
8398   if (isa<CastInst>(Op))
8399     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8400       return Res;
8401
8402   // None of the following transforms are legal for volatile loads.
8403   if (LI.isVolatile()) return 0;
8404   
8405   if (&LI.getParent()->front() != &LI) {
8406     BasicBlock::iterator BBI = &LI; --BBI;
8407     // If the instruction immediately before this is a store to the same
8408     // address, do a simple form of store->load forwarding.
8409     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8410       if (SI->getOperand(1) == LI.getOperand(0))
8411         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8412     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8413       if (LIB->getOperand(0) == LI.getOperand(0))
8414         return ReplaceInstUsesWith(LI, LIB);
8415   }
8416
8417   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8418     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8419         isa<UndefValue>(GEPI->getOperand(0))) {
8420       // Insert a new store to null instruction before the load to indicate
8421       // that this code is not reachable.  We do this instead of inserting
8422       // an unreachable instruction directly because we cannot modify the
8423       // CFG.
8424       new StoreInst(UndefValue::get(LI.getType()),
8425                     Constant::getNullValue(Op->getType()), &LI);
8426       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8427     }
8428
8429   if (Constant *C = dyn_cast<Constant>(Op)) {
8430     // load null/undef -> undef
8431     if ((C->isNullValue() || isa<UndefValue>(C))) {
8432       // Insert a new store to null instruction before the load to indicate that
8433       // this code is not reachable.  We do this instead of inserting an
8434       // unreachable instruction directly because we cannot modify the CFG.
8435       new StoreInst(UndefValue::get(LI.getType()),
8436                     Constant::getNullValue(Op->getType()), &LI);
8437       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8438     }
8439
8440     // Instcombine load (constant global) into the value loaded.
8441     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8442       if (GV->isConstant() && !GV->isDeclaration())
8443         return ReplaceInstUsesWith(LI, GV->getInitializer());
8444
8445     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8446     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8447       if (CE->getOpcode() == Instruction::GetElementPtr) {
8448         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8449           if (GV->isConstant() && !GV->isDeclaration())
8450             if (Constant *V = 
8451                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8452               return ReplaceInstUsesWith(LI, V);
8453         if (CE->getOperand(0)->isNullValue()) {
8454           // Insert a new store to null instruction before the load to indicate
8455           // that this code is not reachable.  We do this instead of inserting
8456           // an unreachable instruction directly because we cannot modify the
8457           // CFG.
8458           new StoreInst(UndefValue::get(LI.getType()),
8459                         Constant::getNullValue(Op->getType()), &LI);
8460           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8461         }
8462
8463       } else if (CE->isCast()) {
8464         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8465           return Res;
8466       }
8467   }
8468
8469   if (Op->hasOneUse()) {
8470     // Change select and PHI nodes to select values instead of addresses: this
8471     // helps alias analysis out a lot, allows many others simplifications, and
8472     // exposes redundancy in the code.
8473     //
8474     // Note that we cannot do the transformation unless we know that the
8475     // introduced loads cannot trap!  Something like this is valid as long as
8476     // the condition is always false: load (select bool %C, int* null, int* %G),
8477     // but it would not be valid if we transformed it to load from null
8478     // unconditionally.
8479     //
8480     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8481       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8482       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8483           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8484         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8485                                      SI->getOperand(1)->getName()+".val"), LI);
8486         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8487                                      SI->getOperand(2)->getName()+".val"), LI);
8488         return new SelectInst(SI->getCondition(), V1, V2);
8489       }
8490
8491       // load (select (cond, null, P)) -> load P
8492       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8493         if (C->isNullValue()) {
8494           LI.setOperand(0, SI->getOperand(2));
8495           return &LI;
8496         }
8497
8498       // load (select (cond, P, null)) -> load P
8499       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8500         if (C->isNullValue()) {
8501           LI.setOperand(0, SI->getOperand(1));
8502           return &LI;
8503         }
8504     }
8505   }
8506   return 0;
8507 }
8508
8509 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8510 /// when possible.
8511 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8512   User *CI = cast<User>(SI.getOperand(1));
8513   Value *CastOp = CI->getOperand(0);
8514
8515   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8516   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8517     const Type *SrcPTy = SrcTy->getElementType();
8518
8519     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8520       // If the source is an array, the code below will not succeed.  Check to
8521       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8522       // constants.
8523       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8524         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8525           if (ASrcTy->getNumElements() != 0) {
8526             Value* Idxs[2];
8527             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8528             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8529             SrcTy = cast<PointerType>(CastOp->getType());
8530             SrcPTy = SrcTy->getElementType();
8531           }
8532
8533       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8534           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8535                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8536
8537         // Okay, we are casting from one integer or pointer type to another of
8538         // the same size.  Instead of casting the pointer before 
8539         // the store, cast the value to be stored.
8540         Value *NewCast;
8541         Value *SIOp0 = SI.getOperand(0);
8542         Instruction::CastOps opcode = Instruction::BitCast;
8543         const Type* CastSrcTy = SIOp0->getType();
8544         const Type* CastDstTy = SrcPTy;
8545         if (isa<PointerType>(CastDstTy)) {
8546           if (CastSrcTy->isInteger())
8547             opcode = Instruction::IntToPtr;
8548         } else if (isa<IntegerType>(CastDstTy)) {
8549           if (isa<PointerType>(SIOp0->getType()))
8550             opcode = Instruction::PtrToInt;
8551         }
8552         if (Constant *C = dyn_cast<Constant>(SIOp0))
8553           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8554         else
8555           NewCast = IC.InsertNewInstBefore(
8556             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8557             SI);
8558         return new StoreInst(NewCast, CastOp);
8559       }
8560     }
8561   }
8562   return 0;
8563 }
8564
8565 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8566   Value *Val = SI.getOperand(0);
8567   Value *Ptr = SI.getOperand(1);
8568
8569   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8570     EraseInstFromFunction(SI);
8571     ++NumCombined;
8572     return 0;
8573   }
8574   
8575   // If the RHS is an alloca with a single use, zapify the store, making the
8576   // alloca dead.
8577   if (Ptr->hasOneUse()) {
8578     if (isa<AllocaInst>(Ptr)) {
8579       EraseInstFromFunction(SI);
8580       ++NumCombined;
8581       return 0;
8582     }
8583     
8584     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8585       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8586           GEP->getOperand(0)->hasOneUse()) {
8587         EraseInstFromFunction(SI);
8588         ++NumCombined;
8589         return 0;
8590       }
8591   }
8592
8593   // Do really simple DSE, to catch cases where there are several consequtive
8594   // stores to the same location, separated by a few arithmetic operations. This
8595   // situation often occurs with bitfield accesses.
8596   BasicBlock::iterator BBI = &SI;
8597   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8598        --ScanInsts) {
8599     --BBI;
8600     
8601     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8602       // Prev store isn't volatile, and stores to the same location?
8603       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8604         ++NumDeadStore;
8605         ++BBI;
8606         EraseInstFromFunction(*PrevSI);
8607         continue;
8608       }
8609       break;
8610     }
8611     
8612     // If this is a load, we have to stop.  However, if the loaded value is from
8613     // the pointer we're loading and is producing the pointer we're storing,
8614     // then *this* store is dead (X = load P; store X -> P).
8615     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8616       if (LI == Val && LI->getOperand(0) == Ptr) {
8617         EraseInstFromFunction(SI);
8618         ++NumCombined;
8619         return 0;
8620       }
8621       // Otherwise, this is a load from some other location.  Stores before it
8622       // may not be dead.
8623       break;
8624     }
8625     
8626     // Don't skip over loads or things that can modify memory.
8627     if (BBI->mayWriteToMemory())
8628       break;
8629   }
8630   
8631   
8632   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8633
8634   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8635   if (isa<ConstantPointerNull>(Ptr)) {
8636     if (!isa<UndefValue>(Val)) {
8637       SI.setOperand(0, UndefValue::get(Val->getType()));
8638       if (Instruction *U = dyn_cast<Instruction>(Val))
8639         AddToWorkList(U);  // Dropped a use.
8640       ++NumCombined;
8641     }
8642     return 0;  // Do not modify these!
8643   }
8644
8645   // store undef, Ptr -> noop
8646   if (isa<UndefValue>(Val)) {
8647     EraseInstFromFunction(SI);
8648     ++NumCombined;
8649     return 0;
8650   }
8651
8652   // If the pointer destination is a cast, see if we can fold the cast into the
8653   // source instead.
8654   if (isa<CastInst>(Ptr))
8655     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8656       return Res;
8657   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8658     if (CE->isCast())
8659       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8660         return Res;
8661
8662   
8663   // If this store is the last instruction in the basic block, and if the block
8664   // ends with an unconditional branch, try to move it to the successor block.
8665   BBI = &SI; ++BBI;
8666   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8667     if (BI->isUnconditional()) {
8668       // Check to see if the successor block has exactly two incoming edges.  If
8669       // so, see if the other predecessor contains a store to the same location.
8670       // if so, insert a PHI node (if needed) and move the stores down.
8671       BasicBlock *Dest = BI->getSuccessor(0);
8672
8673       pred_iterator PI = pred_begin(Dest);
8674       BasicBlock *Other = 0;
8675       if (*PI != BI->getParent())
8676         Other = *PI;
8677       ++PI;
8678       if (PI != pred_end(Dest)) {
8679         if (*PI != BI->getParent())
8680           if (Other)
8681             Other = 0;
8682           else
8683             Other = *PI;
8684         if (++PI != pred_end(Dest))
8685           Other = 0;
8686       }
8687       if (Other) {  // If only one other pred...
8688         BBI = Other->getTerminator();
8689         // Make sure this other block ends in an unconditional branch and that
8690         // there is an instruction before the branch.
8691         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8692             BBI != Other->begin()) {
8693           --BBI;
8694           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8695           
8696           // If this instruction is a store to the same location.
8697           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8698             // Okay, we know we can perform this transformation.  Insert a PHI
8699             // node now if we need it.
8700             Value *MergedVal = OtherStore->getOperand(0);
8701             if (MergedVal != SI.getOperand(0)) {
8702               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8703               PN->reserveOperandSpace(2);
8704               PN->addIncoming(SI.getOperand(0), SI.getParent());
8705               PN->addIncoming(OtherStore->getOperand(0), Other);
8706               MergedVal = InsertNewInstBefore(PN, Dest->front());
8707             }
8708             
8709             // Advance to a place where it is safe to insert the new store and
8710             // insert it.
8711             BBI = Dest->begin();
8712             while (isa<PHINode>(BBI)) ++BBI;
8713             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8714                                               OtherStore->isVolatile()), *BBI);
8715
8716             // Nuke the old stores.
8717             EraseInstFromFunction(SI);
8718             EraseInstFromFunction(*OtherStore);
8719             ++NumCombined;
8720             return 0;
8721           }
8722         }
8723       }
8724     }
8725   
8726   return 0;
8727 }
8728
8729
8730 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8731   // Change br (not X), label True, label False to: br X, label False, True
8732   Value *X = 0;
8733   BasicBlock *TrueDest;
8734   BasicBlock *FalseDest;
8735   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8736       !isa<Constant>(X)) {
8737     // Swap Destinations and condition...
8738     BI.setCondition(X);
8739     BI.setSuccessor(0, FalseDest);
8740     BI.setSuccessor(1, TrueDest);
8741     return &BI;
8742   }
8743
8744   // Cannonicalize fcmp_one -> fcmp_oeq
8745   FCmpInst::Predicate FPred; Value *Y;
8746   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8747                              TrueDest, FalseDest)))
8748     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8749          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8750       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8751       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8752       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8753       NewSCC->takeName(I);
8754       // Swap Destinations and condition...
8755       BI.setCondition(NewSCC);
8756       BI.setSuccessor(0, FalseDest);
8757       BI.setSuccessor(1, TrueDest);
8758       RemoveFromWorkList(I);
8759       I->eraseFromParent();
8760       AddToWorkList(NewSCC);
8761       return &BI;
8762     }
8763
8764   // Cannonicalize icmp_ne -> icmp_eq
8765   ICmpInst::Predicate IPred;
8766   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8767                       TrueDest, FalseDest)))
8768     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8769          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8770          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8771       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8772       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8773       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8774       NewSCC->takeName(I);
8775       // Swap Destinations and condition...
8776       BI.setCondition(NewSCC);
8777       BI.setSuccessor(0, FalseDest);
8778       BI.setSuccessor(1, TrueDest);
8779       RemoveFromWorkList(I);
8780       I->eraseFromParent();;
8781       AddToWorkList(NewSCC);
8782       return &BI;
8783     }
8784
8785   return 0;
8786 }
8787
8788 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8789   Value *Cond = SI.getCondition();
8790   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8791     if (I->getOpcode() == Instruction::Add)
8792       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8793         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8794         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8795           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8796                                                 AddRHS));
8797         SI.setOperand(0, I->getOperand(0));
8798         AddToWorkList(I);
8799         return &SI;
8800       }
8801   }
8802   return 0;
8803 }
8804
8805 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8806 /// is to leave as a vector operation.
8807 static bool CheapToScalarize(Value *V, bool isConstant) {
8808   if (isa<ConstantAggregateZero>(V)) 
8809     return true;
8810   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
8811     if (isConstant) return true;
8812     // If all elts are the same, we can extract.
8813     Constant *Op0 = C->getOperand(0);
8814     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8815       if (C->getOperand(i) != Op0)
8816         return false;
8817     return true;
8818   }
8819   Instruction *I = dyn_cast<Instruction>(V);
8820   if (!I) return false;
8821   
8822   // Insert element gets simplified to the inserted element or is deleted if
8823   // this is constant idx extract element and its a constant idx insertelt.
8824   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8825       isa<ConstantInt>(I->getOperand(2)))
8826     return true;
8827   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8828     return true;
8829   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8830     if (BO->hasOneUse() &&
8831         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8832          CheapToScalarize(BO->getOperand(1), isConstant)))
8833       return true;
8834   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8835     if (CI->hasOneUse() &&
8836         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8837          CheapToScalarize(CI->getOperand(1), isConstant)))
8838       return true;
8839   
8840   return false;
8841 }
8842
8843 /// Read and decode a shufflevector mask.
8844 ///
8845 /// It turns undef elements into values that are larger than the number of
8846 /// elements in the input.
8847 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8848   unsigned NElts = SVI->getType()->getNumElements();
8849   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8850     return std::vector<unsigned>(NElts, 0);
8851   if (isa<UndefValue>(SVI->getOperand(2)))
8852     return std::vector<unsigned>(NElts, 2*NElts);
8853
8854   std::vector<unsigned> Result;
8855   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
8856   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8857     if (isa<UndefValue>(CP->getOperand(i)))
8858       Result.push_back(NElts*2);  // undef -> 8
8859     else
8860       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8861   return Result;
8862 }
8863
8864 /// FindScalarElement - Given a vector and an element number, see if the scalar
8865 /// value is already around as a register, for example if it were inserted then
8866 /// extracted from the vector.
8867 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8868   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8869   const VectorType *PTy = cast<VectorType>(V->getType());
8870   unsigned Width = PTy->getNumElements();
8871   if (EltNo >= Width)  // Out of range access.
8872     return UndefValue::get(PTy->getElementType());
8873   
8874   if (isa<UndefValue>(V))
8875     return UndefValue::get(PTy->getElementType());
8876   else if (isa<ConstantAggregateZero>(V))
8877     return Constant::getNullValue(PTy->getElementType());
8878   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
8879     return CP->getOperand(EltNo);
8880   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8881     // If this is an insert to a variable element, we don't know what it is.
8882     if (!isa<ConstantInt>(III->getOperand(2))) 
8883       return 0;
8884     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8885     
8886     // If this is an insert to the element we are looking for, return the
8887     // inserted value.
8888     if (EltNo == IIElt) 
8889       return III->getOperand(1);
8890     
8891     // Otherwise, the insertelement doesn't modify the value, recurse on its
8892     // vector input.
8893     return FindScalarElement(III->getOperand(0), EltNo);
8894   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8895     unsigned InEl = getShuffleMask(SVI)[EltNo];
8896     if (InEl < Width)
8897       return FindScalarElement(SVI->getOperand(0), InEl);
8898     else if (InEl < Width*2)
8899       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8900     else
8901       return UndefValue::get(PTy->getElementType());
8902   }
8903   
8904   // Otherwise, we don't know.
8905   return 0;
8906 }
8907
8908 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8909
8910   // If packed val is undef, replace extract with scalar undef.
8911   if (isa<UndefValue>(EI.getOperand(0)))
8912     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8913
8914   // If packed val is constant 0, replace extract with scalar 0.
8915   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8916     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8917   
8918   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
8919     // If packed val is constant with uniform operands, replace EI
8920     // with that operand
8921     Constant *op0 = C->getOperand(0);
8922     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8923       if (C->getOperand(i) != op0) {
8924         op0 = 0; 
8925         break;
8926       }
8927     if (op0)
8928       return ReplaceInstUsesWith(EI, op0);
8929   }
8930   
8931   // If extracting a specified index from the vector, see if we can recursively
8932   // find a previously computed scalar that was inserted into the vector.
8933   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8934     // This instruction only demands the single element from the input vector.
8935     // If the input vector has a single use, simplify it based on this use
8936     // property.
8937     uint64_t IndexVal = IdxC->getZExtValue();
8938     if (EI.getOperand(0)->hasOneUse()) {
8939       uint64_t UndefElts;
8940       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8941                                                 1 << IndexVal,
8942                                                 UndefElts)) {
8943         EI.setOperand(0, V);
8944         return &EI;
8945       }
8946     }
8947     
8948     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8949       return ReplaceInstUsesWith(EI, Elt);
8950   }
8951   
8952   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8953     if (I->hasOneUse()) {
8954       // Push extractelement into predecessor operation if legal and
8955       // profitable to do so
8956       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8957         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8958         if (CheapToScalarize(BO, isConstantElt)) {
8959           ExtractElementInst *newEI0 = 
8960             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8961                                    EI.getName()+".lhs");
8962           ExtractElementInst *newEI1 =
8963             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8964                                    EI.getName()+".rhs");
8965           InsertNewInstBefore(newEI0, EI);
8966           InsertNewInstBefore(newEI1, EI);
8967           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8968         }
8969       } else if (isa<LoadInst>(I)) {
8970         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8971                                       PointerType::get(EI.getType()), EI);
8972         GetElementPtrInst *GEP = 
8973           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8974         InsertNewInstBefore(GEP, EI);
8975         return new LoadInst(GEP);
8976       }
8977     }
8978     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8979       // Extracting the inserted element?
8980       if (IE->getOperand(2) == EI.getOperand(1))
8981         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8982       // If the inserted and extracted elements are constants, they must not
8983       // be the same value, extract from the pre-inserted value instead.
8984       if (isa<Constant>(IE->getOperand(2)) &&
8985           isa<Constant>(EI.getOperand(1))) {
8986         AddUsesToWorkList(EI);
8987         EI.setOperand(0, IE->getOperand(0));
8988         return &EI;
8989       }
8990     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8991       // If this is extracting an element from a shufflevector, figure out where
8992       // it came from and extract from the appropriate input element instead.
8993       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8994         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8995         Value *Src;
8996         if (SrcIdx < SVI->getType()->getNumElements())
8997           Src = SVI->getOperand(0);
8998         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8999           SrcIdx -= SVI->getType()->getNumElements();
9000           Src = SVI->getOperand(1);
9001         } else {
9002           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9003         }
9004         return new ExtractElementInst(Src, SrcIdx);
9005       }
9006     }
9007   }
9008   return 0;
9009 }
9010
9011 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9012 /// elements from either LHS or RHS, return the shuffle mask and true. 
9013 /// Otherwise, return false.
9014 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9015                                          std::vector<Constant*> &Mask) {
9016   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9017          "Invalid CollectSingleShuffleElements");
9018   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9019
9020   if (isa<UndefValue>(V)) {
9021     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9022     return true;
9023   } else if (V == LHS) {
9024     for (unsigned i = 0; i != NumElts; ++i)
9025       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9026     return true;
9027   } else if (V == RHS) {
9028     for (unsigned i = 0; i != NumElts; ++i)
9029       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9030     return true;
9031   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9032     // If this is an insert of an extract from some other vector, include it.
9033     Value *VecOp    = IEI->getOperand(0);
9034     Value *ScalarOp = IEI->getOperand(1);
9035     Value *IdxOp    = IEI->getOperand(2);
9036     
9037     if (!isa<ConstantInt>(IdxOp))
9038       return false;
9039     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9040     
9041     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
9042       // Okay, we can handle this if the vector we are insertinting into is
9043       // transitively ok.
9044       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9045         // If so, update the mask to reflect the inserted undef.
9046         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9047         return true;
9048       }      
9049     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9050       if (isa<ConstantInt>(EI->getOperand(1)) &&
9051           EI->getOperand(0)->getType() == V->getType()) {
9052         unsigned ExtractedIdx =
9053           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9054         
9055         // This must be extracting from either LHS or RHS.
9056         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9057           // Okay, we can handle this if the vector we are insertinting into is
9058           // transitively ok.
9059           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9060             // If so, update the mask to reflect the inserted value.
9061             if (EI->getOperand(0) == LHS) {
9062               Mask[InsertedIdx & (NumElts-1)] = 
9063                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9064             } else {
9065               assert(EI->getOperand(0) == RHS);
9066               Mask[InsertedIdx & (NumElts-1)] = 
9067                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9068               
9069             }
9070             return true;
9071           }
9072         }
9073       }
9074     }
9075   }
9076   // TODO: Handle shufflevector here!
9077   
9078   return false;
9079 }
9080
9081 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9082 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
9083 /// that computes V and the LHS value of the shuffle.
9084 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9085                                      Value *&RHS) {
9086   assert(isa<VectorType>(V->getType()) && 
9087          (RHS == 0 || V->getType() == RHS->getType()) &&
9088          "Invalid shuffle!");
9089   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9090
9091   if (isa<UndefValue>(V)) {
9092     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9093     return V;
9094   } else if (isa<ConstantAggregateZero>(V)) {
9095     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9096     return V;
9097   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9098     // If this is an insert of an extract from some other vector, include it.
9099     Value *VecOp    = IEI->getOperand(0);
9100     Value *ScalarOp = IEI->getOperand(1);
9101     Value *IdxOp    = IEI->getOperand(2);
9102     
9103     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9104       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9105           EI->getOperand(0)->getType() == V->getType()) {
9106         unsigned ExtractedIdx =
9107           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9108         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9109         
9110         // Either the extracted from or inserted into vector must be RHSVec,
9111         // otherwise we'd end up with a shuffle of three inputs.
9112         if (EI->getOperand(0) == RHS || RHS == 0) {
9113           RHS = EI->getOperand(0);
9114           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9115           Mask[InsertedIdx & (NumElts-1)] = 
9116             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9117           return V;
9118         }
9119         
9120         if (VecOp == RHS) {
9121           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9122           // Everything but the extracted element is replaced with the RHS.
9123           for (unsigned i = 0; i != NumElts; ++i) {
9124             if (i != InsertedIdx)
9125               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9126           }
9127           return V;
9128         }
9129         
9130         // If this insertelement is a chain that comes from exactly these two
9131         // vectors, return the vector and the effective shuffle.
9132         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9133           return EI->getOperand(0);
9134         
9135       }
9136     }
9137   }
9138   // TODO: Handle shufflevector here!
9139   
9140   // Otherwise, can't do anything fancy.  Return an identity vector.
9141   for (unsigned i = 0; i != NumElts; ++i)
9142     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9143   return V;
9144 }
9145
9146 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9147   Value *VecOp    = IE.getOperand(0);
9148   Value *ScalarOp = IE.getOperand(1);
9149   Value *IdxOp    = IE.getOperand(2);
9150   
9151   // If the inserted element was extracted from some other vector, and if the 
9152   // indexes are constant, try to turn this into a shufflevector operation.
9153   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9154     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9155         EI->getOperand(0)->getType() == IE.getType()) {
9156       unsigned NumVectorElts = IE.getType()->getNumElements();
9157       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9158       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9159       
9160       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9161         return ReplaceInstUsesWith(IE, VecOp);
9162       
9163       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
9164         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9165       
9166       // If we are extracting a value from a vector, then inserting it right
9167       // back into the same place, just use the input vector.
9168       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9169         return ReplaceInstUsesWith(IE, VecOp);      
9170       
9171       // We could theoretically do this for ANY input.  However, doing so could
9172       // turn chains of insertelement instructions into a chain of shufflevector
9173       // instructions, and right now we do not merge shufflevectors.  As such,
9174       // only do this in a situation where it is clear that there is benefit.
9175       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9176         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
9177         // the values of VecOp, except then one read from EIOp0.
9178         // Build a new shuffle mask.
9179         std::vector<Constant*> Mask;
9180         if (isa<UndefValue>(VecOp))
9181           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9182         else {
9183           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9184           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9185                                                        NumVectorElts));
9186         } 
9187         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9188         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9189                                      ConstantVector::get(Mask));
9190       }
9191       
9192       // If this insertelement isn't used by some other insertelement, turn it
9193       // (and any insertelements it points to), into one big shuffle.
9194       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9195         std::vector<Constant*> Mask;
9196         Value *RHS = 0;
9197         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9198         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9199         // We now have a shuffle of LHS, RHS, Mask.
9200         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9201       }
9202     }
9203   }
9204
9205   return 0;
9206 }
9207
9208
9209 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9210   Value *LHS = SVI.getOperand(0);
9211   Value *RHS = SVI.getOperand(1);
9212   std::vector<unsigned> Mask = getShuffleMask(&SVI);
9213
9214   bool MadeChange = false;
9215   
9216   // Undefined shuffle mask -> undefined value.
9217   if (isa<UndefValue>(SVI.getOperand(2)))
9218     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9219   
9220   // If we have shuffle(x, undef, mask) and any elements of mask refer to
9221   // the undef, change them to undefs.
9222   if (isa<UndefValue>(SVI.getOperand(1))) {
9223     // Scan to see if there are any references to the RHS.  If so, replace them
9224     // with undef element refs and set MadeChange to true.
9225     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9226       if (Mask[i] >= e && Mask[i] != 2*e) {
9227         Mask[i] = 2*e;
9228         MadeChange = true;
9229       }
9230     }
9231     
9232     if (MadeChange) {
9233       // Remap any references to RHS to use LHS.
9234       std::vector<Constant*> Elts;
9235       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9236         if (Mask[i] == 2*e)
9237           Elts.push_back(UndefValue::get(Type::Int32Ty));
9238         else
9239           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9240       }
9241       SVI.setOperand(2, ConstantVector::get(Elts));
9242     }
9243   }
9244   
9245   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
9246   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9247   if (LHS == RHS || isa<UndefValue>(LHS)) {
9248     if (isa<UndefValue>(LHS) && LHS == RHS) {
9249       // shuffle(undef,undef,mask) -> undef.
9250       return ReplaceInstUsesWith(SVI, LHS);
9251     }
9252     
9253     // Remap any references to RHS to use LHS.
9254     std::vector<Constant*> Elts;
9255     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9256       if (Mask[i] >= 2*e)
9257         Elts.push_back(UndefValue::get(Type::Int32Ty));
9258       else {
9259         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9260             (Mask[i] <  e && isa<UndefValue>(LHS)))
9261           Mask[i] = 2*e;     // Turn into undef.
9262         else
9263           Mask[i] &= (e-1);  // Force to LHS.
9264         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9265       }
9266     }
9267     SVI.setOperand(0, SVI.getOperand(1));
9268     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9269     SVI.setOperand(2, ConstantVector::get(Elts));
9270     LHS = SVI.getOperand(0);
9271     RHS = SVI.getOperand(1);
9272     MadeChange = true;
9273   }
9274   
9275   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9276   bool isLHSID = true, isRHSID = true;
9277     
9278   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9279     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9280     // Is this an identity shuffle of the LHS value?
9281     isLHSID &= (Mask[i] == i);
9282       
9283     // Is this an identity shuffle of the RHS value?
9284     isRHSID &= (Mask[i]-e == i);
9285   }
9286
9287   // Eliminate identity shuffles.
9288   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9289   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9290   
9291   // If the LHS is a shufflevector itself, see if we can combine it with this
9292   // one without producing an unusual shuffle.  Here we are really conservative:
9293   // we are absolutely afraid of producing a shuffle mask not in the input
9294   // program, because the code gen may not be smart enough to turn a merged
9295   // shuffle into two specific shuffles: it may produce worse code.  As such,
9296   // we only merge two shuffles if the result is one of the two input shuffle
9297   // masks.  In this case, merging the shuffles just removes one instruction,
9298   // which we know is safe.  This is good for things like turning:
9299   // (splat(splat)) -> splat.
9300   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9301     if (isa<UndefValue>(RHS)) {
9302       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9303
9304       std::vector<unsigned> NewMask;
9305       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9306         if (Mask[i] >= 2*e)
9307           NewMask.push_back(2*e);
9308         else
9309           NewMask.push_back(LHSMask[Mask[i]]);
9310       
9311       // If the result mask is equal to the src shuffle or this shuffle mask, do
9312       // the replacement.
9313       if (NewMask == LHSMask || NewMask == Mask) {
9314         std::vector<Constant*> Elts;
9315         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9316           if (NewMask[i] >= e*2) {
9317             Elts.push_back(UndefValue::get(Type::Int32Ty));
9318           } else {
9319             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9320           }
9321         }
9322         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9323                                      LHSSVI->getOperand(1),
9324                                      ConstantVector::get(Elts));
9325       }
9326     }
9327   }
9328
9329   return MadeChange ? &SVI : 0;
9330 }
9331
9332
9333
9334
9335 /// TryToSinkInstruction - Try to move the specified instruction from its
9336 /// current block into the beginning of DestBlock, which can only happen if it's
9337 /// safe to move the instruction past all of the instructions between it and the
9338 /// end of its block.
9339 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9340   assert(I->hasOneUse() && "Invariants didn't hold!");
9341
9342   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9343   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9344
9345   // Do not sink alloca instructions out of the entry block.
9346   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9347     return false;
9348
9349   // We can only sink load instructions if there is nothing between the load and
9350   // the end of block that could change the value.
9351   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9352     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9353          Scan != E; ++Scan)
9354       if (Scan->mayWriteToMemory())
9355         return false;
9356   }
9357
9358   BasicBlock::iterator InsertPos = DestBlock->begin();
9359   while (isa<PHINode>(InsertPos)) ++InsertPos;
9360
9361   I->moveBefore(InsertPos);
9362   ++NumSunkInst;
9363   return true;
9364 }
9365
9366
9367 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9368 /// all reachable code to the worklist.
9369 ///
9370 /// This has a couple of tricks to make the code faster and more powerful.  In
9371 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9372 /// them to the worklist (this significantly speeds up instcombine on code where
9373 /// many instructions are dead or constant).  Additionally, if we find a branch
9374 /// whose condition is a known constant, we only visit the reachable successors.
9375 ///
9376 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9377                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9378                                        InstCombiner &IC,
9379                                        const TargetData *TD) {
9380   // We have now visited this block!  If we've already been here, bail out.
9381   if (!Visited.insert(BB)) return;
9382     
9383   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9384     Instruction *Inst = BBI++;
9385     
9386     // DCE instruction if trivially dead.
9387     if (isInstructionTriviallyDead(Inst)) {
9388       ++NumDeadInst;
9389       DOUT << "IC: DCE: " << *Inst;
9390       Inst->eraseFromParent();
9391       continue;
9392     }
9393     
9394     // ConstantProp instruction if trivially constant.
9395     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9396       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9397       Inst->replaceAllUsesWith(C);
9398       ++NumConstProp;
9399       Inst->eraseFromParent();
9400       continue;
9401     }
9402     
9403     IC.AddToWorkList(Inst);
9404   }
9405
9406   // Recursively visit successors.  If this is a branch or switch on a constant,
9407   // only visit the reachable successor.
9408   TerminatorInst *TI = BB->getTerminator();
9409   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9410     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9411       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9412       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
9413       return;
9414     }
9415   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9416     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9417       // See if this is an explicit destination.
9418       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9419         if (SI->getCaseValue(i) == Cond) {
9420           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
9421           return;
9422         }
9423       
9424       // Otherwise it is the default destination.
9425       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
9426       return;
9427     }
9428   }
9429   
9430   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9431     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
9432 }
9433
9434 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
9435   bool Changed = false;
9436   TD = &getAnalysis<TargetData>();
9437   
9438   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9439              << F.getNameStr() << "\n");
9440
9441   {
9442     // Do a depth-first traversal of the function, populate the worklist with
9443     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9444     // track of which blocks we visit.
9445     SmallPtrSet<BasicBlock*, 64> Visited;
9446     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
9447
9448     // Do a quick scan over the function.  If we find any blocks that are
9449     // unreachable, remove any instructions inside of them.  This prevents
9450     // the instcombine code from having to deal with some bad special cases.
9451     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9452       if (!Visited.count(BB)) {
9453         Instruction *Term = BB->getTerminator();
9454         while (Term != BB->begin()) {   // Remove instrs bottom-up
9455           BasicBlock::iterator I = Term; --I;
9456
9457           DOUT << "IC: DCE: " << *I;
9458           ++NumDeadInst;
9459
9460           if (!I->use_empty())
9461             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9462           I->eraseFromParent();
9463         }
9464       }
9465   }
9466
9467   while (!Worklist.empty()) {
9468     Instruction *I = RemoveOneFromWorkList();
9469     if (I == 0) continue;  // skip null values.
9470
9471     // Check to see if we can DCE the instruction.
9472     if (isInstructionTriviallyDead(I)) {
9473       // Add operands to the worklist.
9474       if (I->getNumOperands() < 4)
9475         AddUsesToWorkList(*I);
9476       ++NumDeadInst;
9477
9478       DOUT << "IC: DCE: " << *I;
9479
9480       I->eraseFromParent();
9481       RemoveFromWorkList(I);
9482       continue;
9483     }
9484
9485     // Instruction isn't dead, see if we can constant propagate it.
9486     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9487       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9488
9489       // Add operands to the worklist.
9490       AddUsesToWorkList(*I);
9491       ReplaceInstUsesWith(*I, C);
9492
9493       ++NumConstProp;
9494       I->eraseFromParent();
9495       RemoveFromWorkList(I);
9496       continue;
9497     }
9498
9499     // See if we can trivially sink this instruction to a successor basic block.
9500     if (I->hasOneUse()) {
9501       BasicBlock *BB = I->getParent();
9502       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9503       if (UserParent != BB) {
9504         bool UserIsSuccessor = false;
9505         // See if the user is one of our successors.
9506         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9507           if (*SI == UserParent) {
9508             UserIsSuccessor = true;
9509             break;
9510           }
9511
9512         // If the user is one of our immediate successors, and if that successor
9513         // only has us as a predecessors (we'd have to split the critical edge
9514         // otherwise), we can keep going.
9515         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9516             next(pred_begin(UserParent)) == pred_end(UserParent))
9517           // Okay, the CFG is simple enough, try to sink this instruction.
9518           Changed |= TryToSinkInstruction(I, UserParent);
9519       }
9520     }
9521
9522     // Now that we have an instruction, try combining it to simplify it...
9523     if (Instruction *Result = visit(*I)) {
9524       ++NumCombined;
9525       // Should we replace the old instruction with a new one?
9526       if (Result != I) {
9527         DOUT << "IC: Old = " << *I
9528              << "    New = " << *Result;
9529
9530         // Everything uses the new instruction now.
9531         I->replaceAllUsesWith(Result);
9532
9533         // Push the new instruction and any users onto the worklist.
9534         AddToWorkList(Result);
9535         AddUsersToWorkList(*Result);
9536
9537         // Move the name to the new instruction first.
9538         Result->takeName(I);
9539
9540         // Insert the new instruction into the basic block...
9541         BasicBlock *InstParent = I->getParent();
9542         BasicBlock::iterator InsertPos = I;
9543
9544         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9545           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9546             ++InsertPos;
9547
9548         InstParent->getInstList().insert(InsertPos, Result);
9549
9550         // Make sure that we reprocess all operands now that we reduced their
9551         // use counts.
9552         AddUsesToWorkList(*I);
9553
9554         // Instructions can end up on the worklist more than once.  Make sure
9555         // we do not process an instruction that has been deleted.
9556         RemoveFromWorkList(I);
9557
9558         // Erase the old instruction.
9559         InstParent->getInstList().erase(I);
9560       } else {
9561         DOUT << "IC: MOD = " << *I;
9562
9563         // If the instruction was modified, it's possible that it is now dead.
9564         // if so, remove it.
9565         if (isInstructionTriviallyDead(I)) {
9566           // Make sure we process all operands now that we are reducing their
9567           // use counts.
9568           AddUsesToWorkList(*I);
9569
9570           // Instructions may end up in the worklist more than once.  Erase all
9571           // occurrences of this instruction.
9572           RemoveFromWorkList(I);
9573           I->eraseFromParent();
9574         } else {
9575           AddToWorkList(I);
9576           AddUsersToWorkList(*I);
9577         }
9578       }
9579       Changed = true;
9580     }
9581   }
9582
9583   assert(WorklistMap.empty() && "Worklist empty, but map not?");
9584   return Changed;
9585 }
9586
9587
9588 bool InstCombiner::runOnFunction(Function &F) {
9589   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9590   
9591   bool EverMadeChange = false;
9592
9593   // Iterate while there is work to do.
9594   unsigned Iteration = 0;
9595   while (DoOneIteration(F, Iteration++)) 
9596     EverMadeChange = true;
9597   return EverMadeChange;
9598 }
9599
9600 FunctionPass *llvm::createInstructionCombiningPass() {
9601   return new InstCombiner();
9602 }
9603