remove temporary vectors.
[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/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/STLExtras.h"
56 #include <algorithm>
57 using namespace llvm;
58 using namespace llvm::PatternMatch;
59
60 STATISTIC(NumCombined , "Number of insts combined");
61 STATISTIC(NumConstProp, "Number of constant folds");
62 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
63 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
64 STATISTIC(NumSunkInst , "Number of instructions sunk");
65
66 namespace {
67   class VISIBILITY_HIDDEN InstCombiner
68     : public FunctionPass,
69       public InstVisitor<InstCombiner, Instruction*> {
70     // Worklist of all of the instructions that need to be simplified.
71     std::vector<Instruction*> WorkList;
72     TargetData *TD;
73
74     /// AddUsersToWorkList - When an instruction is simplified, add all users of
75     /// the instruction to the work lists because they might get more simplified
76     /// now.
77     ///
78     void AddUsersToWorkList(Value &I) {
79       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
80            UI != UE; ++UI)
81         WorkList.push_back(cast<Instruction>(*UI));
82     }
83
84     /// AddUsesToWorkList - When an instruction is simplified, add operands to
85     /// the work lists because they might get more simplified now.
86     ///
87     void AddUsesToWorkList(Instruction &I) {
88       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
89         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
90           WorkList.push_back(Op);
91     }
92     
93     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
94     /// dead.  Add all of its operands to the worklist, turning them into
95     /// undef's to reduce the number of uses of those instructions.
96     ///
97     /// Return the specified operand before it is turned into an undef.
98     ///
99     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
100       Value *R = I.getOperand(op);
101       
102       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
103         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
104           WorkList.push_back(Op);
105           // Set the operand to undef to drop the use.
106           I.setOperand(i, UndefValue::get(Op->getType()));
107         }
108       
109       return R;
110     }
111
112     // removeFromWorkList - remove all instances of I from the worklist.
113     void removeFromWorkList(Instruction *I);
114   public:
115     virtual bool runOnFunction(Function &F);
116
117     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118       AU.addRequired<TargetData>();
119       AU.addPreservedID(LCSSAID);
120       AU.setPreservesCFG();
121     }
122
123     TargetData &getTargetData() const { return *TD; }
124
125     // Visitation implementation - Implement instruction combining for different
126     // instruction types.  The semantics are as follows:
127     // Return Value:
128     //    null        - No change was made
129     //     I          - Change was made, I is still valid, I may be dead though
130     //   otherwise    - Change was made, replace I with returned instruction
131     //
132     Instruction *visitAdd(BinaryOperator &I);
133     Instruction *visitSub(BinaryOperator &I);
134     Instruction *visitMul(BinaryOperator &I);
135     Instruction *visitURem(BinaryOperator &I);
136     Instruction *visitSRem(BinaryOperator &I);
137     Instruction *visitFRem(BinaryOperator &I);
138     Instruction *commonRemTransforms(BinaryOperator &I);
139     Instruction *commonIRemTransforms(BinaryOperator &I);
140     Instruction *commonDivTransforms(BinaryOperator &I);
141     Instruction *commonIDivTransforms(BinaryOperator &I);
142     Instruction *visitUDiv(BinaryOperator &I);
143     Instruction *visitSDiv(BinaryOperator &I);
144     Instruction *visitFDiv(BinaryOperator &I);
145     Instruction *visitAnd(BinaryOperator &I);
146     Instruction *visitOr (BinaryOperator &I);
147     Instruction *visitXor(BinaryOperator &I);
148     Instruction *visitFCmpInst(FCmpInst &I);
149     Instruction *visitICmpInst(ICmpInst &I);
150     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
151
152     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
153                              ICmpInst::Predicate Cond, Instruction &I);
154     Instruction *visitShiftInst(ShiftInst &I);
155     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
156                                      ShiftInst &I);
157     Instruction *commonCastTransforms(CastInst &CI);
158     Instruction *commonIntCastTransforms(CastInst &CI);
159     Instruction *visitTrunc(CastInst &CI);
160     Instruction *visitZExt(CastInst &CI);
161     Instruction *visitSExt(CastInst &CI);
162     Instruction *visitFPTrunc(CastInst &CI);
163     Instruction *visitFPExt(CastInst &CI);
164     Instruction *visitFPToUI(CastInst &CI);
165     Instruction *visitFPToSI(CastInst &CI);
166     Instruction *visitUIToFP(CastInst &CI);
167     Instruction *visitSIToFP(CastInst &CI);
168     Instruction *visitPtrToInt(CastInst &CI);
169     Instruction *visitIntToPtr(CastInst &CI);
170     Instruction *visitBitCast(CastInst &CI);
171     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
172                                 Instruction *FI);
173     Instruction *visitSelectInst(SelectInst &CI);
174     Instruction *visitCallInst(CallInst &CI);
175     Instruction *visitInvokeInst(InvokeInst &II);
176     Instruction *visitPHINode(PHINode &PN);
177     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
178     Instruction *visitAllocationInst(AllocationInst &AI);
179     Instruction *visitFreeInst(FreeInst &FI);
180     Instruction *visitLoadInst(LoadInst &LI);
181     Instruction *visitStoreInst(StoreInst &SI);
182     Instruction *visitBranchInst(BranchInst &BI);
183     Instruction *visitSwitchInst(SwitchInst &SI);
184     Instruction *visitInsertElementInst(InsertElementInst &IE);
185     Instruction *visitExtractElementInst(ExtractElementInst &EI);
186     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
187
188     // visitInstruction - Specify what to return for unhandled instructions...
189     Instruction *visitInstruction(Instruction &I) { return 0; }
190
191   private:
192     Instruction *visitCallSite(CallSite CS);
193     bool transformConstExprCastCall(CallSite CS);
194
195   public:
196     // InsertNewInstBefore - insert an instruction New before instruction Old
197     // in the program.  Add the new instruction to the worklist.
198     //
199     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
200       assert(New && New->getParent() == 0 &&
201              "New instruction already inserted into a basic block!");
202       BasicBlock *BB = Old.getParent();
203       BB->getInstList().insert(&Old, New);  // Insert inst
204       WorkList.push_back(New);              // Add to worklist
205       return New;
206     }
207
208     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
209     /// This also adds the cast to the worklist.  Finally, this returns the
210     /// cast.
211     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
212                             Instruction &Pos) {
213       if (V->getType() == Ty) return V;
214
215       if (Constant *CV = dyn_cast<Constant>(V))
216         return ConstantExpr::getCast(opc, CV, Ty);
217       
218       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
219       WorkList.push_back(C);
220       return C;
221     }
222
223     // ReplaceInstUsesWith - This method is to be used when an instruction is
224     // found to be dead, replacable with another preexisting expression.  Here
225     // we add all uses of I to the worklist, replace all uses of I with the new
226     // value, then return I, so that the inst combiner will know that I was
227     // modified.
228     //
229     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
230       AddUsersToWorkList(I);         // Add all modified instrs to worklist
231       if (&I != V) {
232         I.replaceAllUsesWith(V);
233         return &I;
234       } else {
235         // If we are replacing the instruction with itself, this must be in a
236         // segment of unreachable code, so just clobber the instruction.
237         I.replaceAllUsesWith(UndefValue::get(I.getType()));
238         return &I;
239       }
240     }
241
242     // UpdateValueUsesWith - This method is to be used when an value is
243     // found to be replacable with another preexisting expression or was
244     // updated.  Here we add all uses of I to the worklist, replace all uses of
245     // I with the new value (unless the instruction was just updated), then
246     // return true, so that the inst combiner will know that I was modified.
247     //
248     bool UpdateValueUsesWith(Value *Old, Value *New) {
249       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
250       if (Old != New)
251         Old->replaceAllUsesWith(New);
252       if (Instruction *I = dyn_cast<Instruction>(Old))
253         WorkList.push_back(I);
254       if (Instruction *I = dyn_cast<Instruction>(New))
255         WorkList.push_back(I);
256       return true;
257     }
258     
259     // EraseInstFromFunction - When dealing with an instruction that has side
260     // effects or produces a void value, we can't rely on DCE to delete the
261     // instruction.  Instead, visit methods should return the value returned by
262     // this function.
263     Instruction *EraseInstFromFunction(Instruction &I) {
264       assert(I.use_empty() && "Cannot erase instruction that is used!");
265       AddUsesToWorkList(I);
266       removeFromWorkList(&I);
267       I.eraseFromParent();
268       return 0;  // Don't do anything with FI
269     }
270
271   private:
272     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
273     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
274     /// casts that are known to not do anything...
275     ///
276     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
277                                    Value *V, const Type *DestTy,
278                                    Instruction *InsertBefore);
279
280     /// SimplifyCommutative - This performs a few simplifications for 
281     /// commutative operators.
282     bool SimplifyCommutative(BinaryOperator &I);
283
284     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
285     /// most-complex to least-complex order.
286     bool SimplifyCompare(CmpInst &I);
287
288     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
289                               uint64_t &KnownZero, uint64_t &KnownOne,
290                               unsigned Depth = 0);
291
292     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
293                                       uint64_t &UndefElts, unsigned Depth = 0);
294       
295     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
296     // PHI node as operand #0, see if we can fold the instruction into the PHI
297     // (which is only possible if all operands to the PHI are constants).
298     Instruction *FoldOpIntoPhi(Instruction &I);
299
300     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
301     // operator and they all are only used by the PHI, PHI together their
302     // inputs, and do the operation once, to the result of the PHI.
303     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
304     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
305     
306     
307     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
308                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
309     
310     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
311                               bool isSub, Instruction &I);
312     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
313                                  bool isSigned, bool Inside, Instruction &IB);
314     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
315     Instruction *MatchBSwap(BinaryOperator &I);
316
317     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
318   };
319
320   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
321 }
322
323 // getComplexity:  Assign a complexity or rank value to LLVM Values...
324 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
325 static unsigned getComplexity(Value *V) {
326   if (isa<Instruction>(V)) {
327     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
328       return 3;
329     return 4;
330   }
331   if (isa<Argument>(V)) return 3;
332   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
333 }
334
335 // isOnlyUse - Return true if this instruction will be deleted if we stop using
336 // it.
337 static bool isOnlyUse(Value *V) {
338   return V->hasOneUse() || isa<Constant>(V);
339 }
340
341 // getPromotedType - Return the specified type promoted as it would be to pass
342 // though a va_arg area...
343 static const Type *getPromotedType(const Type *Ty) {
344   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
345     if (ITy->getBitWidth() < 32)
346       return Type::Int32Ty;
347   } else if (Ty == Type::FloatTy)
348     return Type::DoubleTy;
349   return Ty;
350 }
351
352 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
353 /// expression bitcast,  return the operand value, otherwise return null.
354 static Value *getBitCastOperand(Value *V) {
355   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
356     return I->getOperand(0);
357   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
358     if (CE->getOpcode() == Instruction::BitCast)
359       return CE->getOperand(0);
360   return 0;
361 }
362
363 /// This function is a wrapper around CastInst::isEliminableCastPair. It
364 /// simply extracts arguments and returns what that function returns.
365 /// @Determine if it is valid to eliminate a Convert pair
366 static Instruction::CastOps 
367 isEliminableCastPair(
368   const CastInst *CI, ///< The first cast instruction
369   unsigned opcode,       ///< The opcode of the second cast instruction
370   const Type *DstTy,     ///< The target type for the second cast instruction
371   TargetData *TD         ///< The target data for pointer size
372 ) {
373   
374   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
375   const Type *MidTy = CI->getType();                  // B from above
376
377   // Get the opcodes of the two Cast instructions
378   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
379   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
380
381   return Instruction::CastOps(
382       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
383                                      DstTy, TD->getIntPtrType()));
384 }
385
386 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
387 /// in any code being generated.  It does not require codegen if V is simple
388 /// enough or if the cast can be folded into other casts.
389 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
390                               const Type *Ty, TargetData *TD) {
391   if (V->getType() == Ty || isa<Constant>(V)) return false;
392   
393   // If this is another cast that can be eliminated, it isn't codegen either.
394   if (const CastInst *CI = dyn_cast<CastInst>(V))
395     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
396       return false;
397   return true;
398 }
399
400 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
401 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
402 /// casts that are known to not do anything...
403 ///
404 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
405                                              Value *V, const Type *DestTy,
406                                              Instruction *InsertBefore) {
407   if (V->getType() == DestTy) return V;
408   if (Constant *C = dyn_cast<Constant>(V))
409     return ConstantExpr::getCast(opcode, C, DestTy);
410   
411   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
412 }
413
414 // SimplifyCommutative - This performs a few simplifications for commutative
415 // operators:
416 //
417 //  1. Order operands such that they are listed from right (least complex) to
418 //     left (most complex).  This puts constants before unary operators before
419 //     binary operators.
420 //
421 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
422 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
423 //
424 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
425   bool Changed = false;
426   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
427     Changed = !I.swapOperands();
428
429   if (!I.isAssociative()) return Changed;
430   Instruction::BinaryOps Opcode = I.getOpcode();
431   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
432     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
433       if (isa<Constant>(I.getOperand(1))) {
434         Constant *Folded = ConstantExpr::get(I.getOpcode(),
435                                              cast<Constant>(I.getOperand(1)),
436                                              cast<Constant>(Op->getOperand(1)));
437         I.setOperand(0, Op->getOperand(0));
438         I.setOperand(1, Folded);
439         return true;
440       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
441         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
442             isOnlyUse(Op) && isOnlyUse(Op1)) {
443           Constant *C1 = cast<Constant>(Op->getOperand(1));
444           Constant *C2 = cast<Constant>(Op1->getOperand(1));
445
446           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
447           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
448           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
449                                                     Op1->getOperand(0),
450                                                     Op1->getName(), &I);
451           WorkList.push_back(New);
452           I.setOperand(0, New);
453           I.setOperand(1, Folded);
454           return true;
455         }
456     }
457   return Changed;
458 }
459
460 /// SimplifyCompare - For a CmpInst this function just orders the operands
461 /// so that theyare listed from right (least complex) to left (most complex).
462 /// This puts constants before unary operators before binary operators.
463 bool InstCombiner::SimplifyCompare(CmpInst &I) {
464   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
465     return false;
466   I.swapOperands();
467   // Compare instructions are not associative so there's nothing else we can do.
468   return true;
469 }
470
471 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
472 // if the LHS is a constant zero (which is the 'negate' form).
473 //
474 static inline Value *dyn_castNegVal(Value *V) {
475   if (BinaryOperator::isNeg(V))
476     return BinaryOperator::getNegArgument(V);
477
478   // Constants can be considered to be negated values if they can be folded.
479   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
480     return ConstantExpr::getNeg(C);
481   return 0;
482 }
483
484 static inline Value *dyn_castNotVal(Value *V) {
485   if (BinaryOperator::isNot(V))
486     return BinaryOperator::getNotArgument(V);
487
488   // Constants can be considered to be not'ed values...
489   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
490     return ConstantExpr::getNot(C);
491   return 0;
492 }
493
494 // dyn_castFoldableMul - If this value is a multiply that can be folded into
495 // other computations (because it has a constant operand), return the
496 // non-constant operand of the multiply, and set CST to point to the multiplier.
497 // Otherwise, return null.
498 //
499 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
500   if (V->hasOneUse() && V->getType()->isInteger())
501     if (Instruction *I = dyn_cast<Instruction>(V)) {
502       if (I->getOpcode() == Instruction::Mul)
503         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
504           return I->getOperand(0);
505       if (I->getOpcode() == Instruction::Shl)
506         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
507           // The multiplier is really 1 << CST.
508           Constant *One = ConstantInt::get(V->getType(), 1);
509           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
510           return I->getOperand(0);
511         }
512     }
513   return 0;
514 }
515
516 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
517 /// expression, return it.
518 static User *dyn_castGetElementPtr(Value *V) {
519   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
520   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
521     if (CE->getOpcode() == Instruction::GetElementPtr)
522       return cast<User>(V);
523   return false;
524 }
525
526 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
527 static ConstantInt *AddOne(ConstantInt *C) {
528   return cast<ConstantInt>(ConstantExpr::getAdd(C,
529                                          ConstantInt::get(C->getType(), 1)));
530 }
531 static ConstantInt *SubOne(ConstantInt *C) {
532   return cast<ConstantInt>(ConstantExpr::getSub(C,
533                                          ConstantInt::get(C->getType(), 1)));
534 }
535
536 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
537 /// known to be either zero or one and return them in the KnownZero/KnownOne
538 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
539 /// processing.
540 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
541                               uint64_t &KnownOne, unsigned Depth = 0) {
542   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
543   // we cannot optimize based on the assumption that it is zero without changing
544   // it to be an explicit zero.  If we don't change it to zero, other code could
545   // optimized based on the contradictory assumption that it is non-zero.
546   // Because instcombine aggressively folds operations with undef args anyway,
547   // this won't lose us code quality.
548   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
549     // We know all of the bits for a constant!
550     KnownOne = CI->getZExtValue() & Mask;
551     KnownZero = ~KnownOne & Mask;
552     return;
553   }
554
555   KnownZero = KnownOne = 0;   // Don't know anything.
556   if (Depth == 6 || Mask == 0)
557     return;  // Limit search depth.
558
559   uint64_t KnownZero2, KnownOne2;
560   Instruction *I = dyn_cast<Instruction>(V);
561   if (!I) return;
562
563   Mask &= cast<IntegerType>(V->getType())->getBitMask();
564   
565   switch (I->getOpcode()) {
566   case Instruction::And:
567     // If either the LHS or the RHS are Zero, the result is zero.
568     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
569     Mask &= ~KnownZero;
570     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
571     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
572     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
573     
574     // Output known-1 bits are only known if set in both the LHS & RHS.
575     KnownOne &= KnownOne2;
576     // Output known-0 are known to be clear if zero in either the LHS | RHS.
577     KnownZero |= KnownZero2;
578     return;
579   case Instruction::Or:
580     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
581     Mask &= ~KnownOne;
582     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
583     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
584     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
585     
586     // Output known-0 bits are only known if clear in both the LHS & RHS.
587     KnownZero &= KnownZero2;
588     // Output known-1 are known to be set if set in either the LHS | RHS.
589     KnownOne |= KnownOne2;
590     return;
591   case Instruction::Xor: {
592     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
593     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
594     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
595     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
596     
597     // Output known-0 bits are known if clear or set in both the LHS & RHS.
598     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
599     // Output known-1 are known to be set if set in only one of the LHS, RHS.
600     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
601     KnownZero = KnownZeroOut;
602     return;
603   }
604   case Instruction::Select:
605     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
606     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
607     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
608     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
609
610     // Only known if known in both the LHS and RHS.
611     KnownOne &= KnownOne2;
612     KnownZero &= KnownZero2;
613     return;
614   case Instruction::FPTrunc:
615   case Instruction::FPExt:
616   case Instruction::FPToUI:
617   case Instruction::FPToSI:
618   case Instruction::SIToFP:
619   case Instruction::PtrToInt:
620   case Instruction::UIToFP:
621   case Instruction::IntToPtr:
622     return; // Can't work with floating point or pointers
623   case Instruction::Trunc: 
624     // All these have integer operands
625     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
626     return;
627   case Instruction::BitCast: {
628     const Type *SrcTy = I->getOperand(0)->getType();
629     if (SrcTy->isInteger()) {
630       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
631       return;
632     }
633     break;
634   }
635   case Instruction::ZExt:  {
636     // Compute the bits in the result that are not present in the input.
637     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
638     uint64_t NotIn = ~SrcTy->getBitMask();
639     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
640       
641     Mask &= SrcTy->getBitMask();
642     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
643     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
644     // The top bits are known to be zero.
645     KnownZero |= NewBits;
646     return;
647   }
648   case Instruction::SExt: {
649     // Compute the bits in the result that are not present in the input.
650     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
651     uint64_t NotIn = ~SrcTy->getBitMask();
652     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
653       
654     Mask &= SrcTy->getBitMask();
655     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
656     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
657
658     // If the sign bit of the input is known set or clear, then we know the
659     // top bits of the result.
660     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
661     if (KnownZero & InSignBit) {          // Input sign bit known zero
662       KnownZero |= NewBits;
663       KnownOne &= ~NewBits;
664     } else if (KnownOne & InSignBit) {    // Input sign bit known set
665       KnownOne |= NewBits;
666       KnownZero &= ~NewBits;
667     } else {                              // Input sign bit unknown
668       KnownZero &= ~NewBits;
669       KnownOne &= ~NewBits;
670     }
671     return;
672   }
673   case Instruction::Shl:
674     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
675     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
676       uint64_t ShiftAmt = SA->getZExtValue();
677       Mask >>= ShiftAmt;
678       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
679       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
680       KnownZero <<= ShiftAmt;
681       KnownOne  <<= ShiftAmt;
682       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
683       return;
684     }
685     break;
686   case Instruction::LShr:
687     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
688     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
689       // Compute the new bits that are at the top now.
690       uint64_t ShiftAmt = SA->getZExtValue();
691       uint64_t HighBits = (1ULL << ShiftAmt)-1;
692       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
693       
694       // Unsigned shift right.
695       Mask <<= ShiftAmt;
696       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
697       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
698       KnownZero >>= ShiftAmt;
699       KnownOne  >>= ShiftAmt;
700       KnownZero |= HighBits;  // high bits known zero.
701       return;
702     }
703     break;
704   case Instruction::AShr:
705     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
706     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
707       // Compute the new bits that are at the top now.
708       uint64_t ShiftAmt = SA->getZExtValue();
709       uint64_t HighBits = (1ULL << ShiftAmt)-1;
710       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
711       
712       // Signed shift right.
713       Mask <<= ShiftAmt;
714       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
715       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
716       KnownZero >>= ShiftAmt;
717       KnownOne  >>= ShiftAmt;
718         
719       // Handle the sign bits.
720       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
721       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
722         
723       if (KnownZero & SignBit) {       // New bits are known zero.
724         KnownZero |= HighBits;
725       } else if (KnownOne & SignBit) { // New bits are known one.
726         KnownOne |= HighBits;
727       }
728       return;
729     }
730     break;
731   }
732 }
733
734 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
735 /// this predicate to simplify operations downstream.  Mask is known to be zero
736 /// for bits that V cannot have.
737 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
738   uint64_t KnownZero, KnownOne;
739   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
740   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
741   return (KnownZero & Mask) == Mask;
742 }
743
744 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
745 /// specified instruction is a constant integer.  If so, check to see if there
746 /// are any bits set in the constant that are not demanded.  If so, shrink the
747 /// constant and return true.
748 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
749                                    uint64_t Demanded) {
750   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
751   if (!OpC) return false;
752
753   // If there are no bits set that aren't demanded, nothing to do.
754   if ((~Demanded & OpC->getZExtValue()) == 0)
755     return false;
756
757   // This is producing any bits that are not needed, shrink the RHS.
758   uint64_t Val = Demanded & OpC->getZExtValue();
759   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
760   return true;
761 }
762
763 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
764 // set of known zero and one bits, compute the maximum and minimum values that
765 // could have the specified known zero and known one bits, returning them in
766 // min/max.
767 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
768                                                    uint64_t KnownZero,
769                                                    uint64_t KnownOne,
770                                                    int64_t &Min, int64_t &Max) {
771   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
772   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
773
774   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
775   
776   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
777   // bit if it is unknown.
778   Min = KnownOne;
779   Max = KnownOne|UnknownBits;
780   
781   if (SignBit & UnknownBits) { // Sign bit is unknown
782     Min |= SignBit;
783     Max &= ~SignBit;
784   }
785   
786   // Sign extend the min/max values.
787   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
788   Min = (Min << ShAmt) >> ShAmt;
789   Max = (Max << ShAmt) >> ShAmt;
790 }
791
792 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793 // a set of known zero and one bits, compute the maximum and minimum values that
794 // could have the specified known zero and known one bits, returning them in
795 // min/max.
796 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
797                                                      uint64_t KnownZero,
798                                                      uint64_t KnownOne,
799                                                      uint64_t &Min,
800                                                      uint64_t &Max) {
801   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
802   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
803   
804   // The minimum value is when the unknown bits are all zeros.
805   Min = KnownOne;
806   // The maximum value is when the unknown bits are all ones.
807   Max = KnownOne|UnknownBits;
808 }
809
810
811 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
812 /// DemandedMask bits of the result of V are ever used downstream.  If we can
813 /// use this information to simplify V, do so and return true.  Otherwise,
814 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
815 /// the expression (used to simplify the caller).  The KnownZero/One bits may
816 /// only be accurate for those bits in the DemandedMask.
817 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
818                                         uint64_t &KnownZero, uint64_t &KnownOne,
819                                         unsigned Depth) {
820   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
821     // We know all of the bits for a constant!
822     KnownOne = CI->getZExtValue() & DemandedMask;
823     KnownZero = ~KnownOne & DemandedMask;
824     return false;
825   }
826   
827   KnownZero = KnownOne = 0;
828   if (!V->hasOneUse()) {    // Other users may use these bits.
829     if (Depth != 0) {       // Not at the root.
830       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
831       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
832       return false;
833     }
834     // If this is the root being simplified, allow it to have multiple uses,
835     // just set the DemandedMask to all bits.
836     DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
837   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
838     if (V != UndefValue::get(V->getType()))
839       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
840     return false;
841   } else if (Depth == 6) {        // Limit search depth.
842     return false;
843   }
844   
845   Instruction *I = dyn_cast<Instruction>(V);
846   if (!I) return false;        // Only analyze instructions.
847
848   DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
849   
850   uint64_t KnownZero2 = 0, KnownOne2 = 0;
851   switch (I->getOpcode()) {
852   default: break;
853   case Instruction::And:
854     // If either the LHS or the RHS are Zero, the result is zero.
855     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856                              KnownZero, KnownOne, Depth+1))
857       return true;
858     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
859
860     // If something is known zero on the RHS, the bits aren't demanded on the
861     // LHS.
862     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
863                              KnownZero2, KnownOne2, Depth+1))
864       return true;
865     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
866
867     // If all of the demanded bits are known 1 on one side, return the other.
868     // These bits cannot contribute to the result of the 'and'.
869     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
870       return UpdateValueUsesWith(I, I->getOperand(0));
871     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
872       return UpdateValueUsesWith(I, I->getOperand(1));
873     
874     // If all of the demanded bits in the inputs are known zeros, return zero.
875     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
876       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
877       
878     // If the RHS is a constant, see if we can simplify it.
879     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
880       return UpdateValueUsesWith(I, I);
881       
882     // Output known-1 bits are only known if set in both the LHS & RHS.
883     KnownOne &= KnownOne2;
884     // Output known-0 are known to be clear if zero in either the LHS | RHS.
885     KnownZero |= KnownZero2;
886     break;
887   case Instruction::Or:
888     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
889                              KnownZero, KnownOne, Depth+1))
890       return true;
891     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
892     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
893                              KnownZero2, KnownOne2, Depth+1))
894       return true;
895     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
896     
897     // If all of the demanded bits are known zero on one side, return the other.
898     // These bits cannot contribute to the result of the 'or'.
899     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
900       return UpdateValueUsesWith(I, I->getOperand(0));
901     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
902       return UpdateValueUsesWith(I, I->getOperand(1));
903
904     // If all of the potentially set bits on one side are known to be set on
905     // the other side, just use the 'other' side.
906     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
907         (DemandedMask & (~KnownZero)))
908       return UpdateValueUsesWith(I, I->getOperand(0));
909     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
910         (DemandedMask & (~KnownZero2)))
911       return UpdateValueUsesWith(I, I->getOperand(1));
912         
913     // If the RHS is a constant, see if we can simplify it.
914     if (ShrinkDemandedConstant(I, 1, DemandedMask))
915       return UpdateValueUsesWith(I, I);
916           
917     // Output known-0 bits are only known if clear in both the LHS & RHS.
918     KnownZero &= KnownZero2;
919     // Output known-1 are known to be set if set in either the LHS | RHS.
920     KnownOne |= KnownOne2;
921     break;
922   case Instruction::Xor: {
923     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
924                              KnownZero, KnownOne, Depth+1))
925       return true;
926     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
927     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
928                              KnownZero2, KnownOne2, Depth+1))
929       return true;
930     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
931     
932     // If all of the demanded bits are known zero on one side, return the other.
933     // These bits cannot contribute to the result of the 'xor'.
934     if ((DemandedMask & KnownZero) == DemandedMask)
935       return UpdateValueUsesWith(I, I->getOperand(0));
936     if ((DemandedMask & KnownZero2) == DemandedMask)
937       return UpdateValueUsesWith(I, I->getOperand(1));
938     
939     // Output known-0 bits are known if clear or set in both the LHS & RHS.
940     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
941     // Output known-1 are known to be set if set in only one of the LHS, RHS.
942     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
943     
944     // If all of the demanded bits are known to be zero on one side or the
945     // other, turn this into an *inclusive* or.
946     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
947     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
948       Instruction *Or =
949         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
950                                  I->getName());
951       InsertNewInstBefore(Or, *I);
952       return UpdateValueUsesWith(I, Or);
953     }
954     
955     // If all of the demanded bits on one side are known, and all of the set
956     // bits on that side are also known to be set on the other side, turn this
957     // into an AND, as we know the bits will be cleared.
958     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
959     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
960       if ((KnownOne & KnownOne2) == KnownOne) {
961         Constant *AndC = ConstantInt::get(I->getType(), 
962                                           ~KnownOne & DemandedMask);
963         Instruction *And = 
964           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
965         InsertNewInstBefore(And, *I);
966         return UpdateValueUsesWith(I, And);
967       }
968     }
969     
970     // If the RHS is a constant, see if we can simplify it.
971     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
972     if (ShrinkDemandedConstant(I, 1, DemandedMask))
973       return UpdateValueUsesWith(I, I);
974     
975     KnownZero = KnownZeroOut;
976     KnownOne  = KnownOneOut;
977     break;
978   }
979   case Instruction::Select:
980     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
981                              KnownZero, KnownOne, Depth+1))
982       return true;
983     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
984                              KnownZero2, KnownOne2, Depth+1))
985       return true;
986     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
987     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
988     
989     // If the operands are constants, see if we can simplify them.
990     if (ShrinkDemandedConstant(I, 1, DemandedMask))
991       return UpdateValueUsesWith(I, I);
992     if (ShrinkDemandedConstant(I, 2, DemandedMask))
993       return UpdateValueUsesWith(I, I);
994     
995     // Only known if known in both the LHS and RHS.
996     KnownOne &= KnownOne2;
997     KnownZero &= KnownZero2;
998     break;
999   case Instruction::Trunc:
1000     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1001                              KnownZero, KnownOne, Depth+1))
1002       return true;
1003     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1004     break;
1005   case Instruction::BitCast:
1006     if (!I->getOperand(0)->getType()->isInteger())
1007       return false;
1008       
1009     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1010                              KnownZero, KnownOne, Depth+1))
1011       return true;
1012     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1013     break;
1014   case Instruction::ZExt: {
1015     // Compute the bits in the result that are not present in the input.
1016     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1017     uint64_t NotIn = ~SrcTy->getBitMask();
1018     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1019     
1020     DemandedMask &= SrcTy->getBitMask();
1021     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1022                              KnownZero, KnownOne, Depth+1))
1023       return true;
1024     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1025     // The top bits are known to be zero.
1026     KnownZero |= NewBits;
1027     break;
1028   }
1029   case Instruction::SExt: {
1030     // Compute the bits in the result that are not present in the input.
1031     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1032     uint64_t NotIn = ~SrcTy->getBitMask();
1033     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1034     
1035     // Get the sign bit for the source type
1036     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1037     int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1038
1039     // If any of the sign extended bits are demanded, we know that the sign
1040     // bit is demanded.
1041     if (NewBits & DemandedMask)
1042       InputDemandedBits |= InSignBit;
1043       
1044     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1045                              KnownZero, KnownOne, Depth+1))
1046       return true;
1047     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1048       
1049     // If the sign bit of the input is known set or clear, then we know the
1050     // top bits of the result.
1051
1052     // If the input sign bit is known zero, or if the NewBits are not demanded
1053     // convert this into a zero extension.
1054     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1055       // Convert to ZExt cast
1056       CastInst *NewCast = CastInst::create(
1057         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1058       return UpdateValueUsesWith(I, NewCast);
1059     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1060       KnownOne |= NewBits;
1061       KnownZero &= ~NewBits;
1062     } else {                              // Input sign bit unknown
1063       KnownZero &= ~NewBits;
1064       KnownOne &= ~NewBits;
1065     }
1066     break;
1067   }
1068   case Instruction::Add:
1069     // If there is a constant on the RHS, there are a variety of xformations
1070     // we can do.
1071     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1072       // If null, this should be simplified elsewhere.  Some of the xforms here
1073       // won't work if the RHS is zero.
1074       if (RHS->isNullValue())
1075         break;
1076       
1077       // Figure out what the input bits are.  If the top bits of the and result
1078       // are not demanded, then the add doesn't demand them from its input
1079       // either.
1080       
1081       // Shift the demanded mask up so that it's at the top of the uint64_t.
1082       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1083       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1084       
1085       // If the top bit of the output is demanded, demand everything from the
1086       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1087       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1088
1089       // Find information about known zero/one bits in the input.
1090       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1091                                KnownZero2, KnownOne2, Depth+1))
1092         return true;
1093
1094       // If the RHS of the add has bits set that can't affect the input, reduce
1095       // the constant.
1096       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1097         return UpdateValueUsesWith(I, I);
1098       
1099       // Avoid excess work.
1100       if (KnownZero2 == 0 && KnownOne2 == 0)
1101         break;
1102       
1103       // Turn it into OR if input bits are zero.
1104       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1105         Instruction *Or =
1106           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1107                                    I->getName());
1108         InsertNewInstBefore(Or, *I);
1109         return UpdateValueUsesWith(I, Or);
1110       }
1111       
1112       // We can say something about the output known-zero and known-one bits,
1113       // depending on potential carries from the input constant and the
1114       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1115       // bits set and the RHS constant is 0x01001, then we know we have a known
1116       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1117       
1118       // To compute this, we first compute the potential carry bits.  These are
1119       // the bits which may be modified.  I'm not aware of a better way to do
1120       // this scan.
1121       uint64_t RHSVal = RHS->getZExtValue();
1122       
1123       bool CarryIn = false;
1124       uint64_t CarryBits = 0;
1125       uint64_t CurBit = 1;
1126       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1127         // Record the current carry in.
1128         if (CarryIn) CarryBits |= CurBit;
1129         
1130         bool CarryOut;
1131         
1132         // This bit has a carry out unless it is "zero + zero" or
1133         // "zero + anything" with no carry in.
1134         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1135           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1136         } else if (!CarryIn &&
1137                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1138           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1139         } else {
1140           // Otherwise, we have to assume we have a carry out.
1141           CarryOut = true;
1142         }
1143         
1144         // This stage's carry out becomes the next stage's carry-in.
1145         CarryIn = CarryOut;
1146       }
1147       
1148       // Now that we know which bits have carries, compute the known-1/0 sets.
1149       
1150       // Bits are known one if they are known zero in one operand and one in the
1151       // other, and there is no input carry.
1152       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1153       
1154       // Bits are known zero if they are known zero in both operands and there
1155       // is no input carry.
1156       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1157     }
1158     break;
1159   case Instruction::Shl:
1160     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161       uint64_t ShiftAmt = SA->getZExtValue();
1162       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1163                                KnownZero, KnownOne, Depth+1))
1164         return true;
1165       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1166       KnownZero <<= ShiftAmt;
1167       KnownOne  <<= ShiftAmt;
1168       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1169     }
1170     break;
1171   case Instruction::LShr:
1172     // For a logical shift right
1173     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174       unsigned ShiftAmt = SA->getZExtValue();
1175       
1176       // Compute the new bits that are at the top now.
1177       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1178       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1179       uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
1180       // Unsigned shift right.
1181       if (SimplifyDemandedBits(I->getOperand(0),
1182                               (DemandedMask << ShiftAmt) & TypeMask,
1183                                KnownZero, KnownOne, Depth+1))
1184         return true;
1185       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1186       KnownZero &= TypeMask;
1187       KnownOne  &= TypeMask;
1188       KnownZero >>= ShiftAmt;
1189       KnownOne  >>= ShiftAmt;
1190       KnownZero |= HighBits;  // high bits known zero.
1191     }
1192     break;
1193   case Instruction::AShr:
1194     // If this is an arithmetic shift right and only the low-bit is set, we can
1195     // always convert this into a logical shr, even if the shift amount is
1196     // variable.  The low bit of the shift cannot be an input sign bit unless
1197     // the shift amount is >= the size of the datatype, which is undefined.
1198     if (DemandedMask == 1) {
1199       // Perform the logical shift right.
1200       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1201                                     I->getOperand(1), I->getName());
1202       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1203       return UpdateValueUsesWith(I, NewVal);
1204     }    
1205     
1206     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1207       unsigned ShiftAmt = SA->getZExtValue();
1208       
1209       // Compute the new bits that are at the top now.
1210       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1211       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1212       uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
1213       // Signed shift right.
1214       if (SimplifyDemandedBits(I->getOperand(0),
1215                                (DemandedMask << ShiftAmt) & TypeMask,
1216                                KnownZero, KnownOne, Depth+1))
1217         return true;
1218       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1219       KnownZero &= TypeMask;
1220       KnownOne  &= TypeMask;
1221       KnownZero >>= ShiftAmt;
1222       KnownOne  >>= ShiftAmt;
1223         
1224       // Handle the sign bits.
1225       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1226       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1227         
1228       // If the input sign bit is known to be zero, or if none of the top bits
1229       // are demanded, turn this into an unsigned shift right.
1230       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1231         // Perform the logical shift right.
1232         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1233                                       SA, I->getName());
1234         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1235         return UpdateValueUsesWith(I, NewVal);
1236       } else if (KnownOne & SignBit) { // New bits are known one.
1237         KnownOne |= HighBits;
1238       }
1239     }
1240     break;
1241   }
1242   
1243   // If the client is only demanding bits that we know, return the known
1244   // constant.
1245   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1246     return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
1247   return false;
1248 }  
1249
1250
1251 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1252 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1253 /// actually used by the caller.  This method analyzes which elements of the
1254 /// operand are undef and returns that information in UndefElts.
1255 ///
1256 /// If the information about demanded elements can be used to simplify the
1257 /// operation, the operation is simplified, then the resultant value is
1258 /// returned.  This returns null if no change was made.
1259 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1260                                                 uint64_t &UndefElts,
1261                                                 unsigned Depth) {
1262   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1263   assert(VWidth <= 64 && "Vector too wide to analyze!");
1264   uint64_t EltMask = ~0ULL >> (64-VWidth);
1265   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1266          "Invalid DemandedElts!");
1267
1268   if (isa<UndefValue>(V)) {
1269     // If the entire vector is undefined, just return this info.
1270     UndefElts = EltMask;
1271     return 0;
1272   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1273     UndefElts = EltMask;
1274     return UndefValue::get(V->getType());
1275   }
1276   
1277   UndefElts = 0;
1278   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1279     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1280     Constant *Undef = UndefValue::get(EltTy);
1281
1282     std::vector<Constant*> Elts;
1283     for (unsigned i = 0; i != VWidth; ++i)
1284       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1285         Elts.push_back(Undef);
1286         UndefElts |= (1ULL << i);
1287       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1288         Elts.push_back(Undef);
1289         UndefElts |= (1ULL << i);
1290       } else {                               // Otherwise, defined.
1291         Elts.push_back(CP->getOperand(i));
1292       }
1293         
1294     // If we changed the constant, return it.
1295     Constant *NewCP = ConstantPacked::get(Elts);
1296     return NewCP != CP ? NewCP : 0;
1297   } else if (isa<ConstantAggregateZero>(V)) {
1298     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1299     // set to undef.
1300     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1301     Constant *Zero = Constant::getNullValue(EltTy);
1302     Constant *Undef = UndefValue::get(EltTy);
1303     std::vector<Constant*> Elts;
1304     for (unsigned i = 0; i != VWidth; ++i)
1305       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1306     UndefElts = DemandedElts ^ EltMask;
1307     return ConstantPacked::get(Elts);
1308   }
1309   
1310   if (!V->hasOneUse()) {    // Other users may use these bits.
1311     if (Depth != 0) {       // Not at the root.
1312       // TODO: Just compute the UndefElts information recursively.
1313       return false;
1314     }
1315     return false;
1316   } else if (Depth == 10) {        // Limit search depth.
1317     return false;
1318   }
1319   
1320   Instruction *I = dyn_cast<Instruction>(V);
1321   if (!I) return false;        // Only analyze instructions.
1322   
1323   bool MadeChange = false;
1324   uint64_t UndefElts2;
1325   Value *TmpV;
1326   switch (I->getOpcode()) {
1327   default: break;
1328     
1329   case Instruction::InsertElement: {
1330     // If this is a variable index, we don't know which element it overwrites.
1331     // demand exactly the same input as we produce.
1332     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1333     if (Idx == 0) {
1334       // Note that we can't propagate undef elt info, because we don't know
1335       // which elt is getting updated.
1336       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1337                                         UndefElts2, Depth+1);
1338       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1339       break;
1340     }
1341     
1342     // If this is inserting an element that isn't demanded, remove this
1343     // insertelement.
1344     unsigned IdxNo = Idx->getZExtValue();
1345     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1346       return AddSoonDeadInstToWorklist(*I, 0);
1347     
1348     // Otherwise, the element inserted overwrites whatever was there, so the
1349     // input demanded set is simpler than the output set.
1350     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1351                                       DemandedElts & ~(1ULL << IdxNo),
1352                                       UndefElts, Depth+1);
1353     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1354
1355     // The inserted element is defined.
1356     UndefElts |= 1ULL << IdxNo;
1357     break;
1358   }
1359     
1360   case Instruction::And:
1361   case Instruction::Or:
1362   case Instruction::Xor:
1363   case Instruction::Add:
1364   case Instruction::Sub:
1365   case Instruction::Mul:
1366     // div/rem demand all inputs, because they don't want divide by zero.
1367     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1368                                       UndefElts, Depth+1);
1369     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1370     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1371                                       UndefElts2, Depth+1);
1372     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1373       
1374     // Output elements are undefined if both are undefined.  Consider things
1375     // like undef&0.  The result is known zero, not undef.
1376     UndefElts &= UndefElts2;
1377     break;
1378     
1379   case Instruction::Call: {
1380     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1381     if (!II) break;
1382     switch (II->getIntrinsicID()) {
1383     default: break;
1384       
1385     // Binary vector operations that work column-wise.  A dest element is a
1386     // function of the corresponding input elements from the two inputs.
1387     case Intrinsic::x86_sse_sub_ss:
1388     case Intrinsic::x86_sse_mul_ss:
1389     case Intrinsic::x86_sse_min_ss:
1390     case Intrinsic::x86_sse_max_ss:
1391     case Intrinsic::x86_sse2_sub_sd:
1392     case Intrinsic::x86_sse2_mul_sd:
1393     case Intrinsic::x86_sse2_min_sd:
1394     case Intrinsic::x86_sse2_max_sd:
1395       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1396                                         UndefElts, Depth+1);
1397       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1398       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1399                                         UndefElts2, Depth+1);
1400       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1401
1402       // If only the low elt is demanded and this is a scalarizable intrinsic,
1403       // scalarize it now.
1404       if (DemandedElts == 1) {
1405         switch (II->getIntrinsicID()) {
1406         default: break;
1407         case Intrinsic::x86_sse_sub_ss:
1408         case Intrinsic::x86_sse_mul_ss:
1409         case Intrinsic::x86_sse2_sub_sd:
1410         case Intrinsic::x86_sse2_mul_sd:
1411           // TODO: Lower MIN/MAX/ABS/etc
1412           Value *LHS = II->getOperand(1);
1413           Value *RHS = II->getOperand(2);
1414           // Extract the element as scalars.
1415           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1416           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1417           
1418           switch (II->getIntrinsicID()) {
1419           default: assert(0 && "Case stmts out of sync!");
1420           case Intrinsic::x86_sse_sub_ss:
1421           case Intrinsic::x86_sse2_sub_sd:
1422             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1423                                                         II->getName()), *II);
1424             break;
1425           case Intrinsic::x86_sse_mul_ss:
1426           case Intrinsic::x86_sse2_mul_sd:
1427             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1428                                                          II->getName()), *II);
1429             break;
1430           }
1431           
1432           Instruction *New =
1433             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1434                                   II->getName());
1435           InsertNewInstBefore(New, *II);
1436           AddSoonDeadInstToWorklist(*II, 0);
1437           return New;
1438         }            
1439       }
1440         
1441       // Output elements are undefined if both are undefined.  Consider things
1442       // like undef&0.  The result is known zero, not undef.
1443       UndefElts &= UndefElts2;
1444       break;
1445     }
1446     break;
1447   }
1448   }
1449   return MadeChange ? I : 0;
1450 }
1451
1452 /// @returns true if the specified compare instruction is
1453 /// true when both operands are equal...
1454 /// @brief Determine if the ICmpInst returns true if both operands are equal
1455 static bool isTrueWhenEqual(ICmpInst &ICI) {
1456   ICmpInst::Predicate pred = ICI.getPredicate();
1457   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1458          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1459          pred == ICmpInst::ICMP_SLE;
1460 }
1461
1462 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1463 /// function is designed to check a chain of associative operators for a
1464 /// potential to apply a certain optimization.  Since the optimization may be
1465 /// applicable if the expression was reassociated, this checks the chain, then
1466 /// reassociates the expression as necessary to expose the optimization
1467 /// opportunity.  This makes use of a special Functor, which must define
1468 /// 'shouldApply' and 'apply' methods.
1469 ///
1470 template<typename Functor>
1471 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1472   unsigned Opcode = Root.getOpcode();
1473   Value *LHS = Root.getOperand(0);
1474
1475   // Quick check, see if the immediate LHS matches...
1476   if (F.shouldApply(LHS))
1477     return F.apply(Root);
1478
1479   // Otherwise, if the LHS is not of the same opcode as the root, return.
1480   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1481   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1482     // Should we apply this transform to the RHS?
1483     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1484
1485     // If not to the RHS, check to see if we should apply to the LHS...
1486     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1487       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1488       ShouldApply = true;
1489     }
1490
1491     // If the functor wants to apply the optimization to the RHS of LHSI,
1492     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1493     if (ShouldApply) {
1494       BasicBlock *BB = Root.getParent();
1495
1496       // Now all of the instructions are in the current basic block, go ahead
1497       // and perform the reassociation.
1498       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1499
1500       // First move the selected RHS to the LHS of the root...
1501       Root.setOperand(0, LHSI->getOperand(1));
1502
1503       // Make what used to be the LHS of the root be the user of the root...
1504       Value *ExtraOperand = TmpLHSI->getOperand(1);
1505       if (&Root == TmpLHSI) {
1506         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1507         return 0;
1508       }
1509       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1510       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1511       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1512       BasicBlock::iterator ARI = &Root; ++ARI;
1513       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1514       ARI = Root;
1515
1516       // Now propagate the ExtraOperand down the chain of instructions until we
1517       // get to LHSI.
1518       while (TmpLHSI != LHSI) {
1519         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1520         // Move the instruction to immediately before the chain we are
1521         // constructing to avoid breaking dominance properties.
1522         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1523         BB->getInstList().insert(ARI, NextLHSI);
1524         ARI = NextLHSI;
1525
1526         Value *NextOp = NextLHSI->getOperand(1);
1527         NextLHSI->setOperand(1, ExtraOperand);
1528         TmpLHSI = NextLHSI;
1529         ExtraOperand = NextOp;
1530       }
1531
1532       // Now that the instructions are reassociated, have the functor perform
1533       // the transformation...
1534       return F.apply(Root);
1535     }
1536
1537     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1538   }
1539   return 0;
1540 }
1541
1542
1543 // AddRHS - Implements: X + X --> X << 1
1544 struct AddRHS {
1545   Value *RHS;
1546   AddRHS(Value *rhs) : RHS(rhs) {}
1547   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1548   Instruction *apply(BinaryOperator &Add) const {
1549     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1550                          ConstantInt::get(Type::Int8Ty, 1));
1551   }
1552 };
1553
1554 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1555 //                 iff C1&C2 == 0
1556 struct AddMaskingAnd {
1557   Constant *C2;
1558   AddMaskingAnd(Constant *c) : C2(c) {}
1559   bool shouldApply(Value *LHS) const {
1560     ConstantInt *C1;
1561     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1562            ConstantExpr::getAnd(C1, C2)->isNullValue();
1563   }
1564   Instruction *apply(BinaryOperator &Add) const {
1565     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1566   }
1567 };
1568
1569 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1570                                              InstCombiner *IC) {
1571   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1572     if (Constant *SOC = dyn_cast<Constant>(SO))
1573       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1574
1575     return IC->InsertNewInstBefore(CastInst::create(
1576           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1577   }
1578
1579   // Figure out if the constant is the left or the right argument.
1580   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1581   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1582
1583   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1584     if (ConstIsRHS)
1585       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1586     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1587   }
1588
1589   Value *Op0 = SO, *Op1 = ConstOperand;
1590   if (!ConstIsRHS)
1591     std::swap(Op0, Op1);
1592   Instruction *New;
1593   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1594     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1595   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1596     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1597                           SO->getName()+".cmp");
1598   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1599     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1600   else {
1601     assert(0 && "Unknown binary instruction type!");
1602     abort();
1603   }
1604   return IC->InsertNewInstBefore(New, I);
1605 }
1606
1607 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1608 // constant as the other operand, try to fold the binary operator into the
1609 // select arguments.  This also works for Cast instructions, which obviously do
1610 // not have a second operand.
1611 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1612                                      InstCombiner *IC) {
1613   // Don't modify shared select instructions
1614   if (!SI->hasOneUse()) return 0;
1615   Value *TV = SI->getOperand(1);
1616   Value *FV = SI->getOperand(2);
1617
1618   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1619     // Bool selects with constant operands can be folded to logical ops.
1620     if (SI->getType() == Type::Int1Ty) return 0;
1621
1622     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1623     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1624
1625     return new SelectInst(SI->getCondition(), SelectTrueVal,
1626                           SelectFalseVal);
1627   }
1628   return 0;
1629 }
1630
1631
1632 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1633 /// node as operand #0, see if we can fold the instruction into the PHI (which
1634 /// is only possible if all operands to the PHI are constants).
1635 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1636   PHINode *PN = cast<PHINode>(I.getOperand(0));
1637   unsigned NumPHIValues = PN->getNumIncomingValues();
1638   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1639
1640   // Check to see if all of the operands of the PHI are constants.  If there is
1641   // one non-constant value, remember the BB it is.  If there is more than one
1642   // bail out.
1643   BasicBlock *NonConstBB = 0;
1644   for (unsigned i = 0; i != NumPHIValues; ++i)
1645     if (!isa<Constant>(PN->getIncomingValue(i))) {
1646       if (NonConstBB) return 0;  // More than one non-const value.
1647       NonConstBB = PN->getIncomingBlock(i);
1648       
1649       // If the incoming non-constant value is in I's block, we have an infinite
1650       // loop.
1651       if (NonConstBB == I.getParent())
1652         return 0;
1653     }
1654   
1655   // If there is exactly one non-constant value, we can insert a copy of the
1656   // operation in that block.  However, if this is a critical edge, we would be
1657   // inserting the computation one some other paths (e.g. inside a loop).  Only
1658   // do this if the pred block is unconditionally branching into the phi block.
1659   if (NonConstBB) {
1660     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1661     if (!BI || !BI->isUnconditional()) return 0;
1662   }
1663
1664   // Okay, we can do the transformation: create the new PHI node.
1665   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1666   I.setName("");
1667   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1668   InsertNewInstBefore(NewPN, *PN);
1669
1670   // Next, add all of the operands to the PHI.
1671   if (I.getNumOperands() == 2) {
1672     Constant *C = cast<Constant>(I.getOperand(1));
1673     for (unsigned i = 0; i != NumPHIValues; ++i) {
1674       Value *InV;
1675       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1676         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1677           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1678         else
1679           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1680       } else {
1681         assert(PN->getIncomingBlock(i) == NonConstBB);
1682         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1683           InV = BinaryOperator::create(BO->getOpcode(),
1684                                        PN->getIncomingValue(i), C, "phitmp",
1685                                        NonConstBB->getTerminator());
1686         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1687           InV = CmpInst::create(CI->getOpcode(), 
1688                                 CI->getPredicate(),
1689                                 PN->getIncomingValue(i), C, "phitmp",
1690                                 NonConstBB->getTerminator());
1691         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1692           InV = new ShiftInst(SI->getOpcode(),
1693                               PN->getIncomingValue(i), C, "phitmp",
1694                               NonConstBB->getTerminator());
1695         else
1696           assert(0 && "Unknown binop!");
1697         
1698         WorkList.push_back(cast<Instruction>(InV));
1699       }
1700       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1701     }
1702   } else { 
1703     CastInst *CI = cast<CastInst>(&I);
1704     const Type *RetTy = CI->getType();
1705     for (unsigned i = 0; i != NumPHIValues; ++i) {
1706       Value *InV;
1707       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1708         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1709       } else {
1710         assert(PN->getIncomingBlock(i) == NonConstBB);
1711         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1712                                I.getType(), "phitmp", 
1713                                NonConstBB->getTerminator());
1714         WorkList.push_back(cast<Instruction>(InV));
1715       }
1716       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1717     }
1718   }
1719   return ReplaceInstUsesWith(I, NewPN);
1720 }
1721
1722 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1723   bool Changed = SimplifyCommutative(I);
1724   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1725
1726   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1727     // X + undef -> undef
1728     if (isa<UndefValue>(RHS))
1729       return ReplaceInstUsesWith(I, RHS);
1730
1731     // X + 0 --> X
1732     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1733       if (RHSC->isNullValue())
1734         return ReplaceInstUsesWith(I, LHS);
1735     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1736       if (CFP->isExactlyValue(-0.0))
1737         return ReplaceInstUsesWith(I, LHS);
1738     }
1739
1740     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1741       // X + (signbit) --> X ^ signbit
1742       uint64_t Val = CI->getZExtValue();
1743       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1744         return BinaryOperator::createXor(LHS, RHS);
1745       
1746       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1747       // (X & 254)+1 -> (X&254)|1
1748       uint64_t KnownZero, KnownOne;
1749       if (!isa<PackedType>(I.getType()) &&
1750           SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
1751                                KnownZero, KnownOne))
1752         return &I;
1753     }
1754
1755     if (isa<PHINode>(LHS))
1756       if (Instruction *NV = FoldOpIntoPhi(I))
1757         return NV;
1758     
1759     ConstantInt *XorRHS = 0;
1760     Value *XorLHS = 0;
1761     if (isa<ConstantInt>(RHSC) &&
1762         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1763       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1764       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1765       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1766       
1767       uint64_t C0080Val = 1ULL << 31;
1768       int64_t CFF80Val = -C0080Val;
1769       unsigned Size = 32;
1770       do {
1771         if (TySizeBits > Size) {
1772           bool Found = false;
1773           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1774           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1775           if (RHSSExt == CFF80Val) {
1776             if (XorRHS->getZExtValue() == C0080Val)
1777               Found = true;
1778           } else if (RHSZExt == C0080Val) {
1779             if (XorRHS->getSExtValue() == CFF80Val)
1780               Found = true;
1781           }
1782           if (Found) {
1783             // This is a sign extend if the top bits are known zero.
1784             uint64_t Mask = ~0ULL;
1785             Mask <<= 64-(TySizeBits-Size);
1786             Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
1787             if (!MaskedValueIsZero(XorLHS, Mask))
1788               Size = 0;  // Not a sign ext, but can't be any others either.
1789             goto FoundSExt;
1790           }
1791         }
1792         Size >>= 1;
1793         C0080Val >>= Size;
1794         CFF80Val >>= Size;
1795       } while (Size >= 8);
1796       
1797 FoundSExt:
1798       const Type *MiddleType = 0;
1799       switch (Size) {
1800       default: break;
1801       case 32: MiddleType = Type::Int32Ty; break;
1802       case 16: MiddleType = Type::Int16Ty; break;
1803       case 8:  MiddleType = Type::Int8Ty; break;
1804       }
1805       if (MiddleType) {
1806         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1807         InsertNewInstBefore(NewTrunc, I);
1808         return new SExtInst(NewTrunc, I.getType());
1809       }
1810     }
1811   }
1812
1813   // X + X --> X << 1
1814   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1815     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1816
1817     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1818       if (RHSI->getOpcode() == Instruction::Sub)
1819         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1820           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1821     }
1822     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1823       if (LHSI->getOpcode() == Instruction::Sub)
1824         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1825           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1826     }
1827   }
1828
1829   // -A + B  -->  B - A
1830   if (Value *V = dyn_castNegVal(LHS))
1831     return BinaryOperator::createSub(RHS, V);
1832
1833   // A + -B  -->  A - B
1834   if (!isa<Constant>(RHS))
1835     if (Value *V = dyn_castNegVal(RHS))
1836       return BinaryOperator::createSub(LHS, V);
1837
1838
1839   ConstantInt *C2;
1840   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1841     if (X == RHS)   // X*C + X --> X * (C+1)
1842       return BinaryOperator::createMul(RHS, AddOne(C2));
1843
1844     // X*C1 + X*C2 --> X * (C1+C2)
1845     ConstantInt *C1;
1846     if (X == dyn_castFoldableMul(RHS, C1))
1847       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1848   }
1849
1850   // X + X*C --> X * (C+1)
1851   if (dyn_castFoldableMul(RHS, C2) == LHS)
1852     return BinaryOperator::createMul(LHS, AddOne(C2));
1853
1854   // X + ~X --> -1   since   ~X = -X-1
1855   if (dyn_castNotVal(LHS) == RHS ||
1856       dyn_castNotVal(RHS) == LHS)
1857     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1858   
1859
1860   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1861   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1862     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1863       return R;
1864
1865   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1866     Value *X = 0;
1867     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1868       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1869       return BinaryOperator::createSub(C, X);
1870     }
1871
1872     // (X & FF00) + xx00  -> (X+xx00) & FF00
1873     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1874       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1875       if (Anded == CRHS) {
1876         // See if all bits from the first bit set in the Add RHS up are included
1877         // in the mask.  First, get the rightmost bit.
1878         uint64_t AddRHSV = CRHS->getZExtValue();
1879
1880         // Form a mask of all bits from the lowest bit added through the top.
1881         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1882         AddRHSHighBits &= C2->getType()->getBitMask();
1883
1884         // See if the and mask includes all of these bits.
1885         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1886
1887         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1888           // Okay, the xform is safe.  Insert the new add pronto.
1889           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1890                                                             LHS->getName()), I);
1891           return BinaryOperator::createAnd(NewAdd, C2);
1892         }
1893       }
1894     }
1895
1896     // Try to fold constant add into select arguments.
1897     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1898       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1899         return R;
1900   }
1901
1902   // add (cast *A to intptrtype) B -> 
1903   //   cast (GEP (cast *A to sbyte*) B) -> 
1904   //     intptrtype
1905   {
1906     CastInst *CI = dyn_cast<CastInst>(LHS);
1907     Value *Other = RHS;
1908     if (!CI) {
1909       CI = dyn_cast<CastInst>(RHS);
1910       Other = LHS;
1911     }
1912     if (CI && CI->getType()->isSized() && 
1913         (CI->getType()->getPrimitiveSizeInBits() == 
1914          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1915         && isa<PointerType>(CI->getOperand(0)->getType())) {
1916       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1917                                    PointerType::get(Type::Int8Ty), I);
1918       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1919       return new PtrToIntInst(I2, CI->getType());
1920     }
1921   }
1922
1923   return Changed ? &I : 0;
1924 }
1925
1926 // isSignBit - Return true if the value represented by the constant only has the
1927 // highest order bit set.
1928 static bool isSignBit(ConstantInt *CI) {
1929   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1930   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1931 }
1932
1933 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1934   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1935
1936   if (Op0 == Op1)         // sub X, X  -> 0
1937     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1938
1939   // If this is a 'B = x-(-A)', change to B = x+A...
1940   if (Value *V = dyn_castNegVal(Op1))
1941     return BinaryOperator::createAdd(Op0, V);
1942
1943   if (isa<UndefValue>(Op0))
1944     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1945   if (isa<UndefValue>(Op1))
1946     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1947
1948   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1949     // Replace (-1 - A) with (~A)...
1950     if (C->isAllOnesValue())
1951       return BinaryOperator::createNot(Op1);
1952
1953     // C - ~X == X + (1+C)
1954     Value *X = 0;
1955     if (match(Op1, m_Not(m_Value(X))))
1956       return BinaryOperator::createAdd(X,
1957                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1958     // -(X >>u 31) -> (X >>s 31)
1959     // -(X >>s 31) -> (X >>u 31)
1960     if (C->isNullValue()) {
1961       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op1))
1962         if (SI->getOpcode() == Instruction::LShr) {
1963           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1964             // Check to see if we are shifting out everything but the sign bit.
1965             if (CU->getZExtValue() == 
1966                 SI->getType()->getPrimitiveSizeInBits()-1) {
1967               // Ok, the transformation is safe.  Insert AShr.
1968               return new ShiftInst(Instruction::AShr, SI->getOperand(0), CU,
1969                                    SI->getName());
1970             }
1971           }
1972         }
1973         else if (SI->getOpcode() == Instruction::AShr) {
1974           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1975             // Check to see if we are shifting out everything but the sign bit.
1976             if (CU->getZExtValue() == 
1977                 SI->getType()->getPrimitiveSizeInBits()-1) {
1978               // Ok, the transformation is safe.  Insert LShr. 
1979               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
1980                                    SI->getName());
1981             }
1982           }
1983         } 
1984     }
1985
1986     // Try to fold constant sub into select arguments.
1987     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1988       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1989         return R;
1990
1991     if (isa<PHINode>(Op0))
1992       if (Instruction *NV = FoldOpIntoPhi(I))
1993         return NV;
1994   }
1995
1996   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1997     if (Op1I->getOpcode() == Instruction::Add &&
1998         !Op0->getType()->isFPOrFPVector()) {
1999       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2000         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2001       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2002         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2003       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2004         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2005           // C1-(X+C2) --> (C1-C2)-X
2006           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2007                                            Op1I->getOperand(0));
2008       }
2009     }
2010
2011     if (Op1I->hasOneUse()) {
2012       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2013       // is not used by anyone else...
2014       //
2015       if (Op1I->getOpcode() == Instruction::Sub &&
2016           !Op1I->getType()->isFPOrFPVector()) {
2017         // Swap the two operands of the subexpr...
2018         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2019         Op1I->setOperand(0, IIOp1);
2020         Op1I->setOperand(1, IIOp0);
2021
2022         // Create the new top level add instruction...
2023         return BinaryOperator::createAdd(Op0, Op1);
2024       }
2025
2026       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2027       //
2028       if (Op1I->getOpcode() == Instruction::And &&
2029           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2030         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2031
2032         Value *NewNot =
2033           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2034         return BinaryOperator::createAnd(Op0, NewNot);
2035       }
2036
2037       // 0 - (X sdiv C)  -> (X sdiv -C)
2038       if (Op1I->getOpcode() == Instruction::SDiv)
2039         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2040           if (CSI->isNullValue())
2041             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2042               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2043                                                ConstantExpr::getNeg(DivRHS));
2044
2045       // X - X*C --> X * (1-C)
2046       ConstantInt *C2 = 0;
2047       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2048         Constant *CP1 =
2049           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2050         return BinaryOperator::createMul(Op0, CP1);
2051       }
2052     }
2053   }
2054
2055   if (!Op0->getType()->isFPOrFPVector())
2056     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2057       if (Op0I->getOpcode() == Instruction::Add) {
2058         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2059           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2060         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2061           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2062       } else if (Op0I->getOpcode() == Instruction::Sub) {
2063         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2064           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2065       }
2066
2067   ConstantInt *C1;
2068   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2069     if (X == Op1) { // X*C - X --> X * (C-1)
2070       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2071       return BinaryOperator::createMul(Op1, CP1);
2072     }
2073
2074     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2075     if (X == dyn_castFoldableMul(Op1, C2))
2076       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2077   }
2078   return 0;
2079 }
2080
2081 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2082 /// really just returns true if the most significant (sign) bit is set.
2083 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2084   switch (pred) {
2085     case ICmpInst::ICMP_SLT: 
2086       // True if LHS s< RHS and RHS == 0
2087       return RHS->isNullValue();
2088     case ICmpInst::ICMP_SLE: 
2089       // True if LHS s<= RHS and RHS == -1
2090       return RHS->isAllOnesValue();
2091     case ICmpInst::ICMP_UGE: 
2092       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2093       return RHS->getZExtValue() == (1ULL << 
2094         (RHS->getType()->getPrimitiveSizeInBits()-1));
2095     case ICmpInst::ICMP_UGT:
2096       // True if LHS u> RHS and RHS == high-bit-mask - 1
2097       return RHS->getZExtValue() ==
2098         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2099     default:
2100       return false;
2101   }
2102 }
2103
2104 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2105   bool Changed = SimplifyCommutative(I);
2106   Value *Op0 = I.getOperand(0);
2107
2108   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2109     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2110
2111   // Simplify mul instructions with a constant RHS...
2112   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2113     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2114
2115       // ((X << C1)*C2) == (X * (C2 << C1))
2116       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2117         if (SI->getOpcode() == Instruction::Shl)
2118           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2119             return BinaryOperator::createMul(SI->getOperand(0),
2120                                              ConstantExpr::getShl(CI, ShOp));
2121
2122       if (CI->isNullValue())
2123         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2124       if (CI->equalsInt(1))                  // X * 1  == X
2125         return ReplaceInstUsesWith(I, Op0);
2126       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2127         return BinaryOperator::createNeg(Op0, I.getName());
2128
2129       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2130       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2131         uint64_t C = Log2_64(Val);
2132         return new ShiftInst(Instruction::Shl, Op0,
2133                              ConstantInt::get(Type::Int8Ty, C));
2134       }
2135     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2136       if (Op1F->isNullValue())
2137         return ReplaceInstUsesWith(I, Op1);
2138
2139       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2140       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2141       if (Op1F->getValue() == 1.0)
2142         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2143     }
2144     
2145     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2146       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2147           isa<ConstantInt>(Op0I->getOperand(1))) {
2148         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2149         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2150                                                      Op1, "tmp");
2151         InsertNewInstBefore(Add, I);
2152         Value *C1C2 = ConstantExpr::getMul(Op1, 
2153                                            cast<Constant>(Op0I->getOperand(1)));
2154         return BinaryOperator::createAdd(Add, C1C2);
2155         
2156       }
2157
2158     // Try to fold constant mul into select arguments.
2159     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2160       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2161         return R;
2162
2163     if (isa<PHINode>(Op0))
2164       if (Instruction *NV = FoldOpIntoPhi(I))
2165         return NV;
2166   }
2167
2168   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2169     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2170       return BinaryOperator::createMul(Op0v, Op1v);
2171
2172   // If one of the operands of the multiply is a cast from a boolean value, then
2173   // we know the bool is either zero or one, so this is a 'masking' multiply.
2174   // See if we can simplify things based on how the boolean was originally
2175   // formed.
2176   CastInst *BoolCast = 0;
2177   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2178     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2179       BoolCast = CI;
2180   if (!BoolCast)
2181     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2182       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2183         BoolCast = CI;
2184   if (BoolCast) {
2185     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2186       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2187       const Type *SCOpTy = SCIOp0->getType();
2188
2189       // If the icmp is true iff the sign bit of X is set, then convert this
2190       // multiply into a shift/and combination.
2191       if (isa<ConstantInt>(SCIOp1) &&
2192           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2193         // Shift the X value right to turn it into "all signbits".
2194         Constant *Amt = ConstantInt::get(Type::Int8Ty,
2195                                           SCOpTy->getPrimitiveSizeInBits()-1);
2196         Value *V =
2197           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2198                                             BoolCast->getOperand(0)->getName()+
2199                                             ".mask"), I);
2200
2201         // If the multiply type is not the same as the source type, sign extend
2202         // or truncate to the multiply type.
2203         if (I.getType() != V->getType()) {
2204           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2205           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2206           Instruction::CastOps opcode = 
2207             (SrcBits == DstBits ? Instruction::BitCast : 
2208              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2209           V = InsertCastBefore(opcode, V, I.getType(), I);
2210         }
2211
2212         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2213         return BinaryOperator::createAnd(V, OtherOp);
2214       }
2215     }
2216   }
2217
2218   return Changed ? &I : 0;
2219 }
2220
2221 /// This function implements the transforms on div instructions that work
2222 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2223 /// used by the visitors to those instructions.
2224 /// @brief Transforms common to all three div instructions
2225 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2226   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2227
2228   // undef / X -> 0
2229   if (isa<UndefValue>(Op0))
2230     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2231
2232   // X / undef -> undef
2233   if (isa<UndefValue>(Op1))
2234     return ReplaceInstUsesWith(I, Op1);
2235
2236   // Handle cases involving: div X, (select Cond, Y, Z)
2237   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2238     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2239     // same basic block, then we replace the select with Y, and the condition 
2240     // of the select with false (if the cond value is in the same BB).  If the
2241     // select has uses other than the div, this allows them to be simplified
2242     // also. Note that div X, Y is just as good as div X, 0 (undef)
2243     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2244       if (ST->isNullValue()) {
2245         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2246         if (CondI && CondI->getParent() == I.getParent())
2247           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2248         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2249           I.setOperand(1, SI->getOperand(2));
2250         else
2251           UpdateValueUsesWith(SI, SI->getOperand(2));
2252         return &I;
2253       }
2254
2255     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2256     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2257       if (ST->isNullValue()) {
2258         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2259         if (CondI && CondI->getParent() == I.getParent())
2260           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2261         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2262           I.setOperand(1, SI->getOperand(1));
2263         else
2264           UpdateValueUsesWith(SI, SI->getOperand(1));
2265         return &I;
2266       }
2267   }
2268
2269   return 0;
2270 }
2271
2272 /// This function implements the transforms common to both integer division
2273 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2274 /// division instructions.
2275 /// @brief Common integer divide transforms
2276 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2277   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2278
2279   if (Instruction *Common = commonDivTransforms(I))
2280     return Common;
2281
2282   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2283     // div X, 1 == X
2284     if (RHS->equalsInt(1))
2285       return ReplaceInstUsesWith(I, Op0);
2286
2287     // (X / C1) / C2  -> X / (C1*C2)
2288     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2289       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2290         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2291           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2292                                         ConstantExpr::getMul(RHS, LHSRHS));
2293         }
2294
2295     if (!RHS->isNullValue()) { // avoid X udiv 0
2296       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2297         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2298           return R;
2299       if (isa<PHINode>(Op0))
2300         if (Instruction *NV = FoldOpIntoPhi(I))
2301           return NV;
2302     }
2303   }
2304
2305   // 0 / X == 0, we don't need to preserve faults!
2306   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2307     if (LHS->equalsInt(0))
2308       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2309
2310   return 0;
2311 }
2312
2313 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2314   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2315
2316   // Handle the integer div common cases
2317   if (Instruction *Common = commonIDivTransforms(I))
2318     return Common;
2319
2320   // X udiv C^2 -> X >> C
2321   // Check to see if this is an unsigned division with an exact power of 2,
2322   // if so, convert to a right shift.
2323   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2324     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2325       if (isPowerOf2_64(Val)) {
2326         uint64_t ShiftAmt = Log2_64(Val);
2327         return new ShiftInst(Instruction::LShr, Op0, 
2328                               ConstantInt::get(Type::Int8Ty, ShiftAmt));
2329       }
2330   }
2331
2332   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2333   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2334     if (RHSI->getOpcode() == Instruction::Shl &&
2335         isa<ConstantInt>(RHSI->getOperand(0))) {
2336       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2337       if (isPowerOf2_64(C1)) {
2338         Value *N = RHSI->getOperand(1);
2339         const Type *NTy = N->getType();
2340         if (uint64_t C2 = Log2_64(C1)) {
2341           Constant *C2V = ConstantInt::get(NTy, C2);
2342           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2343         }
2344         return new ShiftInst(Instruction::LShr, Op0, N);
2345       }
2346     }
2347   }
2348   
2349   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2350   // where C1&C2 are powers of two.
2351   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2352     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2353       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2354         if (!STO->isNullValue() && !STO->isNullValue()) {
2355           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2356           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2357             // Compute the shift amounts
2358             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2359             // Construct the "on true" case of the select
2360             Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2361             Instruction *TSI = 
2362               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2363             TSI = InsertNewInstBefore(TSI, I);
2364     
2365             // Construct the "on false" case of the select
2366             Constant *FC = ConstantInt::get(Type::Int8Ty, FSA); 
2367             Instruction *FSI = 
2368               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2369             FSI = InsertNewInstBefore(FSI, I);
2370
2371             // construct the select instruction and return it.
2372             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2373           }
2374         }
2375   }
2376   return 0;
2377 }
2378
2379 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2380   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2381
2382   // Handle the integer div common cases
2383   if (Instruction *Common = commonIDivTransforms(I))
2384     return Common;
2385
2386   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2387     // sdiv X, -1 == -X
2388     if (RHS->isAllOnesValue())
2389       return BinaryOperator::createNeg(Op0);
2390
2391     // -X/C -> X/-C
2392     if (Value *LHSNeg = dyn_castNegVal(Op0))
2393       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2394   }
2395
2396   // If the sign bits of both operands are zero (i.e. we can prove they are
2397   // unsigned inputs), turn this into a udiv.
2398   if (I.getType()->isInteger()) {
2399     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2400     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2401       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2402     }
2403   }      
2404   
2405   return 0;
2406 }
2407
2408 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2409   return commonDivTransforms(I);
2410 }
2411
2412 /// GetFactor - If we can prove that the specified value is at least a multiple
2413 /// of some factor, return that factor.
2414 static Constant *GetFactor(Value *V) {
2415   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2416     return CI;
2417   
2418   // Unless we can be tricky, we know this is a multiple of 1.
2419   Constant *Result = ConstantInt::get(V->getType(), 1);
2420   
2421   Instruction *I = dyn_cast<Instruction>(V);
2422   if (!I) return Result;
2423   
2424   if (I->getOpcode() == Instruction::Mul) {
2425     // Handle multiplies by a constant, etc.
2426     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2427                                 GetFactor(I->getOperand(1)));
2428   } else if (I->getOpcode() == Instruction::Shl) {
2429     // (X<<C) -> X * (1 << C)
2430     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2431       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2432       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2433     }
2434   } else if (I->getOpcode() == Instruction::And) {
2435     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2436       // X & 0xFFF0 is known to be a multiple of 16.
2437       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2438       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2439         return ConstantExpr::getShl(Result, 
2440                                     ConstantInt::get(Type::Int8Ty, Zeros));
2441     }
2442   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2443     // Only handle int->int casts.
2444     if (!CI->isIntegerCast())
2445       return Result;
2446     Value *Op = CI->getOperand(0);
2447     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2448   }    
2449   return Result;
2450 }
2451
2452 /// This function implements the transforms on rem instructions that work
2453 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2454 /// is used by the visitors to those instructions.
2455 /// @brief Transforms common to all three rem instructions
2456 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2457   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2458
2459   // 0 % X == 0, we don't need to preserve faults!
2460   if (Constant *LHS = dyn_cast<Constant>(Op0))
2461     if (LHS->isNullValue())
2462       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463
2464   if (isa<UndefValue>(Op0))              // undef % X -> 0
2465     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2466   if (isa<UndefValue>(Op1))
2467     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2468
2469   // Handle cases involving: rem X, (select Cond, Y, Z)
2470   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2471     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2472     // the same basic block, then we replace the select with Y, and the
2473     // condition of the select with false (if the cond value is in the same
2474     // BB).  If the select has uses other than the div, this allows them to be
2475     // simplified also.
2476     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2477       if (ST->isNullValue()) {
2478         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2479         if (CondI && CondI->getParent() == I.getParent())
2480           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2481         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2482           I.setOperand(1, SI->getOperand(2));
2483         else
2484           UpdateValueUsesWith(SI, SI->getOperand(2));
2485         return &I;
2486       }
2487     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2488     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2489       if (ST->isNullValue()) {
2490         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2491         if (CondI && CondI->getParent() == I.getParent())
2492           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2493         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2494           I.setOperand(1, SI->getOperand(1));
2495         else
2496           UpdateValueUsesWith(SI, SI->getOperand(1));
2497         return &I;
2498       }
2499   }
2500
2501   return 0;
2502 }
2503
2504 /// This function implements the transforms common to both integer remainder
2505 /// instructions (urem and srem). It is called by the visitors to those integer
2506 /// remainder instructions.
2507 /// @brief Common integer remainder transforms
2508 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2509   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2510
2511   if (Instruction *common = commonRemTransforms(I))
2512     return common;
2513
2514   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2515     // X % 0 == undef, we don't need to preserve faults!
2516     if (RHS->equalsInt(0))
2517       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2518     
2519     if (RHS->equalsInt(1))  // X % 1 == 0
2520       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2521
2522     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2523       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2524         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2525           return R;
2526       } else if (isa<PHINode>(Op0I)) {
2527         if (Instruction *NV = FoldOpIntoPhi(I))
2528           return NV;
2529       }
2530       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2531       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2532         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2533     }
2534   }
2535
2536   return 0;
2537 }
2538
2539 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2540   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2541
2542   if (Instruction *common = commonIRemTransforms(I))
2543     return common;
2544   
2545   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2546     // X urem C^2 -> X and C
2547     // Check to see if this is an unsigned remainder with an exact power of 2,
2548     // if so, convert to a bitwise and.
2549     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2550       if (isPowerOf2_64(C->getZExtValue()))
2551         return BinaryOperator::createAnd(Op0, SubOne(C));
2552   }
2553
2554   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2555     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2556     if (RHSI->getOpcode() == Instruction::Shl &&
2557         isa<ConstantInt>(RHSI->getOperand(0))) {
2558       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2559       if (isPowerOf2_64(C1)) {
2560         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2561         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2562                                                                    "tmp"), I);
2563         return BinaryOperator::createAnd(Op0, Add);
2564       }
2565     }
2566   }
2567
2568   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2569   // where C1&C2 are powers of two.
2570   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2571     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2572       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2573         // STO == 0 and SFO == 0 handled above.
2574         if (isPowerOf2_64(STO->getZExtValue()) && 
2575             isPowerOf2_64(SFO->getZExtValue())) {
2576           Value *TrueAnd = InsertNewInstBefore(
2577             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2578           Value *FalseAnd = InsertNewInstBefore(
2579             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2580           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2581         }
2582       }
2583   }
2584   
2585   return 0;
2586 }
2587
2588 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2589   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2590
2591   if (Instruction *common = commonIRemTransforms(I))
2592     return common;
2593   
2594   if (Value *RHSNeg = dyn_castNegVal(Op1))
2595     if (!isa<ConstantInt>(RHSNeg) || 
2596         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2597       // X % -Y -> X % Y
2598       AddUsesToWorkList(I);
2599       I.setOperand(1, RHSNeg);
2600       return &I;
2601     }
2602  
2603   // If the top bits of both operands are zero (i.e. we can prove they are
2604   // unsigned inputs), turn this into a urem.
2605   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2606   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2607     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2608     return BinaryOperator::createURem(Op0, Op1, I.getName());
2609   }
2610
2611   return 0;
2612 }
2613
2614 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2615   return commonRemTransforms(I);
2616 }
2617
2618 // isMaxValueMinusOne - return true if this is Max-1
2619 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2620   if (isSigned) {
2621     // Calculate 0111111111..11111
2622     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2623     int64_t Val = INT64_MAX;             // All ones
2624     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2625     return C->getSExtValue() == Val-1;
2626   }
2627   return C->getZExtValue() == C->getType()->getBitMask()-1;
2628 }
2629
2630 // isMinValuePlusOne - return true if this is Min+1
2631 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2632   if (isSigned) {
2633     // Calculate 1111111111000000000000
2634     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2635     int64_t Val = -1;                    // All ones
2636     Val <<= TypeBits-1;                  // Shift over to the right spot
2637     return C->getSExtValue() == Val+1;
2638   }
2639   return C->getZExtValue() == 1; // unsigned
2640 }
2641
2642 // isOneBitSet - Return true if there is exactly one bit set in the specified
2643 // constant.
2644 static bool isOneBitSet(const ConstantInt *CI) {
2645   uint64_t V = CI->getZExtValue();
2646   return V && (V & (V-1)) == 0;
2647 }
2648
2649 #if 0   // Currently unused
2650 // isLowOnes - Return true if the constant is of the form 0+1+.
2651 static bool isLowOnes(const ConstantInt *CI) {
2652   uint64_t V = CI->getZExtValue();
2653
2654   // There won't be bits set in parts that the type doesn't contain.
2655   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2656
2657   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2658   return U && V && (U & V) == 0;
2659 }
2660 #endif
2661
2662 // isHighOnes - Return true if the constant is of the form 1+0+.
2663 // This is the same as lowones(~X).
2664 static bool isHighOnes(const ConstantInt *CI) {
2665   uint64_t V = ~CI->getZExtValue();
2666   if (~V == 0) return false;  // 0's does not match "1+"
2667
2668   // There won't be bits set in parts that the type doesn't contain.
2669   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2670
2671   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2672   return U && V && (U & V) == 0;
2673 }
2674
2675 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2676 /// are carefully arranged to allow folding of expressions such as:
2677 ///
2678 ///      (A < B) | (A > B) --> (A != B)
2679 ///
2680 /// Note that this is only valid if the first and second predicates have the
2681 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2682 ///
2683 /// Three bits are used to represent the condition, as follows:
2684 ///   0  A > B
2685 ///   1  A == B
2686 ///   2  A < B
2687 ///
2688 /// <=>  Value  Definition
2689 /// 000     0   Always false
2690 /// 001     1   A >  B
2691 /// 010     2   A == B
2692 /// 011     3   A >= B
2693 /// 100     4   A <  B
2694 /// 101     5   A != B
2695 /// 110     6   A <= B
2696 /// 111     7   Always true
2697 ///  
2698 static unsigned getICmpCode(const ICmpInst *ICI) {
2699   switch (ICI->getPredicate()) {
2700     // False -> 0
2701   case ICmpInst::ICMP_UGT: return 1;  // 001
2702   case ICmpInst::ICMP_SGT: return 1;  // 001
2703   case ICmpInst::ICMP_EQ:  return 2;  // 010
2704   case ICmpInst::ICMP_UGE: return 3;  // 011
2705   case ICmpInst::ICMP_SGE: return 3;  // 011
2706   case ICmpInst::ICMP_ULT: return 4;  // 100
2707   case ICmpInst::ICMP_SLT: return 4;  // 100
2708   case ICmpInst::ICMP_NE:  return 5;  // 101
2709   case ICmpInst::ICMP_ULE: return 6;  // 110
2710   case ICmpInst::ICMP_SLE: return 6;  // 110
2711     // True -> 7
2712   default:
2713     assert(0 && "Invalid ICmp predicate!");
2714     return 0;
2715   }
2716 }
2717
2718 /// getICmpValue - This is the complement of getICmpCode, which turns an
2719 /// opcode and two operands into either a constant true or false, or a brand 
2720 /// new /// ICmp instruction. The sign is passed in to determine which kind
2721 /// of predicate to use in new icmp instructions.
2722 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2723   switch (code) {
2724   default: assert(0 && "Illegal ICmp code!");
2725   case  0: return ConstantInt::getFalse();
2726   case  1: 
2727     if (sign)
2728       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2729     else
2730       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2731   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2732   case  3: 
2733     if (sign)
2734       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2735     else
2736       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2737   case  4: 
2738     if (sign)
2739       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2740     else
2741       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2742   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2743   case  6: 
2744     if (sign)
2745       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2746     else
2747       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2748   case  7: return ConstantInt::getTrue();
2749   }
2750 }
2751
2752 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2753   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2754     (ICmpInst::isSignedPredicate(p1) && 
2755      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2756     (ICmpInst::isSignedPredicate(p2) && 
2757      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2758 }
2759
2760 namespace { 
2761 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2762 struct FoldICmpLogical {
2763   InstCombiner &IC;
2764   Value *LHS, *RHS;
2765   ICmpInst::Predicate pred;
2766   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2767     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2768       pred(ICI->getPredicate()) {}
2769   bool shouldApply(Value *V) const {
2770     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2771       if (PredicatesFoldable(pred, ICI->getPredicate()))
2772         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2773                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2774     return false;
2775   }
2776   Instruction *apply(Instruction &Log) const {
2777     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2778     if (ICI->getOperand(0) != LHS) {
2779       assert(ICI->getOperand(1) == LHS);
2780       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2781     }
2782
2783     unsigned LHSCode = getICmpCode(ICI);
2784     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2785     unsigned Code;
2786     switch (Log.getOpcode()) {
2787     case Instruction::And: Code = LHSCode & RHSCode; break;
2788     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2789     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2790     default: assert(0 && "Illegal logical opcode!"); return 0;
2791     }
2792
2793     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2794     if (Instruction *I = dyn_cast<Instruction>(RV))
2795       return I;
2796     // Otherwise, it's a constant boolean value...
2797     return IC.ReplaceInstUsesWith(Log, RV);
2798   }
2799 };
2800 } // end anonymous namespace
2801
2802 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2803 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2804 // guaranteed to be either a shift instruction or a binary operator.
2805 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2806                                     ConstantInt *OpRHS,
2807                                     ConstantInt *AndRHS,
2808                                     BinaryOperator &TheAnd) {
2809   Value *X = Op->getOperand(0);
2810   Constant *Together = 0;
2811   if (!isa<ShiftInst>(Op))
2812     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2813
2814   switch (Op->getOpcode()) {
2815   case Instruction::Xor:
2816     if (Op->hasOneUse()) {
2817       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2818       std::string OpName = Op->getName(); Op->setName("");
2819       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2820       InsertNewInstBefore(And, TheAnd);
2821       return BinaryOperator::createXor(And, Together);
2822     }
2823     break;
2824   case Instruction::Or:
2825     if (Together == AndRHS) // (X | C) & C --> C
2826       return ReplaceInstUsesWith(TheAnd, AndRHS);
2827
2828     if (Op->hasOneUse() && Together != OpRHS) {
2829       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2830       std::string Op0Name = Op->getName(); Op->setName("");
2831       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2832       InsertNewInstBefore(Or, TheAnd);
2833       return BinaryOperator::createAnd(Or, AndRHS);
2834     }
2835     break;
2836   case Instruction::Add:
2837     if (Op->hasOneUse()) {
2838       // Adding a one to a single bit bit-field should be turned into an XOR
2839       // of the bit.  First thing to check is to see if this AND is with a
2840       // single bit constant.
2841       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2842
2843       // Clear bits that are not part of the constant.
2844       AndRHSV &= AndRHS->getType()->getBitMask();
2845
2846       // If there is only one bit set...
2847       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2848         // Ok, at this point, we know that we are masking the result of the
2849         // ADD down to exactly one bit.  If the constant we are adding has
2850         // no bits set below this bit, then we can eliminate the ADD.
2851         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2852
2853         // Check to see if any bits below the one bit set in AndRHSV are set.
2854         if ((AddRHS & (AndRHSV-1)) == 0) {
2855           // If not, the only thing that can effect the output of the AND is
2856           // the bit specified by AndRHSV.  If that bit is set, the effect of
2857           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2858           // no effect.
2859           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2860             TheAnd.setOperand(0, X);
2861             return &TheAnd;
2862           } else {
2863             std::string Name = Op->getName(); Op->setName("");
2864             // Pull the XOR out of the AND.
2865             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2866             InsertNewInstBefore(NewAnd, TheAnd);
2867             return BinaryOperator::createXor(NewAnd, AndRHS);
2868           }
2869         }
2870       }
2871     }
2872     break;
2873
2874   case Instruction::Shl: {
2875     // We know that the AND will not produce any of the bits shifted in, so if
2876     // the anded constant includes them, clear them now!
2877     //
2878     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2879     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2880     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2881
2882     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2883       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2884     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2885       TheAnd.setOperand(1, CI);
2886       return &TheAnd;
2887     }
2888     break;
2889   }
2890   case Instruction::LShr:
2891   {
2892     // We know that the AND will not produce any of the bits shifted in, so if
2893     // the anded constant includes them, clear them now!  This only applies to
2894     // unsigned shifts, because a signed shr may bring in set bits!
2895     //
2896     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2897     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2898     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2899
2900     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2901       return ReplaceInstUsesWith(TheAnd, Op);
2902     } else if (CI != AndRHS) {
2903       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2904       return &TheAnd;
2905     }
2906     break;
2907   }
2908   case Instruction::AShr:
2909     // Signed shr.
2910     // See if this is shifting in some sign extension, then masking it out
2911     // with an and.
2912     if (Op->hasOneUse()) {
2913       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2914       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2915       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2916       if (C == AndRHS) {          // Masking out bits shifted in.
2917         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2918         // Make the argument unsigned.
2919         Value *ShVal = Op->getOperand(0);
2920         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2921                                     OpRHS, Op->getName()), TheAnd);
2922         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2923       }
2924     }
2925     break;
2926   }
2927   return 0;
2928 }
2929
2930
2931 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2932 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2933 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2934 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2935 /// insert new instructions.
2936 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2937                                            bool isSigned, bool Inside, 
2938                                            Instruction &IB) {
2939   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
2940             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2941          "Lo is not <= Hi in range emission code!");
2942     
2943   if (Inside) {
2944     if (Lo == Hi)  // Trivially false.
2945       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2946
2947     // V >= Min && V < Hi --> V < Hi
2948     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2949     ICmpInst::Predicate pred = (isSigned ? 
2950         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2951       return new ICmpInst(pred, V, Hi);
2952     }
2953
2954     // Emit V-Lo <u Hi-Lo
2955     Constant *NegLo = ConstantExpr::getNeg(Lo);
2956     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2957     InsertNewInstBefore(Add, IB);
2958     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2959     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2960   }
2961
2962   if (Lo == Hi)  // Trivially true.
2963     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2964
2965   // V < Min || V >= Hi ->'V > Hi-1'
2966   Hi = SubOne(cast<ConstantInt>(Hi));
2967   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2968     ICmpInst::Predicate pred = (isSigned ? 
2969         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2970     return new ICmpInst(pred, V, Hi);
2971   }
2972
2973   // Emit V-Lo > Hi-1-Lo
2974   Constant *NegLo = ConstantExpr::getNeg(Lo);
2975   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2976   InsertNewInstBefore(Add, IB);
2977   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2978   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
2979 }
2980
2981 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2982 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2983 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2984 // not, since all 1s are not contiguous.
2985 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
2986   uint64_t V = Val->getZExtValue();
2987   if (!isShiftedMask_64(V)) return false;
2988
2989   // look for the first zero bit after the run of ones
2990   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2991   // look for the first non-zero bit
2992   ME = 64-CountLeadingZeros_64(V);
2993   return true;
2994 }
2995
2996
2997
2998 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2999 /// where isSub determines whether the operator is a sub.  If we can fold one of
3000 /// the following xforms:
3001 /// 
3002 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3003 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3004 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3005 ///
3006 /// return (A +/- B).
3007 ///
3008 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3009                                         ConstantInt *Mask, bool isSub,
3010                                         Instruction &I) {
3011   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3012   if (!LHSI || LHSI->getNumOperands() != 2 ||
3013       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3014
3015   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3016
3017   switch (LHSI->getOpcode()) {
3018   default: return 0;
3019   case Instruction::And:
3020     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3021       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3022       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3023         break;
3024
3025       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3026       // part, we don't need any explicit masks to take them out of A.  If that
3027       // is all N is, ignore it.
3028       unsigned MB, ME;
3029       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3030         uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3031         Mask >>= 64-MB+1;
3032         if (MaskedValueIsZero(RHS, Mask))
3033           break;
3034       }
3035     }
3036     return 0;
3037   case Instruction::Or:
3038   case Instruction::Xor:
3039     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3040     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3041         ConstantExpr::getAnd(N, Mask)->isNullValue())
3042       break;
3043     return 0;
3044   }
3045   
3046   Instruction *New;
3047   if (isSub)
3048     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3049   else
3050     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3051   return InsertNewInstBefore(New, I);
3052 }
3053
3054 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3055   bool Changed = SimplifyCommutative(I);
3056   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3057
3058   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3059     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3060
3061   // and X, X = X
3062   if (Op0 == Op1)
3063     return ReplaceInstUsesWith(I, Op1);
3064
3065   // See if we can simplify any instructions used by the instruction whose sole 
3066   // purpose is to compute bits we don't care about.
3067   uint64_t KnownZero, KnownOne;
3068   if (!isa<PackedType>(I.getType())) {
3069     if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3070                              KnownZero, KnownOne))
3071     return &I;
3072   } else {
3073     if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Op1)) {
3074       if (CP->isAllOnesValue())
3075         return ReplaceInstUsesWith(I, I.getOperand(0));
3076     }
3077   }
3078   
3079   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3080     uint64_t AndRHSMask = AndRHS->getZExtValue();
3081     uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3082     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3083
3084     // Optimize a variety of ((val OP C1) & C2) combinations...
3085     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3086       Instruction *Op0I = cast<Instruction>(Op0);
3087       Value *Op0LHS = Op0I->getOperand(0);
3088       Value *Op0RHS = Op0I->getOperand(1);
3089       switch (Op0I->getOpcode()) {
3090       case Instruction::Xor:
3091       case Instruction::Or:
3092         // If the mask is only needed on one incoming arm, push it up.
3093         if (Op0I->hasOneUse()) {
3094           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3095             // Not masking anything out for the LHS, move to RHS.
3096             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3097                                                    Op0RHS->getName()+".masked");
3098             InsertNewInstBefore(NewRHS, I);
3099             return BinaryOperator::create(
3100                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3101           }
3102           if (!isa<Constant>(Op0RHS) &&
3103               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3104             // Not masking anything out for the RHS, move to LHS.
3105             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3106                                                    Op0LHS->getName()+".masked");
3107             InsertNewInstBefore(NewLHS, I);
3108             return BinaryOperator::create(
3109                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3110           }
3111         }
3112
3113         break;
3114       case Instruction::Add:
3115         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3116         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3117         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3118         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3119           return BinaryOperator::createAnd(V, AndRHS);
3120         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3121           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3122         break;
3123
3124       case Instruction::Sub:
3125         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3126         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3127         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3128         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3129           return BinaryOperator::createAnd(V, AndRHS);
3130         break;
3131       }
3132
3133       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3134         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3135           return Res;
3136     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3137       // If this is an integer truncation or change from signed-to-unsigned, and
3138       // if the source is an and/or with immediate, transform it.  This
3139       // frequently occurs for bitfield accesses.
3140       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3141         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3142             CastOp->getNumOperands() == 2)
3143           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3144             if (CastOp->getOpcode() == Instruction::And) {
3145               // Change: and (cast (and X, C1) to T), C2
3146               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3147               // This will fold the two constants together, which may allow 
3148               // other simplifications.
3149               Instruction *NewCast = CastInst::createTruncOrBitCast(
3150                 CastOp->getOperand(0), I.getType(), 
3151                 CastOp->getName()+".shrunk");
3152               NewCast = InsertNewInstBefore(NewCast, I);
3153               // trunc_or_bitcast(C1)&C2
3154               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3155               C3 = ConstantExpr::getAnd(C3, AndRHS);
3156               return BinaryOperator::createAnd(NewCast, C3);
3157             } else if (CastOp->getOpcode() == Instruction::Or) {
3158               // Change: and (cast (or X, C1) to T), C2
3159               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3160               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3161               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3162                 return ReplaceInstUsesWith(I, AndRHS);
3163             }
3164       }
3165     }
3166
3167     // Try to fold constant and into select arguments.
3168     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3169       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3170         return R;
3171     if (isa<PHINode>(Op0))
3172       if (Instruction *NV = FoldOpIntoPhi(I))
3173         return NV;
3174   }
3175
3176   Value *Op0NotVal = dyn_castNotVal(Op0);
3177   Value *Op1NotVal = dyn_castNotVal(Op1);
3178
3179   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3180     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3181
3182   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3183   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3184     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3185                                                I.getName()+".demorgan");
3186     InsertNewInstBefore(Or, I);
3187     return BinaryOperator::createNot(Or);
3188   }
3189   
3190   {
3191     Value *A = 0, *B = 0;
3192     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3193       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3194         return ReplaceInstUsesWith(I, Op1);
3195     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3196       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3197         return ReplaceInstUsesWith(I, Op0);
3198     
3199     if (Op0->hasOneUse() &&
3200         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3201       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3202         I.swapOperands();     // Simplify below
3203         std::swap(Op0, Op1);
3204       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3205         cast<BinaryOperator>(Op0)->swapOperands();
3206         I.swapOperands();     // Simplify below
3207         std::swap(Op0, Op1);
3208       }
3209     }
3210     if (Op1->hasOneUse() &&
3211         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3212       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3213         cast<BinaryOperator>(Op1)->swapOperands();
3214         std::swap(A, B);
3215       }
3216       if (A == Op0) {                                // A&(A^B) -> A & ~B
3217         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3218         InsertNewInstBefore(NotB, I);
3219         return BinaryOperator::createAnd(A, NotB);
3220       }
3221     }
3222   }
3223   
3224   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3225     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3226     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3227       return R;
3228
3229     Value *LHSVal, *RHSVal;
3230     ConstantInt *LHSCst, *RHSCst;
3231     ICmpInst::Predicate LHSCC, RHSCC;
3232     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3233       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3234         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3235             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3236             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3237             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3238             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3239             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3240           // Ensure that the larger constant is on the RHS.
3241           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3242             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3243           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3244           ICmpInst *LHS = cast<ICmpInst>(Op0);
3245           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3246             std::swap(LHS, RHS);
3247             std::swap(LHSCst, RHSCst);
3248             std::swap(LHSCC, RHSCC);
3249           }
3250
3251           // At this point, we know we have have two icmp instructions
3252           // comparing a value against two constants and and'ing the result
3253           // together.  Because of the above check, we know that we only have
3254           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3255           // (from the FoldICmpLogical check above), that the two constants 
3256           // are not equal and that the larger constant is on the RHS
3257           assert(LHSCst != RHSCst && "Compares not folded above?");
3258
3259           switch (LHSCC) {
3260           default: assert(0 && "Unknown integer condition code!");
3261           case ICmpInst::ICMP_EQ:
3262             switch (RHSCC) {
3263             default: assert(0 && "Unknown integer condition code!");
3264             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3265             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3266             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3267               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3268             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3269             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3270             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3271               return ReplaceInstUsesWith(I, LHS);
3272             }
3273           case ICmpInst::ICMP_NE:
3274             switch (RHSCC) {
3275             default: assert(0 && "Unknown integer condition code!");
3276             case ICmpInst::ICMP_ULT:
3277               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3278                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3279               break;                        // (X != 13 & X u< 15) -> no change
3280             case ICmpInst::ICMP_SLT:
3281               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3282                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3283               break;                        // (X != 13 & X s< 15) -> no change
3284             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3285             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3286             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3287               return ReplaceInstUsesWith(I, RHS);
3288             case ICmpInst::ICMP_NE:
3289               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3290                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3291                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3292                                                       LHSVal->getName()+".off");
3293                 InsertNewInstBefore(Add, I);
3294                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3295                                     ConstantInt::get(Add->getType(), 1));
3296               }
3297               break;                        // (X != 13 & X != 15) -> no change
3298             }
3299             break;
3300           case ICmpInst::ICMP_ULT:
3301             switch (RHSCC) {
3302             default: assert(0 && "Unknown integer condition code!");
3303             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3304             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3305               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3306             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3307               break;
3308             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3309             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3310               return ReplaceInstUsesWith(I, LHS);
3311             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3312               break;
3313             }
3314             break;
3315           case ICmpInst::ICMP_SLT:
3316             switch (RHSCC) {
3317             default: assert(0 && "Unknown integer condition code!");
3318             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3319             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3320               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3321             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3322               break;
3323             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3324             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3325               return ReplaceInstUsesWith(I, LHS);
3326             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3327               break;
3328             }
3329             break;
3330           case ICmpInst::ICMP_UGT:
3331             switch (RHSCC) {
3332             default: assert(0 && "Unknown integer condition code!");
3333             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3334               return ReplaceInstUsesWith(I, LHS);
3335             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3336               return ReplaceInstUsesWith(I, RHS);
3337             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3338               break;
3339             case ICmpInst::ICMP_NE:
3340               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3341                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3342               break;                        // (X u> 13 & X != 15) -> no change
3343             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3344               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3345                                      true, I);
3346             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3347               break;
3348             }
3349             break;
3350           case ICmpInst::ICMP_SGT:
3351             switch (RHSCC) {
3352             default: assert(0 && "Unknown integer condition code!");
3353             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3354               return ReplaceInstUsesWith(I, LHS);
3355             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3356               return ReplaceInstUsesWith(I, RHS);
3357             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3358               break;
3359             case ICmpInst::ICMP_NE:
3360               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3361                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3362               break;                        // (X s> 13 & X != 15) -> no change
3363             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3364               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3365                                      true, I);
3366             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3367               break;
3368             }
3369             break;
3370           }
3371         }
3372   }
3373
3374   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3375   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3376     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3377       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3378         const Type *SrcTy = Op0C->getOperand(0)->getType();
3379         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3380             // Only do this if the casts both really cause code to be generated.
3381             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3382                               I.getType(), TD) &&
3383             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3384                               I.getType(), TD)) {
3385           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3386                                                          Op1C->getOperand(0),
3387                                                          I.getName());
3388           InsertNewInstBefore(NewOp, I);
3389           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3390         }
3391       }
3392     
3393   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3394   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3395     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3396       if (SI0->getOpcode() == SI1->getOpcode() && 
3397           SI0->getOperand(1) == SI1->getOperand(1) &&
3398           (SI0->hasOneUse() || SI1->hasOneUse())) {
3399         Instruction *NewOp =
3400           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3401                                                         SI1->getOperand(0),
3402                                                         SI0->getName()), I);
3403         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3404       }
3405   }
3406
3407   return Changed ? &I : 0;
3408 }
3409
3410 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3411 /// in the result.  If it does, and if the specified byte hasn't been filled in
3412 /// yet, fill it in and return false.
3413 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3414   Instruction *I = dyn_cast<Instruction>(V);
3415   if (I == 0) return true;
3416
3417   // If this is an or instruction, it is an inner node of the bswap.
3418   if (I->getOpcode() == Instruction::Or)
3419     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3420            CollectBSwapParts(I->getOperand(1), ByteValues);
3421   
3422   // If this is a shift by a constant int, and it is "24", then its operand
3423   // defines a byte.  We only handle unsigned types here.
3424   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3425     // Not shifting the entire input by N-1 bytes?
3426     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3427         8*(ByteValues.size()-1))
3428       return true;
3429     
3430     unsigned DestNo;
3431     if (I->getOpcode() == Instruction::Shl) {
3432       // X << 24 defines the top byte with the lowest of the input bytes.
3433       DestNo = ByteValues.size()-1;
3434     } else {
3435       // X >>u 24 defines the low byte with the highest of the input bytes.
3436       DestNo = 0;
3437     }
3438     
3439     // If the destination byte value is already defined, the values are or'd
3440     // together, which isn't a bswap (unless it's an or of the same bits).
3441     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3442       return true;
3443     ByteValues[DestNo] = I->getOperand(0);
3444     return false;
3445   }
3446   
3447   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3448   // don't have this.
3449   Value *Shift = 0, *ShiftLHS = 0;
3450   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3451   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3452       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3453     return true;
3454   Instruction *SI = cast<Instruction>(Shift);
3455
3456   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3457   if (ShiftAmt->getZExtValue() & 7 ||
3458       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3459     return true;
3460   
3461   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3462   unsigned DestByte;
3463   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3464     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3465       break;
3466   // Unknown mask for bswap.
3467   if (DestByte == ByteValues.size()) return true;
3468   
3469   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3470   unsigned SrcByte;
3471   if (SI->getOpcode() == Instruction::Shl)
3472     SrcByte = DestByte - ShiftBytes;
3473   else
3474     SrcByte = DestByte + ShiftBytes;
3475   
3476   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3477   if (SrcByte != ByteValues.size()-DestByte-1)
3478     return true;
3479   
3480   // If the destination byte value is already defined, the values are or'd
3481   // together, which isn't a bswap (unless it's an or of the same bits).
3482   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3483     return true;
3484   ByteValues[DestByte] = SI->getOperand(0);
3485   return false;
3486 }
3487
3488 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3489 /// If so, insert the new bswap intrinsic and return it.
3490 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3491   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3492   if (I.getType() == Type::Int8Ty)
3493     return 0;
3494   
3495   /// ByteValues - For each byte of the result, we keep track of which value
3496   /// defines each byte.
3497   std::vector<Value*> ByteValues;
3498   ByteValues.resize(TD->getTypeSize(I.getType()));
3499     
3500   // Try to find all the pieces corresponding to the bswap.
3501   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3502       CollectBSwapParts(I.getOperand(1), ByteValues))
3503     return 0;
3504   
3505   // Check to see if all of the bytes come from the same value.
3506   Value *V = ByteValues[0];
3507   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3508   
3509   // Check to make sure that all of the bytes come from the same value.
3510   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3511     if (ByteValues[i] != V)
3512       return 0;
3513     
3514   // If they do then *success* we can turn this into a bswap.  Figure out what
3515   // bswap to make it into.
3516   Module *M = I.getParent()->getParent()->getParent();
3517   const char *FnName = 0;
3518   if (I.getType() == Type::Int16Ty)
3519     FnName = "llvm.bswap.i16";
3520   else if (I.getType() == Type::Int32Ty)
3521     FnName = "llvm.bswap.i32";
3522   else if (I.getType() == Type::Int64Ty)
3523     FnName = "llvm.bswap.i64";
3524   else
3525     assert(0 && "Unknown integer type!");
3526   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3527   return new CallInst(F, V);
3528 }
3529
3530
3531 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3532   bool Changed = SimplifyCommutative(I);
3533   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3534
3535   if (isa<UndefValue>(Op1))
3536     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3537                                ConstantInt::getAllOnesValue(I.getType()));
3538
3539   // or X, X = X
3540   if (Op0 == Op1)
3541     return ReplaceInstUsesWith(I, Op0);
3542
3543   // See if we can simplify any instructions used by the instruction whose sole 
3544   // purpose is to compute bits we don't care about.
3545   uint64_t KnownZero, KnownOne;
3546   if (!isa<PackedType>(I.getType()) &&
3547       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3548                            KnownZero, KnownOne))
3549     return &I;
3550   
3551   // or X, -1 == -1
3552   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3553     ConstantInt *C1 = 0; Value *X = 0;
3554     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3555     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3556       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3557       Op0->setName("");
3558       InsertNewInstBefore(Or, I);
3559       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3560     }
3561
3562     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3563     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3564       std::string Op0Name = Op0->getName(); Op0->setName("");
3565       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3566       InsertNewInstBefore(Or, I);
3567       return BinaryOperator::createXor(Or,
3568                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3569     }
3570
3571     // Try to fold constant and into select arguments.
3572     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3573       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3574         return R;
3575     if (isa<PHINode>(Op0))
3576       if (Instruction *NV = FoldOpIntoPhi(I))
3577         return NV;
3578   }
3579
3580   Value *A = 0, *B = 0;
3581   ConstantInt *C1 = 0, *C2 = 0;
3582
3583   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3584     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3585       return ReplaceInstUsesWith(I, Op1);
3586   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3587     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3588       return ReplaceInstUsesWith(I, Op0);
3589
3590   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3591   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3592   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3593       match(Op1, m_Or(m_Value(), m_Value())) ||
3594       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3595        match(Op1, m_Shift(m_Value(), m_Value())))) {
3596     if (Instruction *BSwap = MatchBSwap(I))
3597       return BSwap;
3598   }
3599   
3600   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3601   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3602       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3603     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3604     Op0->setName("");
3605     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3606   }
3607
3608   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3609   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3610       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3611     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3612     Op0->setName("");
3613     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3614   }
3615
3616   // (A & C1)|(B & C2)
3617   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3618       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3619
3620     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3621       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3622
3623
3624     // If we have: ((V + N) & C1) | (V & C2)
3625     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3626     // replace with V+N.
3627     if (C1 == ConstantExpr::getNot(C2)) {
3628       Value *V1 = 0, *V2 = 0;
3629       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3630           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3631         // Add commutes, try both ways.
3632         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3633           return ReplaceInstUsesWith(I, A);
3634         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3635           return ReplaceInstUsesWith(I, A);
3636       }
3637       // Or commutes, try both ways.
3638       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3639           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3640         // Add commutes, try both ways.
3641         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3642           return ReplaceInstUsesWith(I, B);
3643         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3644           return ReplaceInstUsesWith(I, B);
3645       }
3646     }
3647   }
3648   
3649   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3650   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3651     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3652       if (SI0->getOpcode() == SI1->getOpcode() && 
3653           SI0->getOperand(1) == SI1->getOperand(1) &&
3654           (SI0->hasOneUse() || SI1->hasOneUse())) {
3655         Instruction *NewOp =
3656         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3657                                                      SI1->getOperand(0),
3658                                                      SI0->getName()), I);
3659         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3660       }
3661   }
3662
3663   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3664     if (A == Op1)   // ~A | A == -1
3665       return ReplaceInstUsesWith(I,
3666                                 ConstantInt::getAllOnesValue(I.getType()));
3667   } else {
3668     A = 0;
3669   }
3670   // Note, A is still live here!
3671   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3672     if (Op0 == B)
3673       return ReplaceInstUsesWith(I,
3674                                 ConstantInt::getAllOnesValue(I.getType()));
3675
3676     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3677     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3678       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3679                                               I.getName()+".demorgan"), I);
3680       return BinaryOperator::createNot(And);
3681     }
3682   }
3683
3684   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3685   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3686     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3687       return R;
3688
3689     Value *LHSVal, *RHSVal;
3690     ConstantInt *LHSCst, *RHSCst;
3691     ICmpInst::Predicate LHSCC, RHSCC;
3692     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3693       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3694         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3695             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3696             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3697             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3698             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3699             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3700           // Ensure that the larger constant is on the RHS.
3701           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3702             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3703           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3704           ICmpInst *LHS = cast<ICmpInst>(Op0);
3705           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3706             std::swap(LHS, RHS);
3707             std::swap(LHSCst, RHSCst);
3708             std::swap(LHSCC, RHSCC);
3709           }
3710
3711           // At this point, we know we have have two icmp instructions
3712           // comparing a value against two constants and or'ing the result
3713           // together.  Because of the above check, we know that we only have
3714           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3715           // FoldICmpLogical check above), that the two constants are not
3716           // equal.
3717           assert(LHSCst != RHSCst && "Compares not folded above?");
3718
3719           switch (LHSCC) {
3720           default: assert(0 && "Unknown integer condition code!");
3721           case ICmpInst::ICMP_EQ:
3722             switch (RHSCC) {
3723             default: assert(0 && "Unknown integer condition code!");
3724             case ICmpInst::ICMP_EQ:
3725               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3726                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3727                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3728                                                       LHSVal->getName()+".off");
3729                 InsertNewInstBefore(Add, I);
3730                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3731                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3732               }
3733               break;                         // (X == 13 | X == 15) -> no change
3734             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3735             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3736               break;
3737             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3738             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3739             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3740               return ReplaceInstUsesWith(I, RHS);
3741             }
3742             break;
3743           case ICmpInst::ICMP_NE:
3744             switch (RHSCC) {
3745             default: assert(0 && "Unknown integer condition code!");
3746             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3747             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3748             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3749               return ReplaceInstUsesWith(I, LHS);
3750             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3751             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3752             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3753               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3754             }
3755             break;
3756           case ICmpInst::ICMP_ULT:
3757             switch (RHSCC) {
3758             default: assert(0 && "Unknown integer condition code!");
3759             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3760               break;
3761             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3762               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3763                                      false, I);
3764             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3765               break;
3766             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3767             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3768               return ReplaceInstUsesWith(I, RHS);
3769             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3770               break;
3771             }
3772             break;
3773           case ICmpInst::ICMP_SLT:
3774             switch (RHSCC) {
3775             default: assert(0 && "Unknown integer condition code!");
3776             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3777               break;
3778             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3779               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3780                                      false, I);
3781             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3782               break;
3783             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3784             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3785               return ReplaceInstUsesWith(I, RHS);
3786             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3787               break;
3788             }
3789             break;
3790           case ICmpInst::ICMP_UGT:
3791             switch (RHSCC) {
3792             default: assert(0 && "Unknown integer condition code!");
3793             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3794             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3795               return ReplaceInstUsesWith(I, LHS);
3796             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3797               break;
3798             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3799             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3800               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3801             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3802               break;
3803             }
3804             break;
3805           case ICmpInst::ICMP_SGT:
3806             switch (RHSCC) {
3807             default: assert(0 && "Unknown integer condition code!");
3808             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3809             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3810               return ReplaceInstUsesWith(I, LHS);
3811             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3812               break;
3813             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3814             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3815               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3816             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3817               break;
3818             }
3819             break;
3820           }
3821         }
3822   }
3823     
3824   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3825   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3826     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3827       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3828         const Type *SrcTy = Op0C->getOperand(0)->getType();
3829         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3830             // Only do this if the casts both really cause code to be generated.
3831             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3832                               I.getType(), TD) &&
3833             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3834                               I.getType(), TD)) {
3835           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3836                                                         Op1C->getOperand(0),
3837                                                         I.getName());
3838           InsertNewInstBefore(NewOp, I);
3839           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3840         }
3841       }
3842       
3843
3844   return Changed ? &I : 0;
3845 }
3846
3847 // XorSelf - Implements: X ^ X --> 0
3848 struct XorSelf {
3849   Value *RHS;
3850   XorSelf(Value *rhs) : RHS(rhs) {}
3851   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3852   Instruction *apply(BinaryOperator &Xor) const {
3853     return &Xor;
3854   }
3855 };
3856
3857
3858 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3859   bool Changed = SimplifyCommutative(I);
3860   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3861
3862   if (isa<UndefValue>(Op1))
3863     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3864
3865   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3866   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3867     assert(Result == &I && "AssociativeOpt didn't work?");
3868     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3869   }
3870   
3871   // See if we can simplify any instructions used by the instruction whose sole 
3872   // purpose is to compute bits we don't care about.
3873   uint64_t KnownZero, KnownOne;
3874   if (!isa<PackedType>(I.getType()) &&
3875       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3876                            KnownZero, KnownOne))
3877     return &I;
3878
3879   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3880     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3881     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3882       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3883         return new ICmpInst(ICI->getInversePredicate(),
3884                             ICI->getOperand(0), ICI->getOperand(1));
3885
3886     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3887       // ~(c-X) == X-c-1 == X+(-c-1)
3888       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3889         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3890           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3891           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3892                                               ConstantInt::get(I.getType(), 1));
3893           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3894         }
3895
3896       // ~(~X & Y) --> (X | ~Y)
3897       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3898         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3899         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3900           Instruction *NotY =
3901             BinaryOperator::createNot(Op0I->getOperand(1),
3902                                       Op0I->getOperand(1)->getName()+".not");
3903           InsertNewInstBefore(NotY, I);
3904           return BinaryOperator::createOr(Op0NotVal, NotY);
3905         }
3906       }
3907
3908       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3909         if (Op0I->getOpcode() == Instruction::Add) {
3910           // ~(X-c) --> (-c-1)-X
3911           if (RHS->isAllOnesValue()) {
3912             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3913             return BinaryOperator::createSub(
3914                            ConstantExpr::getSub(NegOp0CI,
3915                                              ConstantInt::get(I.getType(), 1)),
3916                                           Op0I->getOperand(0));
3917           }
3918         } else if (Op0I->getOpcode() == Instruction::Or) {
3919           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3920           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3921             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3922             // Anything in both C1 and C2 is known to be zero, remove it from
3923             // NewRHS.
3924             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3925             NewRHS = ConstantExpr::getAnd(NewRHS, 
3926                                           ConstantExpr::getNot(CommonBits));
3927             WorkList.push_back(Op0I);
3928             I.setOperand(0, Op0I->getOperand(0));
3929             I.setOperand(1, NewRHS);
3930             return &I;
3931           }
3932         }
3933     }
3934
3935     // Try to fold constant and into select arguments.
3936     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3937       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3938         return R;
3939     if (isa<PHINode>(Op0))
3940       if (Instruction *NV = FoldOpIntoPhi(I))
3941         return NV;
3942   }
3943
3944   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3945     if (X == Op1)
3946       return ReplaceInstUsesWith(I,
3947                                 ConstantInt::getAllOnesValue(I.getType()));
3948
3949   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3950     if (X == Op0)
3951       return ReplaceInstUsesWith(I,
3952                                 ConstantInt::getAllOnesValue(I.getType()));
3953
3954   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3955     if (Op1I->getOpcode() == Instruction::Or) {
3956       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3957         Op1I->swapOperands();
3958         I.swapOperands();
3959         std::swap(Op0, Op1);
3960       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3961         I.swapOperands();     // Simplified below.
3962         std::swap(Op0, Op1);
3963       }
3964     } else if (Op1I->getOpcode() == Instruction::Xor) {
3965       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3966         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3967       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3968         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3969     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3970       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3971         Op1I->swapOperands();
3972       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3973         I.swapOperands();     // Simplified below.
3974         std::swap(Op0, Op1);
3975       }
3976     }
3977
3978   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3979     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3980       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3981         Op0I->swapOperands();
3982       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3983         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3984         InsertNewInstBefore(NotB, I);
3985         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3986       }
3987     } else if (Op0I->getOpcode() == Instruction::Xor) {
3988       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3989         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3990       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3991         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3992     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3993       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3994         Op0I->swapOperands();
3995       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
3996           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
3997         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3998         InsertNewInstBefore(N, I);
3999         return BinaryOperator::createAnd(N, Op1);
4000       }
4001     }
4002
4003   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4004   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4005     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4006       return R;
4007
4008   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4009   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4010     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4011       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4012         const Type *SrcTy = Op0C->getOperand(0)->getType();
4013         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4014             // Only do this if the casts both really cause code to be generated.
4015             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4016                               I.getType(), TD) &&
4017             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4018                               I.getType(), TD)) {
4019           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4020                                                          Op1C->getOperand(0),
4021                                                          I.getName());
4022           InsertNewInstBefore(NewOp, I);
4023           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4024         }
4025       }
4026
4027   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4028   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4029     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4030       if (SI0->getOpcode() == SI1->getOpcode() && 
4031           SI0->getOperand(1) == SI1->getOperand(1) &&
4032           (SI0->hasOneUse() || SI1->hasOneUse())) {
4033         Instruction *NewOp =
4034         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4035                                                       SI1->getOperand(0),
4036                                                       SI0->getName()), I);
4037         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4038       }
4039   }
4040     
4041   return Changed ? &I : 0;
4042 }
4043
4044 static bool isPositive(ConstantInt *C) {
4045   return C->getSExtValue() >= 0;
4046 }
4047
4048 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4049 /// overflowed for this type.
4050 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4051                             ConstantInt *In2) {
4052   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4053
4054   return cast<ConstantInt>(Result)->getZExtValue() <
4055          cast<ConstantInt>(In1)->getZExtValue();
4056 }
4057
4058 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4059 /// code necessary to compute the offset from the base pointer (without adding
4060 /// in the base pointer).  Return the result as a signed integer of intptr size.
4061 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4062   TargetData &TD = IC.getTargetData();
4063   gep_type_iterator GTI = gep_type_begin(GEP);
4064   const Type *IntPtrTy = TD.getIntPtrType();
4065   Value *Result = Constant::getNullValue(IntPtrTy);
4066
4067   // Build a mask for high order bits.
4068   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4069
4070   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4071     Value *Op = GEP->getOperand(i);
4072     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4073     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4074     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4075       if (!OpC->isNullValue()) {
4076         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4077         Scale = ConstantExpr::getMul(OpC, Scale);
4078         if (Constant *RC = dyn_cast<Constant>(Result))
4079           Result = ConstantExpr::getAdd(RC, Scale);
4080         else {
4081           // Emit an add instruction.
4082           Result = IC.InsertNewInstBefore(
4083              BinaryOperator::createAdd(Result, Scale,
4084                                        GEP->getName()+".offs"), I);
4085         }
4086       }
4087     } else {
4088       // Convert to correct type.
4089       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4090                                                Op->getName()+".c"), I);
4091       if (Size != 1)
4092         // We'll let instcombine(mul) convert this to a shl if possible.
4093         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4094                                                     GEP->getName()+".idx"), I);
4095
4096       // Emit an add instruction.
4097       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4098                                                     GEP->getName()+".offs"), I);
4099     }
4100   }
4101   return Result;
4102 }
4103
4104 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4105 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4106 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4107                                        ICmpInst::Predicate Cond,
4108                                        Instruction &I) {
4109   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4110
4111   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4112     if (isa<PointerType>(CI->getOperand(0)->getType()))
4113       RHS = CI->getOperand(0);
4114
4115   Value *PtrBase = GEPLHS->getOperand(0);
4116   if (PtrBase == RHS) {
4117     // As an optimization, we don't actually have to compute the actual value of
4118     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4119     // each index is zero or not.
4120     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4121       Instruction *InVal = 0;
4122       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4123       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4124         bool EmitIt = true;
4125         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4126           if (isa<UndefValue>(C))  // undef index -> undef.
4127             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4128           if (C->isNullValue())
4129             EmitIt = false;
4130           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4131             EmitIt = false;  // This is indexing into a zero sized array?
4132           } else if (isa<ConstantInt>(C))
4133             return ReplaceInstUsesWith(I, // No comparison is needed here.
4134                                  ConstantInt::get(Type::Int1Ty, 
4135                                                   Cond == ICmpInst::ICMP_NE));
4136         }
4137
4138         if (EmitIt) {
4139           Instruction *Comp =
4140             new ICmpInst(Cond, GEPLHS->getOperand(i),
4141                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4142           if (InVal == 0)
4143             InVal = Comp;
4144           else {
4145             InVal = InsertNewInstBefore(InVal, I);
4146             InsertNewInstBefore(Comp, I);
4147             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4148               InVal = BinaryOperator::createOr(InVal, Comp);
4149             else                              // True if all are equal
4150               InVal = BinaryOperator::createAnd(InVal, Comp);
4151           }
4152         }
4153       }
4154
4155       if (InVal)
4156         return InVal;
4157       else
4158         // No comparison is needed here, all indexes = 0
4159         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4160                                                 Cond == ICmpInst::ICMP_EQ));
4161     }
4162
4163     // Only lower this if the icmp is the only user of the GEP or if we expect
4164     // the result to fold to a constant!
4165     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4166       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4167       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4168       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4169                           Constant::getNullValue(Offset->getType()));
4170     }
4171   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4172     // If the base pointers are different, but the indices are the same, just
4173     // compare the base pointer.
4174     if (PtrBase != GEPRHS->getOperand(0)) {
4175       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4176       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4177                         GEPRHS->getOperand(0)->getType();
4178       if (IndicesTheSame)
4179         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4180           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4181             IndicesTheSame = false;
4182             break;
4183           }
4184
4185       // If all indices are the same, just compare the base pointers.
4186       if (IndicesTheSame)
4187         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4188                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4189
4190       // Otherwise, the base pointers are different and the indices are
4191       // different, bail out.
4192       return 0;
4193     }
4194
4195     // If one of the GEPs has all zero indices, recurse.
4196     bool AllZeros = true;
4197     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4198       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4199           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4200         AllZeros = false;
4201         break;
4202       }
4203     if (AllZeros)
4204       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4205                           ICmpInst::getSwappedPredicate(Cond), I);
4206
4207     // If the other GEP has all zero indices, recurse.
4208     AllZeros = true;
4209     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4210       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4211           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4212         AllZeros = false;
4213         break;
4214       }
4215     if (AllZeros)
4216       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4217
4218     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4219       // If the GEPs only differ by one index, compare it.
4220       unsigned NumDifferences = 0;  // Keep track of # differences.
4221       unsigned DiffOperand = 0;     // The operand that differs.
4222       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4223         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4224           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4225                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4226             // Irreconcilable differences.
4227             NumDifferences = 2;
4228             break;
4229           } else {
4230             if (NumDifferences++) break;
4231             DiffOperand = i;
4232           }
4233         }
4234
4235       if (NumDifferences == 0)   // SAME GEP?
4236         return ReplaceInstUsesWith(I, // No comparison is needed here.
4237                                    ConstantInt::get(Type::Int1Ty, 
4238                                                     Cond == ICmpInst::ICMP_EQ));
4239       else if (NumDifferences == 1) {
4240         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4241         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4242         // Make sure we do a signed comparison here.
4243         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4244       }
4245     }
4246
4247     // Only lower this if the icmp is the only user of the GEP or if we expect
4248     // the result to fold to a constant!
4249     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4250         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4251       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4252       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4253       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4254       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4255     }
4256   }
4257   return 0;
4258 }
4259
4260 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4261   bool Changed = SimplifyCompare(I);
4262   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4263
4264   // Fold trivial predicates.
4265   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4266     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4267   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4268     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4269   
4270   // Simplify 'fcmp pred X, X'
4271   if (Op0 == Op1) {
4272     switch (I.getPredicate()) {
4273     default: assert(0 && "Unknown predicate!");
4274     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4275     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4276     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4277       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4278     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4279     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4280     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4281       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4282       
4283     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4284     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4285     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4286     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4287       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4288       I.setPredicate(FCmpInst::FCMP_UNO);
4289       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4290       return &I;
4291       
4292     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4293     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4294     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4295     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4296       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4297       I.setPredicate(FCmpInst::FCMP_ORD);
4298       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4299       return &I;
4300     }
4301   }
4302     
4303   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4304     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4305
4306   // Handle fcmp with constant RHS
4307   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4308     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4309       switch (LHSI->getOpcode()) {
4310       case Instruction::PHI:
4311         if (Instruction *NV = FoldOpIntoPhi(I))
4312           return NV;
4313         break;
4314       case Instruction::Select:
4315         // If either operand of the select is a constant, we can fold the
4316         // comparison into the select arms, which will cause one to be
4317         // constant folded and the select turned into a bitwise or.
4318         Value *Op1 = 0, *Op2 = 0;
4319         if (LHSI->hasOneUse()) {
4320           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4321             // Fold the known value into the constant operand.
4322             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4323             // Insert a new FCmp of the other select operand.
4324             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4325                                                       LHSI->getOperand(2), RHSC,
4326                                                       I.getName()), I);
4327           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4328             // Fold the known value into the constant operand.
4329             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4330             // Insert a new FCmp of the other select operand.
4331             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4332                                                       LHSI->getOperand(1), RHSC,
4333                                                       I.getName()), I);
4334           }
4335         }
4336
4337         if (Op1)
4338           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4339         break;
4340       }
4341   }
4342
4343   return Changed ? &I : 0;
4344 }
4345
4346 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4347   bool Changed = SimplifyCompare(I);
4348   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4349   const Type *Ty = Op0->getType();
4350
4351   // icmp X, X
4352   if (Op0 == Op1)
4353     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4354                                                    isTrueWhenEqual(I)));
4355
4356   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4357     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4358
4359   // icmp of GlobalValues can never equal each other as long as they aren't
4360   // external weak linkage type.
4361   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4362     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4363       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4364         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4365                                                        !isTrueWhenEqual(I)));
4366
4367   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4368   // addresses never equal each other!  We already know that Op0 != Op1.
4369   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4370        isa<ConstantPointerNull>(Op0)) &&
4371       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4372        isa<ConstantPointerNull>(Op1)))
4373     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4374                                                    !isTrueWhenEqual(I)));
4375
4376   // icmp's with boolean values can always be turned into bitwise operations
4377   if (Ty == Type::Int1Ty) {
4378     switch (I.getPredicate()) {
4379     default: assert(0 && "Invalid icmp instruction!");
4380     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4381       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4382       InsertNewInstBefore(Xor, I);
4383       return BinaryOperator::createNot(Xor);
4384     }
4385     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4386       return BinaryOperator::createXor(Op0, Op1);
4387
4388     case ICmpInst::ICMP_UGT:
4389     case ICmpInst::ICMP_SGT:
4390       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4391       // FALL THROUGH
4392     case ICmpInst::ICMP_ULT:
4393     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4394       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4395       InsertNewInstBefore(Not, I);
4396       return BinaryOperator::createAnd(Not, Op1);
4397     }
4398     case ICmpInst::ICMP_UGE:
4399     case ICmpInst::ICMP_SGE:
4400       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4401       // FALL THROUGH
4402     case ICmpInst::ICMP_ULE:
4403     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4404       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4405       InsertNewInstBefore(Not, I);
4406       return BinaryOperator::createOr(Not, Op1);
4407     }
4408     }
4409   }
4410
4411   // See if we are doing a comparison between a constant and an instruction that
4412   // can be folded into the comparison.
4413   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4414     switch (I.getPredicate()) {
4415     default: break;
4416     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4417       if (CI->isMinValue(false))
4418         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4419       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4420         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4421       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4422         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4423       break;
4424
4425     case ICmpInst::ICMP_SLT:
4426       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4427         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4428       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4429         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4430       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4431         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4432       break;
4433
4434     case ICmpInst::ICMP_UGT:
4435       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4436         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4437       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4438         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4439       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4440         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4441       break;
4442
4443     case ICmpInst::ICMP_SGT:
4444       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4445         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4446       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4447         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4448       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4449         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4450       break;
4451
4452     case ICmpInst::ICMP_ULE:
4453       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4454         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4455       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4456         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4457       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4458         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4459       break;
4460
4461     case ICmpInst::ICMP_SLE:
4462       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4463         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4464       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4465         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4466       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4467         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4468       break;
4469
4470     case ICmpInst::ICMP_UGE:
4471       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4472         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4473       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4474         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4475       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4476         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4477       break;
4478
4479     case ICmpInst::ICMP_SGE:
4480       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4481         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4482       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4483         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4484       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4485         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4486       break;
4487     }
4488
4489     // If we still have a icmp le or icmp ge instruction, turn it into the
4490     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4491     // already been handled above, this requires little checking.
4492     //
4493     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4494       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4495     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4496       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4497     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4498       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4499     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4500       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4501     
4502     // See if we can fold the comparison based on bits known to be zero or one
4503     // in the input.
4504     uint64_t KnownZero, KnownOne;
4505     if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
4506                              KnownZero, KnownOne, 0))
4507       return &I;
4508         
4509     // Given the known and unknown bits, compute a range that the LHS could be
4510     // in.
4511     if (KnownOne | KnownZero) {
4512       // Compute the Min, Max and RHS values based on the known bits. For the
4513       // EQ and NE we use unsigned values.
4514       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4515       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4516       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4517         SRHSVal = CI->getSExtValue();
4518         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4519                                                SMax);
4520       } else {
4521         URHSVal = CI->getZExtValue();
4522         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4523                                                  UMax);
4524       }
4525       switch (I.getPredicate()) {  // LE/GE have been folded already.
4526       default: assert(0 && "Unknown icmp opcode!");
4527       case ICmpInst::ICMP_EQ:
4528         if (UMax < URHSVal || UMin > URHSVal)
4529           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4530         break;
4531       case ICmpInst::ICMP_NE:
4532         if (UMax < URHSVal || UMin > URHSVal)
4533           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4534         break;
4535       case ICmpInst::ICMP_ULT:
4536         if (UMax < URHSVal)
4537           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4538         if (UMin > URHSVal)
4539           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4540         break;
4541       case ICmpInst::ICMP_UGT:
4542         if (UMin > URHSVal)
4543           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4544         if (UMax < URHSVal)
4545           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4546         break;
4547       case ICmpInst::ICMP_SLT:
4548         if (SMax < SRHSVal)
4549           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4550         if (SMin > SRHSVal)
4551           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4552         break;
4553       case ICmpInst::ICMP_SGT: 
4554         if (SMin > SRHSVal)
4555           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4556         if (SMax < SRHSVal)
4557           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4558         break;
4559       }
4560     }
4561           
4562     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4563     // instruction, see if that instruction also has constants so that the 
4564     // instruction can be folded into the icmp 
4565     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4566       switch (LHSI->getOpcode()) {
4567       case Instruction::And:
4568         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4569             LHSI->getOperand(0)->hasOneUse()) {
4570           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4571
4572           // If the LHS is an AND of a truncating cast, we can widen the
4573           // and/compare to be the input width without changing the value
4574           // produced, eliminating a cast.
4575           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4576             // We can do this transformation if either the AND constant does not
4577             // have its sign bit set or if it is an equality comparison. 
4578             // Extending a relational comparison when we're checking the sign
4579             // bit would not work.
4580             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4581                 (I.isEquality() ||
4582                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4583                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4584               ConstantInt *NewCST;
4585               ConstantInt *NewCI;
4586               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4587                                          AndCST->getZExtValue());
4588               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4589                                         CI->getZExtValue());
4590               Instruction *NewAnd = 
4591                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4592                                           LHSI->getName());
4593               InsertNewInstBefore(NewAnd, I);
4594               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4595             }
4596           }
4597           
4598           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4599           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4600           // happens a LOT in code produced by the C front-end, for bitfield
4601           // access.
4602           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4603
4604           // Check to see if there is a noop-cast between the shift and the and.
4605           if (!Shift) {
4606             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4607               if (CI->getOpcode() == Instruction::BitCast)
4608                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4609           }
4610
4611           ConstantInt *ShAmt;
4612           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4613           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4614           const Type *AndTy = AndCST->getType();          // Type of the and.
4615
4616           // We can fold this as long as we can't shift unknown bits
4617           // into the mask.  This can only happen with signed shift
4618           // rights, as they sign-extend.
4619           if (ShAmt) {
4620             bool CanFold = Shift->isLogicalShift();
4621             if (!CanFold) {
4622               // To test for the bad case of the signed shr, see if any
4623               // of the bits shifted in could be tested after the mask.
4624               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4625               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4626
4627               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4628               Constant *ShVal =
4629                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4630                                      OShAmt);
4631               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4632                 CanFold = true;
4633             }
4634
4635             if (CanFold) {
4636               Constant *NewCst;
4637               if (Shift->getOpcode() == Instruction::Shl)
4638                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4639               else
4640                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4641
4642               // Check to see if we are shifting out any of the bits being
4643               // compared.
4644               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4645                 // If we shifted bits out, the fold is not going to work out.
4646                 // As a special case, check to see if this means that the
4647                 // result is always true or false now.
4648                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4649                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4650                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4651                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4652               } else {
4653                 I.setOperand(1, NewCst);
4654                 Constant *NewAndCST;
4655                 if (Shift->getOpcode() == Instruction::Shl)
4656                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4657                 else
4658                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4659                 LHSI->setOperand(1, NewAndCST);
4660                 LHSI->setOperand(0, Shift->getOperand(0));
4661                 WorkList.push_back(Shift); // Shift is dead.
4662                 AddUsesToWorkList(I);
4663                 return &I;
4664               }
4665             }
4666           }
4667           
4668           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4669           // preferable because it allows the C<<Y expression to be hoisted out
4670           // of a loop if Y is invariant and X is not.
4671           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4672               I.isEquality() && !Shift->isArithmeticShift() &&
4673               isa<Instruction>(Shift->getOperand(0))) {
4674             // Compute C << Y.
4675             Value *NS;
4676             if (Shift->getOpcode() == Instruction::LShr) {
4677               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4678                                  "tmp");
4679             } else {
4680               // Insert a logical shift.
4681               NS = new ShiftInst(Instruction::LShr, AndCST,
4682                                  Shift->getOperand(1), "tmp");
4683             }
4684             InsertNewInstBefore(cast<Instruction>(NS), I);
4685
4686             // Compute X & (C << Y).
4687             Instruction *NewAnd = BinaryOperator::createAnd(
4688                 Shift->getOperand(0), NS, LHSI->getName());
4689             InsertNewInstBefore(NewAnd, I);
4690             
4691             I.setOperand(0, NewAnd);
4692             return &I;
4693           }
4694         }
4695         break;
4696
4697       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4698         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4699           if (I.isEquality()) {
4700             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4701
4702             // Check that the shift amount is in range.  If not, don't perform
4703             // undefined shifts.  When the shift is visited it will be
4704             // simplified.
4705             if (ShAmt->getZExtValue() >= TypeBits)
4706               break;
4707
4708             // If we are comparing against bits always shifted out, the
4709             // comparison cannot succeed.
4710             Constant *Comp =
4711               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4712             if (Comp != CI) {// Comparing against a bit that we know is zero.
4713               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4714               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4715               return ReplaceInstUsesWith(I, Cst);
4716             }
4717
4718             if (LHSI->hasOneUse()) {
4719               // Otherwise strength reduce the shift into an and.
4720               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4721               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4722               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4723
4724               Instruction *AndI =
4725                 BinaryOperator::createAnd(LHSI->getOperand(0),
4726                                           Mask, LHSI->getName()+".mask");
4727               Value *And = InsertNewInstBefore(AndI, I);
4728               return new ICmpInst(I.getPredicate(), And,
4729                                      ConstantExpr::getLShr(CI, ShAmt));
4730             }
4731           }
4732         }
4733         break;
4734
4735       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4736       case Instruction::AShr:
4737         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4738           if (I.isEquality()) {
4739             // Check that the shift amount is in range.  If not, don't perform
4740             // undefined shifts.  When the shift is visited it will be
4741             // simplified.
4742             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4743             if (ShAmt->getZExtValue() >= TypeBits)
4744               break;
4745
4746             // If we are comparing against bits always shifted out, the
4747             // comparison cannot succeed.
4748             Constant *Comp;
4749             if (LHSI->getOpcode() == Instruction::LShr) 
4750               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4751                                            ShAmt);
4752             else
4753               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4754                                            ShAmt);
4755
4756             if (Comp != CI) {// Comparing against a bit that we know is zero.
4757               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4758               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4759               return ReplaceInstUsesWith(I, Cst);
4760             }
4761
4762             if (LHSI->hasOneUse() || CI->isNullValue()) {
4763               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4764
4765               // Otherwise strength reduce the shift into an and.
4766               uint64_t Val = ~0ULL;          // All ones.
4767               Val <<= ShAmtVal;              // Shift over to the right spot.
4768               Val &= ~0ULL >> (64-TypeBits);
4769               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4770
4771               Instruction *AndI =
4772                 BinaryOperator::createAnd(LHSI->getOperand(0),
4773                                           Mask, LHSI->getName()+".mask");
4774               Value *And = InsertNewInstBefore(AndI, I);
4775               return new ICmpInst(I.getPredicate(), And,
4776                                      ConstantExpr::getShl(CI, ShAmt));
4777             }
4778           }
4779         }
4780         break;
4781
4782       case Instruction::SDiv:
4783       case Instruction::UDiv:
4784         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4785         // Fold this div into the comparison, producing a range check. 
4786         // Determine, based on the divide type, what the range is being 
4787         // checked.  If there is an overflow on the low or high side, remember 
4788         // it, otherwise compute the range [low, hi) bounding the new value.
4789         // See: InsertRangeTest above for the kinds of replacements possible.
4790         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4791           // FIXME: If the operand types don't match the type of the divide 
4792           // then don't attempt this transform. The code below doesn't have the
4793           // logic to deal with a signed divide and an unsigned compare (and
4794           // vice versa). This is because (x /s C1) <s C2  produces different 
4795           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4796           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4797           // work. :(  The if statement below tests that condition and bails 
4798           // if it finds it. 
4799           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4800           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4801             break;
4802
4803           // Initialize the variables that will indicate the nature of the
4804           // range check.
4805           bool LoOverflow = false, HiOverflow = false;
4806           ConstantInt *LoBound = 0, *HiBound = 0;
4807
4808           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4809           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4810           // C2 (CI). By solving for X we can turn this into a range check 
4811           // instead of computing a divide. 
4812           ConstantInt *Prod = 
4813             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4814
4815           // Determine if the product overflows by seeing if the product is
4816           // not equal to the divide. Make sure we do the same kind of divide
4817           // as in the LHS instruction that we're folding. 
4818           bool ProdOV = !DivRHS->isNullValue() && 
4819             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4820               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4821
4822           // Get the ICmp opcode
4823           ICmpInst::Predicate predicate = I.getPredicate();
4824
4825           if (DivRHS->isNullValue()) {  
4826             // Don't hack on divide by zeros!
4827           } else if (!DivIsSigned) {  // udiv
4828             LoBound = Prod;
4829             LoOverflow = ProdOV;
4830             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4831           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4832             if (CI->isNullValue()) {       // (X / pos) op 0
4833               // Can't overflow.
4834               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4835               HiBound = DivRHS;
4836             } else if (isPositive(CI)) {   // (X / pos) op pos
4837               LoBound = Prod;
4838               LoOverflow = ProdOV;
4839               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4840             } else {                       // (X / pos) op neg
4841               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4842               LoOverflow = AddWithOverflow(LoBound, Prod,
4843                                            cast<ConstantInt>(DivRHSH));
4844               HiBound = Prod;
4845               HiOverflow = ProdOV;
4846             }
4847           } else {                         // Divisor is < 0.
4848             if (CI->isNullValue()) {       // (X / neg) op 0
4849               LoBound = AddOne(DivRHS);
4850               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4851               if (HiBound == DivRHS)
4852                 LoBound = 0;               // - INTMIN = INTMIN
4853             } else if (isPositive(CI)) {   // (X / neg) op pos
4854               HiOverflow = LoOverflow = ProdOV;
4855               if (!LoOverflow)
4856                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4857               HiBound = AddOne(Prod);
4858             } else {                       // (X / neg) op neg
4859               LoBound = Prod;
4860               LoOverflow = HiOverflow = ProdOV;
4861               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4862             }
4863
4864             // Dividing by a negate swaps the condition.
4865             predicate = ICmpInst::getSwappedPredicate(predicate);
4866           }
4867
4868           if (LoBound) {
4869             Value *X = LHSI->getOperand(0);
4870             switch (predicate) {
4871             default: assert(0 && "Unhandled icmp opcode!");
4872             case ICmpInst::ICMP_EQ:
4873               if (LoOverflow && HiOverflow)
4874                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4875               else if (HiOverflow)
4876                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4877                                     ICmpInst::ICMP_UGE, X, LoBound);
4878               else if (LoOverflow)
4879                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4880                                     ICmpInst::ICMP_ULT, X, HiBound);
4881               else
4882                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4883                                        true, I);
4884             case ICmpInst::ICMP_NE:
4885               if (LoOverflow && HiOverflow)
4886                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4887               else if (HiOverflow)
4888                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4889                                     ICmpInst::ICMP_ULT, X, LoBound);
4890               else if (LoOverflow)
4891                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4892                                     ICmpInst::ICMP_UGE, X, HiBound);
4893               else
4894                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4895                                        false, I);
4896             case ICmpInst::ICMP_ULT:
4897             case ICmpInst::ICMP_SLT:
4898               if (LoOverflow)
4899                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4900               return new ICmpInst(predicate, X, LoBound);
4901             case ICmpInst::ICMP_UGT:
4902             case ICmpInst::ICMP_SGT:
4903               if (HiOverflow)
4904                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4905               if (predicate == ICmpInst::ICMP_UGT)
4906                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4907               else
4908                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4909             }
4910           }
4911         }
4912         break;
4913       }
4914
4915     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4916     if (I.isEquality()) {
4917       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4918
4919       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4920       // the second operand is a constant, simplify a bit.
4921       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4922         switch (BO->getOpcode()) {
4923         case Instruction::SRem:
4924           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4925           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4926               BO->hasOneUse()) {
4927             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4928             if (V > 1 && isPowerOf2_64(V)) {
4929               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4930                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4931               return new ICmpInst(I.getPredicate(), NewRem, 
4932                                   Constant::getNullValue(BO->getType()));
4933             }
4934           }
4935           break;
4936         case Instruction::Add:
4937           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4938           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4939             if (BO->hasOneUse())
4940               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4941                                   ConstantExpr::getSub(CI, BOp1C));
4942           } else if (CI->isNullValue()) {
4943             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4944             // efficiently invertible, or if the add has just this one use.
4945             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4946
4947             if (Value *NegVal = dyn_castNegVal(BOp1))
4948               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4949             else if (Value *NegVal = dyn_castNegVal(BOp0))
4950               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4951             else if (BO->hasOneUse()) {
4952               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4953               BO->setName("");
4954               InsertNewInstBefore(Neg, I);
4955               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4956             }
4957           }
4958           break;
4959         case Instruction::Xor:
4960           // For the xor case, we can xor two constants together, eliminating
4961           // the explicit xor.
4962           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4963             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4964                                 ConstantExpr::getXor(CI, BOC));
4965
4966           // FALLTHROUGH
4967         case Instruction::Sub:
4968           // Replace (([sub|xor] A, B) != 0) with (A != B)
4969           if (CI->isNullValue())
4970             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4971                                 BO->getOperand(1));
4972           break;
4973
4974         case Instruction::Or:
4975           // If bits are being or'd in that are not present in the constant we
4976           // are comparing against, then the comparison could never succeed!
4977           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4978             Constant *NotCI = ConstantExpr::getNot(CI);
4979             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4980               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4981                                                              isICMP_NE));
4982           }
4983           break;
4984
4985         case Instruction::And:
4986           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4987             // If bits are being compared against that are and'd out, then the
4988             // comparison can never succeed!
4989             if (!ConstantExpr::getAnd(CI,
4990                                       ConstantExpr::getNot(BOC))->isNullValue())
4991               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4992                                                              isICMP_NE));
4993
4994             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4995             if (CI == BOC && isOneBitSet(CI))
4996               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4997                                   ICmpInst::ICMP_NE, Op0,
4998                                   Constant::getNullValue(CI->getType()));
4999
5000             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5001             if (isSignBit(BOC)) {
5002               Value *X = BO->getOperand(0);
5003               Constant *Zero = Constant::getNullValue(X->getType());
5004               ICmpInst::Predicate pred = isICMP_NE ? 
5005                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5006               return new ICmpInst(pred, X, Zero);
5007             }
5008
5009             // ((X & ~7) == 0) --> X < 8
5010             if (CI->isNullValue() && isHighOnes(BOC)) {
5011               Value *X = BO->getOperand(0);
5012               Constant *NegX = ConstantExpr::getNeg(BOC);
5013               ICmpInst::Predicate pred = isICMP_NE ? 
5014                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5015               return new ICmpInst(pred, X, NegX);
5016             }
5017
5018           }
5019         default: break;
5020         }
5021       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5022         // Handle set{eq|ne} <intrinsic>, intcst.
5023         switch (II->getIntrinsicID()) {
5024         default: break;
5025         case Intrinsic::bswap_i16: 
5026           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5027           WorkList.push_back(II);  // Dead?
5028           I.setOperand(0, II->getOperand(1));
5029           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5030                                            ByteSwap_16(CI->getZExtValue())));
5031           return &I;
5032         case Intrinsic::bswap_i32:   
5033           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5034           WorkList.push_back(II);  // Dead?
5035           I.setOperand(0, II->getOperand(1));
5036           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5037                                            ByteSwap_32(CI->getZExtValue())));
5038           return &I;
5039         case Intrinsic::bswap_i64:   
5040           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5041           WorkList.push_back(II);  // Dead?
5042           I.setOperand(0, II->getOperand(1));
5043           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5044                                            ByteSwap_64(CI->getZExtValue())));
5045           return &I;
5046         }
5047       }
5048     } else {  // Not a ICMP_EQ/ICMP_NE
5049       // If the LHS is a cast from an integral value of the same size, then 
5050       // since we know the RHS is a constant, try to simlify.
5051       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5052         Value *CastOp = Cast->getOperand(0);
5053         const Type *SrcTy = CastOp->getType();
5054         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5055         if (SrcTy->isInteger() && 
5056             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5057           // If this is an unsigned comparison, try to make the comparison use
5058           // smaller constant values.
5059           switch (I.getPredicate()) {
5060             default: break;
5061             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5062               ConstantInt *CUI = cast<ConstantInt>(CI);
5063               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5064                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5065                                     ConstantInt::get(SrcTy, -1));
5066               break;
5067             }
5068             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5069               ConstantInt *CUI = cast<ConstantInt>(CI);
5070               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5071                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5072                                     Constant::getNullValue(SrcTy));
5073               break;
5074             }
5075           }
5076
5077         }
5078       }
5079     }
5080   }
5081
5082   // Handle icmp with constant RHS
5083   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5084     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5085       switch (LHSI->getOpcode()) {
5086       case Instruction::GetElementPtr:
5087         if (RHSC->isNullValue()) {
5088           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5089           bool isAllZeros = true;
5090           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5091             if (!isa<Constant>(LHSI->getOperand(i)) ||
5092                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5093               isAllZeros = false;
5094               break;
5095             }
5096           if (isAllZeros)
5097             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5098                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5099         }
5100         break;
5101
5102       case Instruction::PHI:
5103         if (Instruction *NV = FoldOpIntoPhi(I))
5104           return NV;
5105         break;
5106       case Instruction::Select:
5107         // If either operand of the select is a constant, we can fold the
5108         // comparison into the select arms, which will cause one to be
5109         // constant folded and the select turned into a bitwise or.
5110         Value *Op1 = 0, *Op2 = 0;
5111         if (LHSI->hasOneUse()) {
5112           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5113             // Fold the known value into the constant operand.
5114             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5115             // Insert a new ICmp of the other select operand.
5116             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5117                                                    LHSI->getOperand(2), RHSC,
5118                                                    I.getName()), I);
5119           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5120             // Fold the known value into the constant operand.
5121             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5122             // Insert a new ICmp of the other select operand.
5123             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5124                                                    LHSI->getOperand(1), RHSC,
5125                                                    I.getName()), I);
5126           }
5127         }
5128
5129         if (Op1)
5130           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5131         break;
5132       }
5133   }
5134
5135   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5136   if (User *GEP = dyn_castGetElementPtr(Op0))
5137     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5138       return NI;
5139   if (User *GEP = dyn_castGetElementPtr(Op1))
5140     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5141                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5142       return NI;
5143
5144   // Test to see if the operands of the icmp are casted versions of other
5145   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5146   // now.
5147   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5148     if (isa<PointerType>(Op0->getType()) && 
5149         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5150       // We keep moving the cast from the left operand over to the right
5151       // operand, where it can often be eliminated completely.
5152       Op0 = CI->getOperand(0);
5153
5154       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5155       // so eliminate it as well.
5156       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5157         Op1 = CI2->getOperand(0);
5158
5159       // If Op1 is a constant, we can fold the cast into the constant.
5160       if (Op0->getType() != Op1->getType())
5161         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5162           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5163         } else {
5164           // Otherwise, cast the RHS right before the icmp
5165           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5166         }
5167       return new ICmpInst(I.getPredicate(), Op0, Op1);
5168     }
5169   }
5170   
5171   if (isa<CastInst>(Op0)) {
5172     // Handle the special case of: icmp (cast bool to X), <cst>
5173     // This comes up when you have code like
5174     //   int X = A < B;
5175     //   if (X) ...
5176     // For generality, we handle any zero-extension of any operand comparison
5177     // with a constant or another cast from the same type.
5178     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5179       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5180         return R;
5181   }
5182   
5183   if (I.isEquality()) {
5184     Value *A, *B, *C, *D;
5185     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5186       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5187         Value *OtherVal = A == Op1 ? B : A;
5188         return new ICmpInst(I.getPredicate(), OtherVal,
5189                             Constant::getNullValue(A->getType()));
5190       }
5191
5192       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5193         // A^c1 == C^c2 --> A == C^(c1^c2)
5194         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5195           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5196             if (Op1->hasOneUse()) {
5197               Constant *NC = ConstantExpr::getXor(C1, C2);
5198               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5199               return new ICmpInst(I.getPredicate(), A,
5200                                   InsertNewInstBefore(Xor, I));
5201             }
5202         
5203         // A^B == A^D -> B == D
5204         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5205         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5206         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5207         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5208       }
5209     }
5210     
5211     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5212         (A == Op0 || B == Op0)) {
5213       // A == (A^B)  ->  B == 0
5214       Value *OtherVal = A == Op0 ? B : A;
5215       return new ICmpInst(I.getPredicate(), OtherVal,
5216                           Constant::getNullValue(A->getType()));
5217     }
5218     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5219       // (A-B) == A  ->  B == 0
5220       return new ICmpInst(I.getPredicate(), B,
5221                           Constant::getNullValue(B->getType()));
5222     }
5223     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5224       // A == (A-B)  ->  B == 0
5225       return new ICmpInst(I.getPredicate(), B,
5226                           Constant::getNullValue(B->getType()));
5227     }
5228     
5229     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5230     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5231         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5232         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5233       Value *X = 0, *Y = 0, *Z = 0;
5234       
5235       if (A == C) {
5236         X = B; Y = D; Z = A;
5237       } else if (A == D) {
5238         X = B; Y = C; Z = A;
5239       } else if (B == C) {
5240         X = A; Y = D; Z = B;
5241       } else if (B == D) {
5242         X = A; Y = C; Z = B;
5243       }
5244       
5245       if (X) {   // Build (X^Y) & Z
5246         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5247         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5248         I.setOperand(0, Op1);
5249         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5250         return &I;
5251       }
5252     }
5253   }
5254   return Changed ? &I : 0;
5255 }
5256
5257 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5258 // We only handle extending casts so far.
5259 //
5260 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5261   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5262   Value *LHSCIOp        = LHSCI->getOperand(0);
5263   const Type *SrcTy     = LHSCIOp->getType();
5264   const Type *DestTy    = LHSCI->getType();
5265   Value *RHSCIOp;
5266
5267   // We only handle extension cast instructions, so far. Enforce this.
5268   if (LHSCI->getOpcode() != Instruction::ZExt &&
5269       LHSCI->getOpcode() != Instruction::SExt)
5270     return 0;
5271
5272   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5273   bool isSignedCmp = ICI.isSignedPredicate();
5274
5275   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5276     // Not an extension from the same type?
5277     RHSCIOp = CI->getOperand(0);
5278     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5279       return 0;
5280     
5281     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5282     // and the other is a zext), then we can't handle this.
5283     if (CI->getOpcode() != LHSCI->getOpcode())
5284       return 0;
5285
5286     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5287     // then we can't handle this.
5288     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5289       return 0;
5290     
5291     // Okay, just insert a compare of the reduced operands now!
5292     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5293   }
5294
5295   // If we aren't dealing with a constant on the RHS, exit early
5296   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5297   if (!CI)
5298     return 0;
5299
5300   // Compute the constant that would happen if we truncated to SrcTy then
5301   // reextended to DestTy.
5302   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5303   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5304
5305   // If the re-extended constant didn't change...
5306   if (Res2 == CI) {
5307     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5308     // For example, we might have:
5309     //    %A = sext short %X to uint
5310     //    %B = icmp ugt uint %A, 1330
5311     // It is incorrect to transform this into 
5312     //    %B = icmp ugt short %X, 1330 
5313     // because %A may have negative value. 
5314     //
5315     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5316     // OR operation is EQ/NE.
5317     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5318       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5319     else
5320       return 0;
5321   }
5322
5323   // The re-extended constant changed so the constant cannot be represented 
5324   // in the shorter type. Consequently, we cannot emit a simple comparison.
5325
5326   // First, handle some easy cases. We know the result cannot be equal at this
5327   // point so handle the ICI.isEquality() cases
5328   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5329     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5330   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5331     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5332
5333   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5334   // should have been folded away previously and not enter in here.
5335   Value *Result;
5336   if (isSignedCmp) {
5337     // We're performing a signed comparison.
5338     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5339       Result = ConstantInt::getFalse();          // X < (small) --> false
5340     else
5341       Result = ConstantInt::getTrue();           // X < (large) --> true
5342   } else {
5343     // We're performing an unsigned comparison.
5344     if (isSignedExt) {
5345       // We're performing an unsigned comp with a sign extended value.
5346       // This is true if the input is >= 0. [aka >s -1]
5347       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5348       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5349                                    NegOne, ICI.getName()), ICI);
5350     } else {
5351       // Unsigned extend & unsigned compare -> always true.
5352       Result = ConstantInt::getTrue();
5353     }
5354   }
5355
5356   // Finally, return the value computed.
5357   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5358       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5359     return ReplaceInstUsesWith(ICI, Result);
5360   } else {
5361     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5362             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5363            "ICmp should be folded!");
5364     if (Constant *CI = dyn_cast<Constant>(Result))
5365       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5366     else
5367       return BinaryOperator::createNot(Result);
5368   }
5369 }
5370
5371 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5372   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5373   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5374
5375   // shl X, 0 == X and shr X, 0 == X
5376   // shl 0, X == 0 and shr 0, X == 0
5377   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5378       Op0 == Constant::getNullValue(Op0->getType()))
5379     return ReplaceInstUsesWith(I, Op0);
5380   
5381   if (isa<UndefValue>(Op0)) {            
5382     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5383       return ReplaceInstUsesWith(I, Op0);
5384     else                                    // undef << X -> 0, undef >>u X -> 0
5385       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5386   }
5387   if (isa<UndefValue>(Op1)) {
5388     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5389       return ReplaceInstUsesWith(I, Op0);          
5390     else                                     // X << undef, X >>u undef -> 0
5391       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5392   }
5393
5394   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5395   if (I.getOpcode() == Instruction::AShr)
5396     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5397       if (CSI->isAllOnesValue())
5398         return ReplaceInstUsesWith(I, CSI);
5399
5400   // Try to fold constant and into select arguments.
5401   if (isa<Constant>(Op0))
5402     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5403       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5404         return R;
5405
5406   // See if we can turn a signed shr into an unsigned shr.
5407   if (I.isArithmeticShift()) {
5408     if (MaskedValueIsZero(Op0,
5409                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5410       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5411     }
5412   }
5413
5414   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5415     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5416       return Res;
5417   return 0;
5418 }
5419
5420 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5421                                                ShiftInst &I) {
5422   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5423   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5424   bool isUnsignedShift = !isSignedShift;
5425
5426   // See if we can simplify any instructions used by the instruction whose sole 
5427   // purpose is to compute bits we don't care about.
5428   uint64_t KnownZero, KnownOne;
5429   if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
5430                            KnownZero, KnownOne))
5431     return &I;
5432   
5433   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5434   // of a signed value.
5435   //
5436   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5437   if (Op1->getZExtValue() >= TypeBits) {
5438     if (isUnsignedShift || isLeftShift)
5439       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5440     else {
5441       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5442       return &I;
5443     }
5444   }
5445   
5446   // ((X*C1) << C2) == (X * (C1 << C2))
5447   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5448     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5449       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5450         return BinaryOperator::createMul(BO->getOperand(0),
5451                                          ConstantExpr::getShl(BOOp, Op1));
5452   
5453   // Try to fold constant and into select arguments.
5454   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5455     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5456       return R;
5457   if (isa<PHINode>(Op0))
5458     if (Instruction *NV = FoldOpIntoPhi(I))
5459       return NV;
5460   
5461   if (Op0->hasOneUse()) {
5462     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5463       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5464       Value *V1, *V2;
5465       ConstantInt *CC;
5466       switch (Op0BO->getOpcode()) {
5467         default: break;
5468         case Instruction::Add:
5469         case Instruction::And:
5470         case Instruction::Or:
5471         case Instruction::Xor:
5472           // These operators commute.
5473           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5474           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5475               match(Op0BO->getOperand(1),
5476                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5477             Instruction *YS = new ShiftInst(Instruction::Shl, 
5478                                             Op0BO->getOperand(0), Op1,
5479                                             Op0BO->getName());
5480             InsertNewInstBefore(YS, I); // (Y << C)
5481             Instruction *X = 
5482               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5483                                      Op0BO->getOperand(1)->getName());
5484             InsertNewInstBefore(X, I);  // (X + (Y << C))
5485             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5486             C2 = ConstantExpr::getShl(C2, Op1);
5487             return BinaryOperator::createAnd(X, C2);
5488           }
5489           
5490           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5491           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5492               match(Op0BO->getOperand(1),
5493                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5494                           m_ConstantInt(CC))) && V2 == Op1 &&
5495       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5496             Instruction *YS = new ShiftInst(Instruction::Shl, 
5497                                             Op0BO->getOperand(0), Op1,
5498                                             Op0BO->getName());
5499             InsertNewInstBefore(YS, I); // (Y << C)
5500             Instruction *XM =
5501               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5502                                         V1->getName()+".mask");
5503             InsertNewInstBefore(XM, I); // X & (CC << C)
5504             
5505             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5506           }
5507           
5508           // FALL THROUGH.
5509         case Instruction::Sub:
5510           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5511           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5512               match(Op0BO->getOperand(0),
5513                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5514             Instruction *YS = new ShiftInst(Instruction::Shl, 
5515                                             Op0BO->getOperand(1), Op1,
5516                                             Op0BO->getName());
5517             InsertNewInstBefore(YS, I); // (Y << C)
5518             Instruction *X =
5519               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5520                                      Op0BO->getOperand(0)->getName());
5521             InsertNewInstBefore(X, I);  // (X + (Y << C))
5522             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5523             C2 = ConstantExpr::getShl(C2, Op1);
5524             return BinaryOperator::createAnd(X, C2);
5525           }
5526           
5527           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5528           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5529               match(Op0BO->getOperand(0),
5530                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5531                           m_ConstantInt(CC))) && V2 == Op1 &&
5532               cast<BinaryOperator>(Op0BO->getOperand(0))
5533                   ->getOperand(0)->hasOneUse()) {
5534             Instruction *YS = new ShiftInst(Instruction::Shl, 
5535                                             Op0BO->getOperand(1), Op1,
5536                                             Op0BO->getName());
5537             InsertNewInstBefore(YS, I); // (Y << C)
5538             Instruction *XM =
5539               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5540                                         V1->getName()+".mask");
5541             InsertNewInstBefore(XM, I); // X & (CC << C)
5542             
5543             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5544           }
5545           
5546           break;
5547       }
5548       
5549       
5550       // If the operand is an bitwise operator with a constant RHS, and the
5551       // shift is the only use, we can pull it out of the shift.
5552       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5553         bool isValid = true;     // Valid only for And, Or, Xor
5554         bool highBitSet = false; // Transform if high bit of constant set?
5555         
5556         switch (Op0BO->getOpcode()) {
5557           default: isValid = false; break;   // Do not perform transform!
5558           case Instruction::Add:
5559             isValid = isLeftShift;
5560             break;
5561           case Instruction::Or:
5562           case Instruction::Xor:
5563             highBitSet = false;
5564             break;
5565           case Instruction::And:
5566             highBitSet = true;
5567             break;
5568         }
5569         
5570         // If this is a signed shift right, and the high bit is modified
5571         // by the logical operation, do not perform the transformation.
5572         // The highBitSet boolean indicates the value of the high bit of
5573         // the constant which would cause it to be modified for this
5574         // operation.
5575         //
5576         if (isValid && !isLeftShift && isSignedShift) {
5577           uint64_t Val = Op0C->getZExtValue();
5578           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5579         }
5580         
5581         if (isValid) {
5582           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5583           
5584           Instruction *NewShift =
5585             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5586                           Op0BO->getName());
5587           Op0BO->setName("");
5588           InsertNewInstBefore(NewShift, I);
5589           
5590           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5591                                         NewRHS);
5592         }
5593       }
5594     }
5595   }
5596   
5597   // Find out if this is a shift of a shift by a constant.
5598   ShiftInst *ShiftOp = 0;
5599   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5600     ShiftOp = Op0SI;
5601   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5602     // If this is a noop-integer cast of a shift instruction, use the shift.
5603     if (isa<ShiftInst>(CI->getOperand(0))) {
5604       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5605     }
5606   }
5607   
5608   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5609     // Find the operands and properties of the input shift.  Note that the
5610     // signedness of the input shift may differ from the current shift if there
5611     // is a noop cast between the two.
5612     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5613     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5614     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5615     
5616     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5617
5618     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5619     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5620     
5621     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5622     if (isLeftShift == isShiftOfLeftShift) {
5623       // Do not fold these shifts if the first one is signed and the second one
5624       // is unsigned and this is a right shift.  Further, don't do any folding
5625       // on them.
5626       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5627         return 0;
5628       
5629       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5630       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5631         Amt = Op0->getType()->getPrimitiveSizeInBits();
5632       
5633       Value *Op = ShiftOp->getOperand(0);
5634       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5635                                           ConstantInt::get(Type::Int8Ty, Amt));
5636       if (I.getType() == ShiftResult->getType())
5637         return ShiftResult;
5638       InsertNewInstBefore(ShiftResult, I);
5639       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5640     }
5641     
5642     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5643     // signed types, we can only support the (A >> c1) << c2 configuration,
5644     // because it can not turn an arbitrary bit of A into a sign bit.
5645     if (isUnsignedShift || isLeftShift) {
5646       // Calculate bitmask for what gets shifted off the edge.
5647       Constant *C = ConstantInt::getAllOnesValue(I.getType());
5648       if (isLeftShift)
5649         C = ConstantExpr::getShl(C, ShiftAmt1C);
5650       else
5651         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5652       
5653       Value *Op = ShiftOp->getOperand(0);
5654       
5655       Instruction *Mask =
5656         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5657       InsertNewInstBefore(Mask, I);
5658       
5659       // Figure out what flavor of shift we should use...
5660       if (ShiftAmt1 == ShiftAmt2) {
5661         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5662       } else if (ShiftAmt1 < ShiftAmt2) {
5663         return new ShiftInst(I.getOpcode(), Mask,
5664                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5665       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5666         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5667           return new ShiftInst(Instruction::LShr, Mask, 
5668             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5669         } else {
5670           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5671                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5672         }
5673       } else {
5674         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5675         Instruction *Shift =
5676           new ShiftInst(ShiftOp->getOpcode(), Mask,
5677                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5678         InsertNewInstBefore(Shift, I);
5679         
5680         C = ConstantInt::getAllOnesValue(Shift->getType());
5681         C = ConstantExpr::getShl(C, Op1);
5682         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5683       }
5684     } else {
5685       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5686       // this case, C1 == C2 and C1 is 8, 16, or 32.
5687       if (ShiftAmt1 == ShiftAmt2) {
5688         const Type *SExtType = 0;
5689         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5690         case 8 : SExtType = Type::Int8Ty; break;
5691         case 16: SExtType = Type::Int16Ty; break;
5692         case 32: SExtType = Type::Int32Ty; break;
5693         }
5694         
5695         if (SExtType) {
5696           Instruction *NewTrunc = 
5697             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5698           InsertNewInstBefore(NewTrunc, I);
5699           return new SExtInst(NewTrunc, I.getType());
5700         }
5701       }
5702     }
5703   }
5704   return 0;
5705 }
5706
5707
5708 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5709 /// expression.  If so, decompose it, returning some value X, such that Val is
5710 /// X*Scale+Offset.
5711 ///
5712 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5713                                         unsigned &Offset) {
5714   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5715   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5716     Offset = CI->getZExtValue();
5717     Scale  = 1;
5718     return ConstantInt::get(Type::Int32Ty, 0);
5719   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5720     if (I->getNumOperands() == 2) {
5721       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5722         if (I->getOpcode() == Instruction::Shl) {
5723           // This is a value scaled by '1 << the shift amt'.
5724           Scale = 1U << CUI->getZExtValue();
5725           Offset = 0;
5726           return I->getOperand(0);
5727         } else if (I->getOpcode() == Instruction::Mul) {
5728           // This value is scaled by 'CUI'.
5729           Scale = CUI->getZExtValue();
5730           Offset = 0;
5731           return I->getOperand(0);
5732         } else if (I->getOpcode() == Instruction::Add) {
5733           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5734           // where C1 is divisible by C2.
5735           unsigned SubScale;
5736           Value *SubVal = 
5737             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5738           Offset += CUI->getZExtValue();
5739           if (SubScale > 1 && (Offset % SubScale == 0)) {
5740             Scale = SubScale;
5741             return SubVal;
5742           }
5743         }
5744       }
5745     }
5746   }
5747
5748   // Otherwise, we can't look past this.
5749   Scale = 1;
5750   Offset = 0;
5751   return Val;
5752 }
5753
5754
5755 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5756 /// try to eliminate the cast by moving the type information into the alloc.
5757 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5758                                                    AllocationInst &AI) {
5759   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5760   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5761   
5762   // Remove any uses of AI that are dead.
5763   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5764   std::vector<Instruction*> DeadUsers;
5765   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5766     Instruction *User = cast<Instruction>(*UI++);
5767     if (isInstructionTriviallyDead(User)) {
5768       while (UI != E && *UI == User)
5769         ++UI; // If this instruction uses AI more than once, don't break UI.
5770       
5771       // Add operands to the worklist.
5772       AddUsesToWorkList(*User);
5773       ++NumDeadInst;
5774       DOUT << "IC: DCE: " << *User;
5775       
5776       User->eraseFromParent();
5777       removeFromWorkList(User);
5778     }
5779   }
5780   
5781   // Get the type really allocated and the type casted to.
5782   const Type *AllocElTy = AI.getAllocatedType();
5783   const Type *CastElTy = PTy->getElementType();
5784   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5785
5786   unsigned AllocElTyAlign = TD->getTypeAlignmentABI(AllocElTy);
5787   unsigned CastElTyAlign = TD->getTypeAlignmentABI(CastElTy);
5788   if (CastElTyAlign < AllocElTyAlign) return 0;
5789
5790   // If the allocation has multiple uses, only promote it if we are strictly
5791   // increasing the alignment of the resultant allocation.  If we keep it the
5792   // same, we open the door to infinite loops of various kinds.
5793   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5794
5795   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5796   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5797   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5798
5799   // See if we can satisfy the modulus by pulling a scale out of the array
5800   // size argument.
5801   unsigned ArraySizeScale, ArrayOffset;
5802   Value *NumElements = // See if the array size is a decomposable linear expr.
5803     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5804  
5805   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5806   // do the xform.
5807   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5808       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5809
5810   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5811   Value *Amt = 0;
5812   if (Scale == 1) {
5813     Amt = NumElements;
5814   } else {
5815     // If the allocation size is constant, form a constant mul expression
5816     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5817     if (isa<ConstantInt>(NumElements))
5818       Amt = ConstantExpr::getMul(
5819               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5820     // otherwise multiply the amount and the number of elements
5821     else if (Scale != 1) {
5822       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5823       Amt = InsertNewInstBefore(Tmp, AI);
5824     }
5825   }
5826   
5827   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5828     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5829     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5830     Amt = InsertNewInstBefore(Tmp, AI);
5831   }
5832   
5833   std::string Name = AI.getName(); AI.setName("");
5834   AllocationInst *New;
5835   if (isa<MallocInst>(AI))
5836     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5837   else
5838     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5839   InsertNewInstBefore(New, AI);
5840   
5841   // If the allocation has multiple uses, insert a cast and change all things
5842   // that used it to use the new cast.  This will also hack on CI, but it will
5843   // die soon.
5844   if (!AI.hasOneUse()) {
5845     AddUsesToWorkList(AI);
5846     // New is the allocation instruction, pointer typed. AI is the original
5847     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5848     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5849     InsertNewInstBefore(NewCast, AI);
5850     AI.replaceAllUsesWith(NewCast);
5851   }
5852   return ReplaceInstUsesWith(CI, New);
5853 }
5854
5855 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5856 /// and return it without inserting any new casts.  This is used by code that
5857 /// tries to decide whether promoting or shrinking integer operations to wider
5858 /// or smaller types will allow us to eliminate a truncate or extend.
5859 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5860                                        int &NumCastsRemoved) {
5861   if (isa<Constant>(V)) return true;
5862   
5863   Instruction *I = dyn_cast<Instruction>(V);
5864   if (!I || !I->hasOneUse()) return false;
5865   
5866   switch (I->getOpcode()) {
5867   case Instruction::And:
5868   case Instruction::Or:
5869   case Instruction::Xor:
5870     // These operators can all arbitrarily be extended or truncated.
5871     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5872            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5873   case Instruction::AShr:
5874   case Instruction::LShr:
5875   case Instruction::Shl:
5876     // If this is just a bitcast changing the sign of the operation, we can
5877     // convert if the operand can be converted.
5878     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5879       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5880     break;
5881   case Instruction::Trunc:
5882   case Instruction::ZExt:
5883   case Instruction::SExt:
5884   case Instruction::BitCast:
5885     // If this is a cast from the destination type, we can trivially eliminate
5886     // it, and this will remove a cast overall.
5887     if (I->getOperand(0)->getType() == Ty) {
5888       // If the first operand is itself a cast, and is eliminable, do not count
5889       // this as an eliminable cast.  We would prefer to eliminate those two
5890       // casts first.
5891       if (isa<CastInst>(I->getOperand(0)))
5892         return true;
5893       
5894       ++NumCastsRemoved;
5895       return true;
5896     }
5897     break;
5898   default:
5899     // TODO: Can handle more cases here.
5900     break;
5901   }
5902   
5903   return false;
5904 }
5905
5906 /// EvaluateInDifferentType - Given an expression that 
5907 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5908 /// evaluate the expression.
5909 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5910                                              bool isSigned ) {
5911   if (Constant *C = dyn_cast<Constant>(V))
5912     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5913
5914   // Otherwise, it must be an instruction.
5915   Instruction *I = cast<Instruction>(V);
5916   Instruction *Res = 0;
5917   switch (I->getOpcode()) {
5918   case Instruction::And:
5919   case Instruction::Or:
5920   case Instruction::Xor: {
5921     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5922     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5923     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5924                                  LHS, RHS, I->getName());
5925     break;
5926   }
5927   case Instruction::AShr:
5928   case Instruction::LShr:
5929   case Instruction::Shl: {
5930     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5931     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5932                         I->getOperand(1), I->getName());
5933     break;
5934   }    
5935   case Instruction::Trunc:
5936   case Instruction::ZExt:
5937   case Instruction::SExt:
5938   case Instruction::BitCast:
5939     // If the source type of the cast is the type we're trying for then we can
5940     // just return the source. There's no need to insert it because its not new.
5941     if (I->getOperand(0)->getType() == Ty)
5942       return I->getOperand(0);
5943     
5944     // Some other kind of cast, which shouldn't happen, so just ..
5945     // FALL THROUGH
5946   default: 
5947     // TODO: Can handle more cases here.
5948     assert(0 && "Unreachable!");
5949     break;
5950   }
5951   
5952   return InsertNewInstBefore(Res, *I);
5953 }
5954
5955 /// @brief Implement the transforms common to all CastInst visitors.
5956 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5957   Value *Src = CI.getOperand(0);
5958
5959   // Casting undef to anything results in undef so might as just replace it and
5960   // get rid of the cast.
5961   if (isa<UndefValue>(Src))   // cast undef -> undef
5962     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5963
5964   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5965   // eliminate it now.
5966   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5967     if (Instruction::CastOps opc = 
5968         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5969       // The first cast (CSrc) is eliminable so we need to fix up or replace
5970       // the second cast (CI). CSrc will then have a good chance of being dead.
5971       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5972     }
5973   }
5974
5975   // If casting the result of a getelementptr instruction with no offset, turn
5976   // this into a cast of the original pointer!
5977   //
5978   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5979     bool AllZeroOperands = true;
5980     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5981       if (!isa<Constant>(GEP->getOperand(i)) ||
5982           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5983         AllZeroOperands = false;
5984         break;
5985       }
5986     if (AllZeroOperands) {
5987       // Changing the cast operand is usually not a good idea but it is safe
5988       // here because the pointer operand is being replaced with another 
5989       // pointer operand so the opcode doesn't need to change.
5990       CI.setOperand(0, GEP->getOperand(0));
5991       return &CI;
5992     }
5993   }
5994     
5995   // If we are casting a malloc or alloca to a pointer to a type of the same
5996   // size, rewrite the allocation instruction to allocate the "right" type.
5997   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5998     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5999       return V;
6000
6001   // If we are casting a select then fold the cast into the select
6002   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6003     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6004       return NV;
6005
6006   // If we are casting a PHI then fold the cast into the PHI
6007   if (isa<PHINode>(Src))
6008     if (Instruction *NV = FoldOpIntoPhi(CI))
6009       return NV;
6010   
6011   return 0;
6012 }
6013
6014 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6015 /// integers. This function implements the common transforms for all those
6016 /// cases.
6017 /// @brief Implement the transforms common to CastInst with integer operands
6018 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6019   if (Instruction *Result = commonCastTransforms(CI))
6020     return Result;
6021
6022   Value *Src = CI.getOperand(0);
6023   const Type *SrcTy = Src->getType();
6024   const Type *DestTy = CI.getType();
6025   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6026   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6027
6028   // See if we can simplify any instructions used by the LHS whose sole 
6029   // purpose is to compute bits we don't care about.
6030   uint64_t KnownZero = 0, KnownOne = 0;
6031   if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6032                            KnownZero, KnownOne))
6033     return &CI;
6034
6035   // If the source isn't an instruction or has more than one use then we
6036   // can't do anything more. 
6037   Instruction *SrcI = dyn_cast<Instruction>(Src);
6038   if (!SrcI || !Src->hasOneUse())
6039     return 0;
6040
6041   // Attempt to propagate the cast into the instruction.
6042   int NumCastsRemoved = 0;
6043   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6044     // If this cast is a truncate, evaluting in a different type always
6045     // eliminates the cast, so it is always a win.  If this is a noop-cast
6046     // this just removes a noop cast which isn't pointful, but simplifies
6047     // the code.  If this is a zero-extension, we need to do an AND to
6048     // maintain the clear top-part of the computation, so we require that
6049     // the input have eliminated at least one cast.  If this is a sign
6050     // extension, we insert two new casts (to do the extension) so we
6051     // require that two casts have been eliminated.
6052     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6053     if (!DoXForm) {
6054       switch (CI.getOpcode()) {
6055         case Instruction::Trunc:
6056           DoXForm = true;
6057           break;
6058         case Instruction::ZExt:
6059           DoXForm = NumCastsRemoved >= 1;
6060           break;
6061         case Instruction::SExt:
6062           DoXForm = NumCastsRemoved >= 2;
6063           break;
6064         case Instruction::BitCast:
6065           DoXForm = false;
6066           break;
6067         default:
6068           // All the others use floating point so we shouldn't actually 
6069           // get here because of the check above.
6070           assert(!"Unknown cast type .. unreachable");
6071           break;
6072       }
6073     }
6074     
6075     if (DoXForm) {
6076       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6077                                            CI.getOpcode() == Instruction::SExt);
6078       assert(Res->getType() == DestTy);
6079       switch (CI.getOpcode()) {
6080       default: assert(0 && "Unknown cast type!");
6081       case Instruction::Trunc:
6082       case Instruction::BitCast:
6083         // Just replace this cast with the result.
6084         return ReplaceInstUsesWith(CI, Res);
6085       case Instruction::ZExt: {
6086         // We need to emit an AND to clear the high bits.
6087         assert(SrcBitSize < DestBitSize && "Not a zext?");
6088         Constant *C = 
6089           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6090         if (DestBitSize < 64)
6091           C = ConstantExpr::getTrunc(C, DestTy);
6092         return BinaryOperator::createAnd(Res, C);
6093       }
6094       case Instruction::SExt:
6095         // We need to emit a cast to truncate, then a cast to sext.
6096         return CastInst::create(Instruction::SExt,
6097             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6098                              CI), DestTy);
6099       }
6100     }
6101   }
6102   
6103   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6104   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6105
6106   switch (SrcI->getOpcode()) {
6107   case Instruction::Add:
6108   case Instruction::Mul:
6109   case Instruction::And:
6110   case Instruction::Or:
6111   case Instruction::Xor:
6112     // If we are discarding information, or just changing the sign, 
6113     // rewrite.
6114     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6115       // Don't insert two casts if they cannot be eliminated.  We allow 
6116       // two casts to be inserted if the sizes are the same.  This could 
6117       // only be converting signedness, which is a noop.
6118       if (DestBitSize == SrcBitSize || 
6119           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6120           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6121         Instruction::CastOps opcode = CI.getOpcode();
6122         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6123         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6124         return BinaryOperator::create(
6125             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6126       }
6127     }
6128
6129     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6130     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6131         SrcI->getOpcode() == Instruction::Xor &&
6132         Op1 == ConstantInt::getTrue() &&
6133         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6134       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6135       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6136     }
6137     break;
6138   case Instruction::SDiv:
6139   case Instruction::UDiv:
6140   case Instruction::SRem:
6141   case Instruction::URem:
6142     // If we are just changing the sign, rewrite.
6143     if (DestBitSize == SrcBitSize) {
6144       // Don't insert two casts if they cannot be eliminated.  We allow 
6145       // two casts to be inserted if the sizes are the same.  This could 
6146       // only be converting signedness, which is a noop.
6147       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6148           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6149         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6150                                               Op0, DestTy, SrcI);
6151         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6152                                               Op1, DestTy, SrcI);
6153         return BinaryOperator::create(
6154           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6155       }
6156     }
6157     break;
6158
6159   case Instruction::Shl:
6160     // Allow changing the sign of the source operand.  Do not allow 
6161     // changing the size of the shift, UNLESS the shift amount is a 
6162     // constant.  We must not change variable sized shifts to a smaller 
6163     // size, because it is undefined to shift more bits out than exist 
6164     // in the value.
6165     if (DestBitSize == SrcBitSize ||
6166         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6167       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6168           Instruction::BitCast : Instruction::Trunc);
6169       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6170       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6171     }
6172     break;
6173   case Instruction::AShr:
6174     // If this is a signed shr, and if all bits shifted in are about to be
6175     // truncated off, turn it into an unsigned shr to allow greater
6176     // simplifications.
6177     if (DestBitSize < SrcBitSize &&
6178         isa<ConstantInt>(Op1)) {
6179       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6180       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6181         // Insert the new logical shift right.
6182         return new ShiftInst(Instruction::LShr, Op0, Op1);
6183       }
6184     }
6185     break;
6186
6187   case Instruction::ICmp:
6188     // If we are just checking for a icmp eq of a single bit and casting it
6189     // to an integer, then shift the bit to the appropriate place and then
6190     // cast to integer to avoid the comparison.
6191     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6192       uint64_t Op1CV = Op1C->getZExtValue();
6193       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6194       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6195       // cast (X == 1) to int --> X        iff X has only the low bit set.
6196       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6197       // cast (X != 0) to int --> X        iff X has only the low bit set.
6198       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6199       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6200       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6201       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6202         // If Op1C some other power of two, convert:
6203         uint64_t KnownZero, KnownOne;
6204         uint64_t TypeMask = Op1C->getType()->getBitMask();
6205         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6206
6207         // This only works for EQ and NE
6208         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6209         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6210           break;
6211         
6212         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6213           bool isNE = pred == ICmpInst::ICMP_NE;
6214           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6215             // (X&4) == 2 --> false
6216             // (X&4) != 2 --> true
6217             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6218             Res = ConstantExpr::getZExt(Res, CI.getType());
6219             return ReplaceInstUsesWith(CI, Res);
6220           }
6221           
6222           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6223           Value *In = Op0;
6224           if (ShiftAmt) {
6225             // Perform a logical shr by shiftamt.
6226             // Insert the shift to put the result in the low bit.
6227             In = InsertNewInstBefore(
6228               new ShiftInst(Instruction::LShr, In,
6229                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6230                             In->getName()+".lobit"), CI);
6231           }
6232           
6233           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6234             Constant *One = ConstantInt::get(In->getType(), 1);
6235             In = BinaryOperator::createXor(In, One, "tmp");
6236             InsertNewInstBefore(cast<Instruction>(In), CI);
6237           }
6238           
6239           if (CI.getType() == In->getType())
6240             return ReplaceInstUsesWith(CI, In);
6241           else
6242             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6243         }
6244       }
6245     }
6246     break;
6247   }
6248   return 0;
6249 }
6250
6251 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6252   if (Instruction *Result = commonIntCastTransforms(CI))
6253     return Result;
6254   
6255   Value *Src = CI.getOperand(0);
6256   const Type *Ty = CI.getType();
6257   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6258   
6259   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6260     switch (SrcI->getOpcode()) {
6261     default: break;
6262     case Instruction::LShr:
6263       // We can shrink lshr to something smaller if we know the bits shifted in
6264       // are already zeros.
6265       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6266         unsigned ShAmt = ShAmtV->getZExtValue();
6267         
6268         // Get a mask for the bits shifting in.
6269         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6270         Value* SrcIOp0 = SrcI->getOperand(0);
6271         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6272           if (ShAmt >= DestBitWidth)        // All zeros.
6273             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6274
6275           // Okay, we can shrink this.  Truncate the input, then return a new
6276           // shift.
6277           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6278           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6279         }
6280       } else {     // This is a variable shr.
6281         
6282         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6283         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6284         // loop-invariant and CSE'd.
6285         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6286           Value *One = ConstantInt::get(SrcI->getType(), 1);
6287
6288           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6289                                                        SrcI->getOperand(1),
6290                                                        "tmp"), CI);
6291           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6292                                                             SrcI->getOperand(0),
6293                                                             "tmp"), CI);
6294           Value *Zero = Constant::getNullValue(V->getType());
6295           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6296         }
6297       }
6298       break;
6299     }
6300   }
6301   
6302   return 0;
6303 }
6304
6305 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6306   // If one of the common conversion will work ..
6307   if (Instruction *Result = commonIntCastTransforms(CI))
6308     return Result;
6309
6310   Value *Src = CI.getOperand(0);
6311
6312   // If this is a cast of a cast
6313   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6314     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6315     // types and if the sizes are just right we can convert this into a logical
6316     // 'and' which will be much cheaper than the pair of casts.
6317     if (isa<TruncInst>(CSrc)) {
6318       // Get the sizes of the types involved
6319       Value *A = CSrc->getOperand(0);
6320       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6321       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6322       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6323       // If we're actually extending zero bits and the trunc is a no-op
6324       if (MidSize < DstSize && SrcSize == DstSize) {
6325         // Replace both of the casts with an And of the type mask.
6326         uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
6327         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6328         Instruction *And = 
6329           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6330         // Unfortunately, if the type changed, we need to cast it back.
6331         if (And->getType() != CI.getType()) {
6332           And->setName(CSrc->getName()+".mask");
6333           InsertNewInstBefore(And, CI);
6334           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6335         }
6336         return And;
6337       }
6338     }
6339   }
6340
6341   return 0;
6342 }
6343
6344 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6345   return commonIntCastTransforms(CI);
6346 }
6347
6348 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6349   return commonCastTransforms(CI);
6350 }
6351
6352 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6353   return commonCastTransforms(CI);
6354 }
6355
6356 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6357   return commonCastTransforms(CI);
6358 }
6359
6360 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6361   return commonCastTransforms(CI);
6362 }
6363
6364 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6365   return commonCastTransforms(CI);
6366 }
6367
6368 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6369   return commonCastTransforms(CI);
6370 }
6371
6372 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6373   return commonCastTransforms(CI);
6374 }
6375
6376 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6377   return commonCastTransforms(CI);
6378 }
6379
6380 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6381
6382   // If the operands are integer typed then apply the integer transforms,
6383   // otherwise just apply the common ones.
6384   Value *Src = CI.getOperand(0);
6385   const Type *SrcTy = Src->getType();
6386   const Type *DestTy = CI.getType();
6387
6388   if (SrcTy->isInteger() && DestTy->isInteger()) {
6389     if (Instruction *Result = commonIntCastTransforms(CI))
6390       return Result;
6391   } else {
6392     if (Instruction *Result = commonCastTransforms(CI))
6393       return Result;
6394   }
6395
6396
6397   // Get rid of casts from one type to the same type. These are useless and can
6398   // be replaced by the operand.
6399   if (DestTy == Src->getType())
6400     return ReplaceInstUsesWith(CI, Src);
6401
6402   // If the source and destination are pointers, and this cast is equivalent to
6403   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6404   // This can enhance SROA and other transforms that want type-safe pointers.
6405   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6406     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6407       const Type *DstElTy = DstPTy->getElementType();
6408       const Type *SrcElTy = SrcPTy->getElementType();
6409       
6410       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6411       unsigned NumZeros = 0;
6412       while (SrcElTy != DstElTy && 
6413              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6414              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6415         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6416         ++NumZeros;
6417       }
6418
6419       // If we found a path from the src to dest, create the getelementptr now.
6420       if (SrcElTy == DstElTy) {
6421         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6422         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6423       }
6424     }
6425   }
6426
6427   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6428     if (SVI->hasOneUse()) {
6429       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6430       // a bitconvert to a vector with the same # elts.
6431       if (isa<PackedType>(DestTy) && 
6432           cast<PackedType>(DestTy)->getNumElements() == 
6433                 SVI->getType()->getNumElements()) {
6434         CastInst *Tmp;
6435         // If either of the operands is a cast from CI.getType(), then
6436         // evaluating the shuffle in the casted destination's type will allow
6437         // us to eliminate at least one cast.
6438         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6439              Tmp->getOperand(0)->getType() == DestTy) ||
6440             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6441              Tmp->getOperand(0)->getType() == DestTy)) {
6442           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6443                                                SVI->getOperand(0), DestTy, &CI);
6444           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6445                                                SVI->getOperand(1), DestTy, &CI);
6446           // Return a new shuffle vector.  Use the same element ID's, as we
6447           // know the vector types match #elts.
6448           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6449         }
6450       }
6451     }
6452   }
6453   return 0;
6454 }
6455
6456 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6457 ///   %C = or %A, %B
6458 ///   %D = select %cond, %C, %A
6459 /// into:
6460 ///   %C = select %cond, %B, 0
6461 ///   %D = or %A, %C
6462 ///
6463 /// Assuming that the specified instruction is an operand to the select, return
6464 /// a bitmask indicating which operands of this instruction are foldable if they
6465 /// equal the other incoming value of the select.
6466 ///
6467 static unsigned GetSelectFoldableOperands(Instruction *I) {
6468   switch (I->getOpcode()) {
6469   case Instruction::Add:
6470   case Instruction::Mul:
6471   case Instruction::And:
6472   case Instruction::Or:
6473   case Instruction::Xor:
6474     return 3;              // Can fold through either operand.
6475   case Instruction::Sub:   // Can only fold on the amount subtracted.
6476   case Instruction::Shl:   // Can only fold on the shift amount.
6477   case Instruction::LShr:
6478   case Instruction::AShr:
6479     return 1;
6480   default:
6481     return 0;              // Cannot fold
6482   }
6483 }
6484
6485 /// GetSelectFoldableConstant - For the same transformation as the previous
6486 /// function, return the identity constant that goes into the select.
6487 static Constant *GetSelectFoldableConstant(Instruction *I) {
6488   switch (I->getOpcode()) {
6489   default: assert(0 && "This cannot happen!"); abort();
6490   case Instruction::Add:
6491   case Instruction::Sub:
6492   case Instruction::Or:
6493   case Instruction::Xor:
6494     return Constant::getNullValue(I->getType());
6495   case Instruction::Shl:
6496   case Instruction::LShr:
6497   case Instruction::AShr:
6498     return Constant::getNullValue(Type::Int8Ty);
6499   case Instruction::And:
6500     return ConstantInt::getAllOnesValue(I->getType());
6501   case Instruction::Mul:
6502     return ConstantInt::get(I->getType(), 1);
6503   }
6504 }
6505
6506 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6507 /// have the same opcode and only one use each.  Try to simplify this.
6508 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6509                                           Instruction *FI) {
6510   if (TI->getNumOperands() == 1) {
6511     // If this is a non-volatile load or a cast from the same type,
6512     // merge.
6513     if (TI->isCast()) {
6514       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6515         return 0;
6516     } else {
6517       return 0;  // unknown unary op.
6518     }
6519
6520     // Fold this by inserting a select from the input values.
6521     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6522                                        FI->getOperand(0), SI.getName()+".v");
6523     InsertNewInstBefore(NewSI, SI);
6524     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6525                             TI->getType());
6526   }
6527
6528   // Only handle binary, compare and shift operators here.
6529   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6530     return 0;
6531
6532   // Figure out if the operations have any operands in common.
6533   Value *MatchOp, *OtherOpT, *OtherOpF;
6534   bool MatchIsOpZero;
6535   if (TI->getOperand(0) == FI->getOperand(0)) {
6536     MatchOp  = TI->getOperand(0);
6537     OtherOpT = TI->getOperand(1);
6538     OtherOpF = FI->getOperand(1);
6539     MatchIsOpZero = true;
6540   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6541     MatchOp  = TI->getOperand(1);
6542     OtherOpT = TI->getOperand(0);
6543     OtherOpF = FI->getOperand(0);
6544     MatchIsOpZero = false;
6545   } else if (!TI->isCommutative()) {
6546     return 0;
6547   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6548     MatchOp  = TI->getOperand(0);
6549     OtherOpT = TI->getOperand(1);
6550     OtherOpF = FI->getOperand(0);
6551     MatchIsOpZero = true;
6552   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6553     MatchOp  = TI->getOperand(1);
6554     OtherOpT = TI->getOperand(0);
6555     OtherOpF = FI->getOperand(1);
6556     MatchIsOpZero = true;
6557   } else {
6558     return 0;
6559   }
6560
6561   // If we reach here, they do have operations in common.
6562   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6563                                      OtherOpF, SI.getName()+".v");
6564   InsertNewInstBefore(NewSI, SI);
6565
6566   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6567     if (MatchIsOpZero)
6568       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6569     else
6570       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6571   }
6572
6573   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6574   if (MatchIsOpZero)
6575     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6576   else
6577     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6578 }
6579
6580 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6581   Value *CondVal = SI.getCondition();
6582   Value *TrueVal = SI.getTrueValue();
6583   Value *FalseVal = SI.getFalseValue();
6584
6585   // select true, X, Y  -> X
6586   // select false, X, Y -> Y
6587   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6588     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6589
6590   // select C, X, X -> X
6591   if (TrueVal == FalseVal)
6592     return ReplaceInstUsesWith(SI, TrueVal);
6593
6594   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6595     return ReplaceInstUsesWith(SI, FalseVal);
6596   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6597     return ReplaceInstUsesWith(SI, TrueVal);
6598   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6599     if (isa<Constant>(TrueVal))
6600       return ReplaceInstUsesWith(SI, TrueVal);
6601     else
6602       return ReplaceInstUsesWith(SI, FalseVal);
6603   }
6604
6605   if (SI.getType() == Type::Int1Ty) {
6606     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6607       if (C->getZExtValue()) {
6608         // Change: A = select B, true, C --> A = or B, C
6609         return BinaryOperator::createOr(CondVal, FalseVal);
6610       } else {
6611         // Change: A = select B, false, C --> A = and !B, C
6612         Value *NotCond =
6613           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6614                                              "not."+CondVal->getName()), SI);
6615         return BinaryOperator::createAnd(NotCond, FalseVal);
6616       }
6617     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6618       if (C->getZExtValue() == false) {
6619         // Change: A = select B, C, false --> A = and B, C
6620         return BinaryOperator::createAnd(CondVal, TrueVal);
6621       } else {
6622         // Change: A = select B, C, true --> A = or !B, C
6623         Value *NotCond =
6624           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6625                                              "not."+CondVal->getName()), SI);
6626         return BinaryOperator::createOr(NotCond, TrueVal);
6627       }
6628     }
6629   }
6630
6631   // Selecting between two integer constants?
6632   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6633     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6634       // select C, 1, 0 -> cast C to int
6635       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6636         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6637       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6638         // select C, 0, 1 -> cast !C to int
6639         Value *NotCond =
6640           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6641                                                "not."+CondVal->getName()), SI);
6642         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6643       }
6644
6645       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6646
6647         // (x <s 0) ? -1 : 0 -> ashr x, 31
6648         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6649         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6650           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6651             bool CanXForm = false;
6652             if (IC->isSignedPredicate())
6653               CanXForm = CmpCst->isNullValue() && 
6654                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6655             else {
6656               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6657               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6658                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6659             }
6660             
6661             if (CanXForm) {
6662               // The comparison constant and the result are not neccessarily the
6663               // same width. Make an all-ones value by inserting a AShr.
6664               Value *X = IC->getOperand(0);
6665               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6666               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6667               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6668                                                ShAmt, "ones");
6669               InsertNewInstBefore(SRA, SI);
6670               
6671               // Finally, convert to the type of the select RHS.  We figure out
6672               // if this requires a SExt, Trunc or BitCast based on the sizes.
6673               Instruction::CastOps opc = Instruction::BitCast;
6674               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6675               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6676               if (SRASize < SISize)
6677                 opc = Instruction::SExt;
6678               else if (SRASize > SISize)
6679                 opc = Instruction::Trunc;
6680               return CastInst::create(opc, SRA, SI.getType());
6681             }
6682           }
6683
6684
6685         // If one of the constants is zero (we know they can't both be) and we
6686         // have a fcmp instruction with zero, and we have an 'and' with the
6687         // non-constant value, eliminate this whole mess.  This corresponds to
6688         // cases like this: ((X & 27) ? 27 : 0)
6689         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6690           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6691               cast<Constant>(IC->getOperand(1))->isNullValue())
6692             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6693               if (ICA->getOpcode() == Instruction::And &&
6694                   isa<ConstantInt>(ICA->getOperand(1)) &&
6695                   (ICA->getOperand(1) == TrueValC ||
6696                    ICA->getOperand(1) == FalseValC) &&
6697                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6698                 // Okay, now we know that everything is set up, we just don't
6699                 // know whether we have a icmp_ne or icmp_eq and whether the 
6700                 // true or false val is the zero.
6701                 bool ShouldNotVal = !TrueValC->isNullValue();
6702                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6703                 Value *V = ICA;
6704                 if (ShouldNotVal)
6705                   V = InsertNewInstBefore(BinaryOperator::create(
6706                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6707                 return ReplaceInstUsesWith(SI, V);
6708               }
6709       }
6710     }
6711
6712   // See if we are selecting two values based on a comparison of the two values.
6713   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6714     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6715       // Transform (X == Y) ? X : Y  -> Y
6716       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6717         return ReplaceInstUsesWith(SI, FalseVal);
6718       // Transform (X != Y) ? X : Y  -> X
6719       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6720         return ReplaceInstUsesWith(SI, TrueVal);
6721       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6722
6723     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6724       // Transform (X == Y) ? Y : X  -> X
6725       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6726         return ReplaceInstUsesWith(SI, FalseVal);
6727       // Transform (X != Y) ? Y : X  -> Y
6728       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6729         return ReplaceInstUsesWith(SI, TrueVal);
6730       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6731     }
6732   }
6733
6734   // See if we are selecting two values based on a comparison of the two values.
6735   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6736     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6737       // Transform (X == Y) ? X : Y  -> Y
6738       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6739         return ReplaceInstUsesWith(SI, FalseVal);
6740       // Transform (X != Y) ? X : Y  -> X
6741       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6742         return ReplaceInstUsesWith(SI, TrueVal);
6743       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6744
6745     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6746       // Transform (X == Y) ? Y : X  -> X
6747       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6748         return ReplaceInstUsesWith(SI, FalseVal);
6749       // Transform (X != Y) ? Y : X  -> Y
6750       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6751         return ReplaceInstUsesWith(SI, TrueVal);
6752       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6753     }
6754   }
6755
6756   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6757     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6758       if (TI->hasOneUse() && FI->hasOneUse()) {
6759         Instruction *AddOp = 0, *SubOp = 0;
6760
6761         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6762         if (TI->getOpcode() == FI->getOpcode())
6763           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6764             return IV;
6765
6766         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6767         // even legal for FP.
6768         if (TI->getOpcode() == Instruction::Sub &&
6769             FI->getOpcode() == Instruction::Add) {
6770           AddOp = FI; SubOp = TI;
6771         } else if (FI->getOpcode() == Instruction::Sub &&
6772                    TI->getOpcode() == Instruction::Add) {
6773           AddOp = TI; SubOp = FI;
6774         }
6775
6776         if (AddOp) {
6777           Value *OtherAddOp = 0;
6778           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6779             OtherAddOp = AddOp->getOperand(1);
6780           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6781             OtherAddOp = AddOp->getOperand(0);
6782           }
6783
6784           if (OtherAddOp) {
6785             // So at this point we know we have (Y -> OtherAddOp):
6786             //        select C, (add X, Y), (sub X, Z)
6787             Value *NegVal;  // Compute -Z
6788             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6789               NegVal = ConstantExpr::getNeg(C);
6790             } else {
6791               NegVal = InsertNewInstBefore(
6792                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6793             }
6794
6795             Value *NewTrueOp = OtherAddOp;
6796             Value *NewFalseOp = NegVal;
6797             if (AddOp != TI)
6798               std::swap(NewTrueOp, NewFalseOp);
6799             Instruction *NewSel =
6800               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6801
6802             NewSel = InsertNewInstBefore(NewSel, SI);
6803             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6804           }
6805         }
6806       }
6807
6808   // See if we can fold the select into one of our operands.
6809   if (SI.getType()->isInteger()) {
6810     // See the comment above GetSelectFoldableOperands for a description of the
6811     // transformation we are doing here.
6812     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6813       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6814           !isa<Constant>(FalseVal))
6815         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6816           unsigned OpToFold = 0;
6817           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6818             OpToFold = 1;
6819           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6820             OpToFold = 2;
6821           }
6822
6823           if (OpToFold) {
6824             Constant *C = GetSelectFoldableConstant(TVI);
6825             std::string Name = TVI->getName(); TVI->setName("");
6826             Instruction *NewSel =
6827               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6828                              Name);
6829             InsertNewInstBefore(NewSel, SI);
6830             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6831               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6832             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6833               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6834             else {
6835               assert(0 && "Unknown instruction!!");
6836             }
6837           }
6838         }
6839
6840     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6841       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6842           !isa<Constant>(TrueVal))
6843         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6844           unsigned OpToFold = 0;
6845           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6846             OpToFold = 1;
6847           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6848             OpToFold = 2;
6849           }
6850
6851           if (OpToFold) {
6852             Constant *C = GetSelectFoldableConstant(FVI);
6853             std::string Name = FVI->getName(); FVI->setName("");
6854             Instruction *NewSel =
6855               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6856                              Name);
6857             InsertNewInstBefore(NewSel, SI);
6858             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6859               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6860             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6861               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6862             else {
6863               assert(0 && "Unknown instruction!!");
6864             }
6865           }
6866         }
6867   }
6868
6869   if (BinaryOperator::isNot(CondVal)) {
6870     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6871     SI.setOperand(1, FalseVal);
6872     SI.setOperand(2, TrueVal);
6873     return &SI;
6874   }
6875
6876   return 0;
6877 }
6878
6879 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6880 /// determine, return it, otherwise return 0.
6881 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6882   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6883     unsigned Align = GV->getAlignment();
6884     if (Align == 0 && TD) 
6885       Align = TD->getTypeAlignmentPref(GV->getType()->getElementType());
6886     return Align;
6887   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6888     unsigned Align = AI->getAlignment();
6889     if (Align == 0 && TD) {
6890       if (isa<AllocaInst>(AI))
6891         Align = TD->getTypeAlignmentPref(AI->getType()->getElementType());
6892       else if (isa<MallocInst>(AI)) {
6893         // Malloc returns maximally aligned memory.
6894         Align = TD->getTypeAlignmentABI(AI->getType()->getElementType());
6895         Align =
6896           std::max(Align,
6897                    (unsigned)TD->getTypeAlignmentABI(Type::DoubleTy));
6898         Align =
6899           std::max(Align,
6900                    (unsigned)TD->getTypeAlignmentABI(Type::Int64Ty));
6901       }
6902     }
6903     return Align;
6904   } else if (isa<BitCastInst>(V) ||
6905              (isa<ConstantExpr>(V) && 
6906               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6907     User *CI = cast<User>(V);
6908     if (isa<PointerType>(CI->getOperand(0)->getType()))
6909       return GetKnownAlignment(CI->getOperand(0), TD);
6910     return 0;
6911   } else if (isa<GetElementPtrInst>(V) ||
6912              (isa<ConstantExpr>(V) && 
6913               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6914     User *GEPI = cast<User>(V);
6915     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6916     if (BaseAlignment == 0) return 0;
6917     
6918     // If all indexes are zero, it is just the alignment of the base pointer.
6919     bool AllZeroOperands = true;
6920     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6921       if (!isa<Constant>(GEPI->getOperand(i)) ||
6922           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6923         AllZeroOperands = false;
6924         break;
6925       }
6926     if (AllZeroOperands)
6927       return BaseAlignment;
6928     
6929     // Otherwise, if the base alignment is >= the alignment we expect for the
6930     // base pointer type, then we know that the resultant pointer is aligned at
6931     // least as much as its type requires.
6932     if (!TD) return 0;
6933
6934     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6935     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
6936     if (TD->getTypeAlignmentABI(PtrTy->getElementType())
6937         <= BaseAlignment) {
6938       const Type *GEPTy = GEPI->getType();
6939       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
6940       return TD->getTypeAlignmentABI(GEPPtrTy->getElementType());
6941     }
6942     return 0;
6943   }
6944   return 0;
6945 }
6946
6947
6948 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6949 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6950 /// the heavy lifting.
6951 ///
6952 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6953   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6954   if (!II) return visitCallSite(&CI);
6955   
6956   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6957   // visitCallSite.
6958   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6959     bool Changed = false;
6960
6961     // memmove/cpy/set of zero bytes is a noop.
6962     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6963       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6964
6965       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6966         if (CI->getZExtValue() == 1) {
6967           // Replace the instruction with just byte operations.  We would
6968           // transform other cases to loads/stores, but we don't know if
6969           // alignment is sufficient.
6970         }
6971     }
6972
6973     // If we have a memmove and the source operation is a constant global,
6974     // then the source and dest pointers can't alias, so we can change this
6975     // into a call to memcpy.
6976     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6977       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6978         if (GVSrc->isConstant()) {
6979           Module *M = CI.getParent()->getParent()->getParent();
6980           const char *Name;
6981           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6982               Type::Int32Ty)
6983             Name = "llvm.memcpy.i32";
6984           else
6985             Name = "llvm.memcpy.i64";
6986           Constant *MemCpy = M->getOrInsertFunction(Name,
6987                                      CI.getCalledFunction()->getFunctionType());
6988           CI.setOperand(0, MemCpy);
6989           Changed = true;
6990         }
6991     }
6992
6993     // If we can determine a pointer alignment that is bigger than currently
6994     // set, update the alignment.
6995     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6996       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6997       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6998       unsigned Align = std::min(Alignment1, Alignment2);
6999       if (MI->getAlignment()->getZExtValue() < Align) {
7000         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7001         Changed = true;
7002       }
7003     } else if (isa<MemSetInst>(MI)) {
7004       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7005       if (MI->getAlignment()->getZExtValue() < Alignment) {
7006         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7007         Changed = true;
7008       }
7009     }
7010           
7011     if (Changed) return II;
7012   } else {
7013     switch (II->getIntrinsicID()) {
7014     default: break;
7015     case Intrinsic::ppc_altivec_lvx:
7016     case Intrinsic::ppc_altivec_lvxl:
7017     case Intrinsic::x86_sse_loadu_ps:
7018     case Intrinsic::x86_sse2_loadu_pd:
7019     case Intrinsic::x86_sse2_loadu_dq:
7020       // Turn PPC lvx     -> load if the pointer is known aligned.
7021       // Turn X86 loadups -> load if the pointer is known aligned.
7022       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7023         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7024                                       PointerType::get(II->getType()), CI);
7025         return new LoadInst(Ptr);
7026       }
7027       break;
7028     case Intrinsic::ppc_altivec_stvx:
7029     case Intrinsic::ppc_altivec_stvxl:
7030       // Turn stvx -> store if the pointer is known aligned.
7031       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7032         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7033         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7034                                       OpPtrTy, CI);
7035         return new StoreInst(II->getOperand(1), Ptr);
7036       }
7037       break;
7038     case Intrinsic::x86_sse_storeu_ps:
7039     case Intrinsic::x86_sse2_storeu_pd:
7040     case Intrinsic::x86_sse2_storeu_dq:
7041     case Intrinsic::x86_sse2_storel_dq:
7042       // Turn X86 storeu -> store if the pointer is known aligned.
7043       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7044         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7045         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7046                                       OpPtrTy, CI);
7047         return new StoreInst(II->getOperand(2), Ptr);
7048       }
7049       break;
7050       
7051     case Intrinsic::x86_sse_cvttss2si: {
7052       // These intrinsics only demands the 0th element of its input vector.  If
7053       // we can simplify the input based on that, do so now.
7054       uint64_t UndefElts;
7055       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7056                                                 UndefElts)) {
7057         II->setOperand(1, V);
7058         return II;
7059       }
7060       break;
7061     }
7062       
7063     case Intrinsic::ppc_altivec_vperm:
7064       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7065       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7066         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7067         
7068         // Check that all of the elements are integer constants or undefs.
7069         bool AllEltsOk = true;
7070         for (unsigned i = 0; i != 16; ++i) {
7071           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7072               !isa<UndefValue>(Mask->getOperand(i))) {
7073             AllEltsOk = false;
7074             break;
7075           }
7076         }
7077         
7078         if (AllEltsOk) {
7079           // Cast the input vectors to byte vectors.
7080           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7081                                         II->getOperand(1), Mask->getType(), CI);
7082           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7083                                         II->getOperand(2), Mask->getType(), CI);
7084           Value *Result = UndefValue::get(Op0->getType());
7085           
7086           // Only extract each element once.
7087           Value *ExtractedElts[32];
7088           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7089           
7090           for (unsigned i = 0; i != 16; ++i) {
7091             if (isa<UndefValue>(Mask->getOperand(i)))
7092               continue;
7093             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7094             Idx &= 31;  // Match the hardware behavior.
7095             
7096             if (ExtractedElts[Idx] == 0) {
7097               Instruction *Elt = 
7098                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7099               InsertNewInstBefore(Elt, CI);
7100               ExtractedElts[Idx] = Elt;
7101             }
7102           
7103             // Insert this value into the result vector.
7104             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7105             InsertNewInstBefore(cast<Instruction>(Result), CI);
7106           }
7107           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7108         }
7109       }
7110       break;
7111
7112     case Intrinsic::stackrestore: {
7113       // If the save is right next to the restore, remove the restore.  This can
7114       // happen when variable allocas are DCE'd.
7115       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7116         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7117           BasicBlock::iterator BI = SS;
7118           if (&*++BI == II)
7119             return EraseInstFromFunction(CI);
7120         }
7121       }
7122       
7123       // If the stack restore is in a return/unwind block and if there are no
7124       // allocas or calls between the restore and the return, nuke the restore.
7125       TerminatorInst *TI = II->getParent()->getTerminator();
7126       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7127         BasicBlock::iterator BI = II;
7128         bool CannotRemove = false;
7129         for (++BI; &*BI != TI; ++BI) {
7130           if (isa<AllocaInst>(BI) ||
7131               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7132             CannotRemove = true;
7133             break;
7134           }
7135         }
7136         if (!CannotRemove)
7137           return EraseInstFromFunction(CI);
7138       }
7139       break;
7140     }
7141     }
7142   }
7143
7144   return visitCallSite(II);
7145 }
7146
7147 // InvokeInst simplification
7148 //
7149 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7150   return visitCallSite(&II);
7151 }
7152
7153 // visitCallSite - Improvements for call and invoke instructions.
7154 //
7155 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7156   bool Changed = false;
7157
7158   // If the callee is a constexpr cast of a function, attempt to move the cast
7159   // to the arguments of the call/invoke.
7160   if (transformConstExprCastCall(CS)) return 0;
7161
7162   Value *Callee = CS.getCalledValue();
7163
7164   if (Function *CalleeF = dyn_cast<Function>(Callee))
7165     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7166       Instruction *OldCall = CS.getInstruction();
7167       // If the call and callee calling conventions don't match, this call must
7168       // be unreachable, as the call is undefined.
7169       new StoreInst(ConstantInt::getTrue(),
7170                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7171       if (!OldCall->use_empty())
7172         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7173       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7174         return EraseInstFromFunction(*OldCall);
7175       return 0;
7176     }
7177
7178   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7179     // This instruction is not reachable, just remove it.  We insert a store to
7180     // undef so that we know that this code is not reachable, despite the fact
7181     // that we can't modify the CFG here.
7182     new StoreInst(ConstantInt::getTrue(),
7183                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7184                   CS.getInstruction());
7185
7186     if (!CS.getInstruction()->use_empty())
7187       CS.getInstruction()->
7188         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7189
7190     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7191       // Don't break the CFG, insert a dummy cond branch.
7192       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7193                      ConstantInt::getTrue(), II);
7194     }
7195     return EraseInstFromFunction(*CS.getInstruction());
7196   }
7197
7198   const PointerType *PTy = cast<PointerType>(Callee->getType());
7199   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7200   if (FTy->isVarArg()) {
7201     // See if we can optimize any arguments passed through the varargs area of
7202     // the call.
7203     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7204            E = CS.arg_end(); I != E; ++I)
7205       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7206         // If this cast does not effect the value passed through the varargs
7207         // area, we can eliminate the use of the cast.
7208         Value *Op = CI->getOperand(0);
7209         if (CI->isLosslessCast()) {
7210           *I = Op;
7211           Changed = true;
7212         }
7213       }
7214   }
7215
7216   return Changed ? CS.getInstruction() : 0;
7217 }
7218
7219 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7220 // attempt to move the cast to the arguments of the call/invoke.
7221 //
7222 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7223   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7224   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7225   if (CE->getOpcode() != Instruction::BitCast || 
7226       !isa<Function>(CE->getOperand(0)))
7227     return false;
7228   Function *Callee = cast<Function>(CE->getOperand(0));
7229   Instruction *Caller = CS.getInstruction();
7230
7231   // Okay, this is a cast from a function to a different type.  Unless doing so
7232   // would cause a type conversion of one of our arguments, change this call to
7233   // be a direct call with arguments casted to the appropriate types.
7234   //
7235   const FunctionType *FT = Callee->getFunctionType();
7236   const Type *OldRetTy = Caller->getType();
7237
7238   // Check to see if we are changing the return type...
7239   if (OldRetTy != FT->getReturnType()) {
7240     if (Callee->isDeclaration() && !Caller->use_empty() && 
7241         OldRetTy != FT->getReturnType() &&
7242         // Conversion is ok if changing from pointer to int of same size.
7243         !(isa<PointerType>(FT->getReturnType()) &&
7244           TD->getIntPtrType() == OldRetTy))
7245       return false;   // Cannot transform this return value.
7246
7247     // If the callsite is an invoke instruction, and the return value is used by
7248     // a PHI node in a successor, we cannot change the return type of the call
7249     // because there is no place to put the cast instruction (without breaking
7250     // the critical edge).  Bail out in this case.
7251     if (!Caller->use_empty())
7252       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7253         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7254              UI != E; ++UI)
7255           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7256             if (PN->getParent() == II->getNormalDest() ||
7257                 PN->getParent() == II->getUnwindDest())
7258               return false;
7259   }
7260
7261   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7262   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7263
7264   CallSite::arg_iterator AI = CS.arg_begin();
7265   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7266     const Type *ParamTy = FT->getParamType(i);
7267     const Type *ActTy = (*AI)->getType();
7268     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7269     //Either we can cast directly, or we can upconvert the argument
7270     bool isConvertible = ActTy == ParamTy ||
7271       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7272       (ParamTy->isInteger() && ActTy->isInteger() &&
7273        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7274       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7275        && c->getSExtValue() > 0);
7276     if (Callee->isDeclaration() && !isConvertible) return false;
7277   }
7278
7279   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7280       Callee->isDeclaration())
7281     return false;   // Do not delete arguments unless we have a function body...
7282
7283   // Okay, we decided that this is a safe thing to do: go ahead and start
7284   // inserting cast instructions as necessary...
7285   std::vector<Value*> Args;
7286   Args.reserve(NumActualArgs);
7287
7288   AI = CS.arg_begin();
7289   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7290     const Type *ParamTy = FT->getParamType(i);
7291     if ((*AI)->getType() == ParamTy) {
7292       Args.push_back(*AI);
7293     } else {
7294       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7295           false, ParamTy, false);
7296       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7297       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7298     }
7299   }
7300
7301   // If the function takes more arguments than the call was taking, add them
7302   // now...
7303   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7304     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7305
7306   // If we are removing arguments to the function, emit an obnoxious warning...
7307   if (FT->getNumParams() < NumActualArgs)
7308     if (!FT->isVarArg()) {
7309       cerr << "WARNING: While resolving call to function '"
7310            << Callee->getName() << "' arguments were dropped!\n";
7311     } else {
7312       // Add all of the arguments in their promoted form to the arg list...
7313       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7314         const Type *PTy = getPromotedType((*AI)->getType());
7315         if (PTy != (*AI)->getType()) {
7316           // Must promote to pass through va_arg area!
7317           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7318                                                                 PTy, false);
7319           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7320           InsertNewInstBefore(Cast, *Caller);
7321           Args.push_back(Cast);
7322         } else {
7323           Args.push_back(*AI);
7324         }
7325       }
7326     }
7327
7328   if (FT->getReturnType() == Type::VoidTy)
7329     Caller->setName("");   // Void type should not have a name...
7330
7331   Instruction *NC;
7332   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7333     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7334                         Args, Caller->getName(), Caller);
7335     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7336   } else {
7337     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7338     if (cast<CallInst>(Caller)->isTailCall())
7339       cast<CallInst>(NC)->setTailCall();
7340    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7341   }
7342
7343   // Insert a cast of the return type as necessary...
7344   Value *NV = NC;
7345   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7346     if (NV->getType() != Type::VoidTy) {
7347       const Type *CallerTy = Caller->getType();
7348       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7349                                                             CallerTy, false);
7350       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7351
7352       // If this is an invoke instruction, we should insert it after the first
7353       // non-phi, instruction in the normal successor block.
7354       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7355         BasicBlock::iterator I = II->getNormalDest()->begin();
7356         while (isa<PHINode>(I)) ++I;
7357         InsertNewInstBefore(NC, *I);
7358       } else {
7359         // Otherwise, it's a call, just insert cast right after the call instr
7360         InsertNewInstBefore(NC, *Caller);
7361       }
7362       AddUsersToWorkList(*Caller);
7363     } else {
7364       NV = UndefValue::get(Caller->getType());
7365     }
7366   }
7367
7368   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7369     Caller->replaceAllUsesWith(NV);
7370   Caller->getParent()->getInstList().erase(Caller);
7371   removeFromWorkList(Caller);
7372   return true;
7373 }
7374
7375 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7376 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7377 /// and a single binop.
7378 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7379   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7380   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7381          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7382   unsigned Opc = FirstInst->getOpcode();
7383   Value *LHSVal = FirstInst->getOperand(0);
7384   Value *RHSVal = FirstInst->getOperand(1);
7385     
7386   const Type *LHSType = LHSVal->getType();
7387   const Type *RHSType = RHSVal->getType();
7388   
7389   // Scan to see if all operands are the same opcode, all have one use, and all
7390   // kill their operands (i.e. the operands have one use).
7391   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7392     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7393     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7394         // Verify type of the LHS matches so we don't fold cmp's of different
7395         // types or GEP's with different index types.
7396         I->getOperand(0)->getType() != LHSType ||
7397         I->getOperand(1)->getType() != RHSType)
7398       return 0;
7399
7400     // If they are CmpInst instructions, check their predicates
7401     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7402       if (cast<CmpInst>(I)->getPredicate() !=
7403           cast<CmpInst>(FirstInst)->getPredicate())
7404         return 0;
7405     
7406     // Keep track of which operand needs a phi node.
7407     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7408     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7409   }
7410   
7411   // Otherwise, this is safe to transform, determine if it is profitable.
7412
7413   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7414   // Indexes are often folded into load/store instructions, so we don't want to
7415   // hide them behind a phi.
7416   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7417     return 0;
7418   
7419   Value *InLHS = FirstInst->getOperand(0);
7420   Value *InRHS = FirstInst->getOperand(1);
7421   PHINode *NewLHS = 0, *NewRHS = 0;
7422   if (LHSVal == 0) {
7423     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7424     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7425     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7426     InsertNewInstBefore(NewLHS, PN);
7427     LHSVal = NewLHS;
7428   }
7429   
7430   if (RHSVal == 0) {
7431     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7432     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7433     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7434     InsertNewInstBefore(NewRHS, PN);
7435     RHSVal = NewRHS;
7436   }
7437   
7438   // Add all operands to the new PHIs.
7439   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7440     if (NewLHS) {
7441       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7442       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7443     }
7444     if (NewRHS) {
7445       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7446       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7447     }
7448   }
7449     
7450   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7451     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7452   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7453     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7454                            RHSVal);
7455   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7456     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7457   else {
7458     assert(isa<GetElementPtrInst>(FirstInst));
7459     return new GetElementPtrInst(LHSVal, RHSVal);
7460   }
7461 }
7462
7463 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7464 /// of the block that defines it.  This means that it must be obvious the value
7465 /// of the load is not changed from the point of the load to the end of the
7466 /// block it is in.
7467 static bool isSafeToSinkLoad(LoadInst *L) {
7468   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7469   
7470   for (++BBI; BBI != E; ++BBI)
7471     if (BBI->mayWriteToMemory())
7472       return false;
7473   return true;
7474 }
7475
7476
7477 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7478 // operator and they all are only used by the PHI, PHI together their
7479 // inputs, and do the operation once, to the result of the PHI.
7480 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7481   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7482
7483   // Scan the instruction, looking for input operations that can be folded away.
7484   // If all input operands to the phi are the same instruction (e.g. a cast from
7485   // the same type or "+42") we can pull the operation through the PHI, reducing
7486   // code size and simplifying code.
7487   Constant *ConstantOp = 0;
7488   const Type *CastSrcTy = 0;
7489   bool isVolatile = false;
7490   if (isa<CastInst>(FirstInst)) {
7491     CastSrcTy = FirstInst->getOperand(0)->getType();
7492   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7493              isa<CmpInst>(FirstInst)) {
7494     // Can fold binop, compare or shift here if the RHS is a constant, 
7495     // otherwise call FoldPHIArgBinOpIntoPHI.
7496     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7497     if (ConstantOp == 0)
7498       return FoldPHIArgBinOpIntoPHI(PN);
7499   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7500     isVolatile = LI->isVolatile();
7501     // We can't sink the load if the loaded value could be modified between the
7502     // load and the PHI.
7503     if (LI->getParent() != PN.getIncomingBlock(0) ||
7504         !isSafeToSinkLoad(LI))
7505       return 0;
7506   } else if (isa<GetElementPtrInst>(FirstInst)) {
7507     if (FirstInst->getNumOperands() == 2)
7508       return FoldPHIArgBinOpIntoPHI(PN);
7509     // Can't handle general GEPs yet.
7510     return 0;
7511   } else {
7512     return 0;  // Cannot fold this operation.
7513   }
7514
7515   // Check to see if all arguments are the same operation.
7516   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7517     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7518     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7519     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7520       return 0;
7521     if (CastSrcTy) {
7522       if (I->getOperand(0)->getType() != CastSrcTy)
7523         return 0;  // Cast operation must match.
7524     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7525       // We can't sink the load if the loaded value could be modified between 
7526       // the load and the PHI.
7527       if (LI->isVolatile() != isVolatile ||
7528           LI->getParent() != PN.getIncomingBlock(i) ||
7529           !isSafeToSinkLoad(LI))
7530         return 0;
7531     } else if (I->getOperand(1) != ConstantOp) {
7532       return 0;
7533     }
7534   }
7535
7536   // Okay, they are all the same operation.  Create a new PHI node of the
7537   // correct type, and PHI together all of the LHS's of the instructions.
7538   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7539                                PN.getName()+".in");
7540   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7541
7542   Value *InVal = FirstInst->getOperand(0);
7543   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7544
7545   // Add all operands to the new PHI.
7546   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7547     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7548     if (NewInVal != InVal)
7549       InVal = 0;
7550     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7551   }
7552
7553   Value *PhiVal;
7554   if (InVal) {
7555     // The new PHI unions all of the same values together.  This is really
7556     // common, so we handle it intelligently here for compile-time speed.
7557     PhiVal = InVal;
7558     delete NewPN;
7559   } else {
7560     InsertNewInstBefore(NewPN, PN);
7561     PhiVal = NewPN;
7562   }
7563
7564   // Insert and return the new operation.
7565   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7566     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7567   else if (isa<LoadInst>(FirstInst))
7568     return new LoadInst(PhiVal, "", isVolatile);
7569   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7570     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7571   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7572     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7573                            PhiVal, ConstantOp);
7574   else
7575     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7576                          PhiVal, ConstantOp);
7577 }
7578
7579 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7580 /// that is dead.
7581 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7582   if (PN->use_empty()) return true;
7583   if (!PN->hasOneUse()) return false;
7584
7585   // Remember this node, and if we find the cycle, return.
7586   if (!PotentiallyDeadPHIs.insert(PN).second)
7587     return true;
7588
7589   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7590     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7591
7592   return false;
7593 }
7594
7595 // PHINode simplification
7596 //
7597 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7598   // If LCSSA is around, don't mess with Phi nodes
7599   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7600   
7601   if (Value *V = PN.hasConstantValue())
7602     return ReplaceInstUsesWith(PN, V);
7603
7604   // If all PHI operands are the same operation, pull them through the PHI,
7605   // reducing code size.
7606   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7607       PN.getIncomingValue(0)->hasOneUse())
7608     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7609       return Result;
7610
7611   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7612   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7613   // PHI)... break the cycle.
7614   if (PN.hasOneUse()) {
7615     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7616     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7617       std::set<PHINode*> PotentiallyDeadPHIs;
7618       PotentiallyDeadPHIs.insert(&PN);
7619       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7620         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7621     }
7622    
7623     // If this phi has a single use, and if that use just computes a value for
7624     // the next iteration of a loop, delete the phi.  This occurs with unused
7625     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7626     // common case here is good because the only other things that catch this
7627     // are induction variable analysis (sometimes) and ADCE, which is only run
7628     // late.
7629     if (PHIUser->hasOneUse() &&
7630         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7631         PHIUser->use_back() == &PN) {
7632       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7633     }
7634   }
7635
7636   return 0;
7637 }
7638
7639 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7640                                    Instruction *InsertPoint,
7641                                    InstCombiner *IC) {
7642   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7643   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7644   // We must cast correctly to the pointer type. Ensure that we
7645   // sign extend the integer value if it is smaller as this is
7646   // used for address computation.
7647   Instruction::CastOps opcode = 
7648      (VTySize < PtrSize ? Instruction::SExt :
7649       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7650   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7651 }
7652
7653
7654 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7655   Value *PtrOp = GEP.getOperand(0);
7656   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7657   // If so, eliminate the noop.
7658   if (GEP.getNumOperands() == 1)
7659     return ReplaceInstUsesWith(GEP, PtrOp);
7660
7661   if (isa<UndefValue>(GEP.getOperand(0)))
7662     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7663
7664   bool HasZeroPointerIndex = false;
7665   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7666     HasZeroPointerIndex = C->isNullValue();
7667
7668   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7669     return ReplaceInstUsesWith(GEP, PtrOp);
7670
7671   // Eliminate unneeded casts for indices.
7672   bool MadeChange = false;
7673   gep_type_iterator GTI = gep_type_begin(GEP);
7674   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7675     if (isa<SequentialType>(*GTI)) {
7676       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7677         if (CI->getOpcode() == Instruction::ZExt ||
7678             CI->getOpcode() == Instruction::SExt) {
7679           const Type *SrcTy = CI->getOperand(0)->getType();
7680           // We can eliminate a cast from i32 to i64 iff the target 
7681           // is a 32-bit pointer target.
7682           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7683             MadeChange = true;
7684             GEP.setOperand(i, CI->getOperand(0));
7685           }
7686         }
7687       }
7688       // If we are using a wider index than needed for this platform, shrink it
7689       // to what we need.  If the incoming value needs a cast instruction,
7690       // insert it.  This explicit cast can make subsequent optimizations more
7691       // obvious.
7692       Value *Op = GEP.getOperand(i);
7693       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7694         if (Constant *C = dyn_cast<Constant>(Op)) {
7695           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7696           MadeChange = true;
7697         } else {
7698           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7699                                 GEP);
7700           GEP.setOperand(i, Op);
7701           MadeChange = true;
7702         }
7703     }
7704   if (MadeChange) return &GEP;
7705
7706   // Combine Indices - If the source pointer to this getelementptr instruction
7707   // is a getelementptr instruction, combine the indices of the two
7708   // getelementptr instructions into a single instruction.
7709   //
7710   std::vector<Value*> SrcGEPOperands;
7711   if (User *Src = dyn_castGetElementPtr(PtrOp))
7712     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7713
7714   if (!SrcGEPOperands.empty()) {
7715     // Note that if our source is a gep chain itself that we wait for that
7716     // chain to be resolved before we perform this transformation.  This
7717     // avoids us creating a TON of code in some cases.
7718     //
7719     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7720         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7721       return 0;   // Wait until our source is folded to completion.
7722
7723     std::vector<Value *> Indices;
7724
7725     // Find out whether the last index in the source GEP is a sequential idx.
7726     bool EndsWithSequential = false;
7727     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7728            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7729       EndsWithSequential = !isa<StructType>(*I);
7730
7731     // Can we combine the two pointer arithmetics offsets?
7732     if (EndsWithSequential) {
7733       // Replace: gep (gep %P, long B), long A, ...
7734       // With:    T = long A+B; gep %P, T, ...
7735       //
7736       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7737       if (SO1 == Constant::getNullValue(SO1->getType())) {
7738         Sum = GO1;
7739       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7740         Sum = SO1;
7741       } else {
7742         // If they aren't the same type, convert both to an integer of the
7743         // target's pointer size.
7744         if (SO1->getType() != GO1->getType()) {
7745           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7746             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7747           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7748             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7749           } else {
7750             unsigned PS = TD->getPointerSize();
7751             if (TD->getTypeSize(SO1->getType()) == PS) {
7752               // Convert GO1 to SO1's type.
7753               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7754
7755             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7756               // Convert SO1 to GO1's type.
7757               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7758             } else {
7759               const Type *PT = TD->getIntPtrType();
7760               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7761               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7762             }
7763           }
7764         }
7765         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7766           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7767         else {
7768           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7769           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7770         }
7771       }
7772
7773       // Recycle the GEP we already have if possible.
7774       if (SrcGEPOperands.size() == 2) {
7775         GEP.setOperand(0, SrcGEPOperands[0]);
7776         GEP.setOperand(1, Sum);
7777         return &GEP;
7778       } else {
7779         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7780                        SrcGEPOperands.end()-1);
7781         Indices.push_back(Sum);
7782         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7783       }
7784     } else if (isa<Constant>(*GEP.idx_begin()) &&
7785                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7786                SrcGEPOperands.size() != 1) {
7787       // Otherwise we can do the fold if the first index of the GEP is a zero
7788       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7789                      SrcGEPOperands.end());
7790       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7791     }
7792
7793     if (!Indices.empty())
7794       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7795
7796   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7797     // GEP of global variable.  If all of the indices for this GEP are
7798     // constants, we can promote this to a constexpr instead of an instruction.
7799
7800     // Scan for nonconstants...
7801     SmallVector<Constant*, 8> Indices;
7802     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7803     for (; I != E && isa<Constant>(*I); ++I)
7804       Indices.push_back(cast<Constant>(*I));
7805
7806     if (I == E) {  // If they are all constants...
7807       Constant *CE = ConstantExpr::getGetElementPtr(GV,
7808                                                     &Indices[0],Indices.size());
7809
7810       // Replace all uses of the GEP with the new constexpr...
7811       return ReplaceInstUsesWith(GEP, CE);
7812     }
7813   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7814     if (!isa<PointerType>(X->getType())) {
7815       // Not interesting.  Source pointer must be a cast from pointer.
7816     } else if (HasZeroPointerIndex) {
7817       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7818       // into     : GEP [10 x ubyte]* X, long 0, ...
7819       //
7820       // This occurs when the program declares an array extern like "int X[];"
7821       //
7822       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7823       const PointerType *XTy = cast<PointerType>(X->getType());
7824       if (const ArrayType *XATy =
7825           dyn_cast<ArrayType>(XTy->getElementType()))
7826         if (const ArrayType *CATy =
7827             dyn_cast<ArrayType>(CPTy->getElementType()))
7828           if (CATy->getElementType() == XATy->getElementType()) {
7829             // At this point, we know that the cast source type is a pointer
7830             // to an array of the same type as the destination pointer
7831             // array.  Because the array type is never stepped over (there
7832             // is a leading zero) we can fold the cast into this GEP.
7833             GEP.setOperand(0, X);
7834             return &GEP;
7835           }
7836     } else if (GEP.getNumOperands() == 2) {
7837       // Transform things like:
7838       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7839       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7840       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7841       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7842       if (isa<ArrayType>(SrcElTy) &&
7843           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7844           TD->getTypeSize(ResElTy)) {
7845         Value *V = InsertNewInstBefore(
7846                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7847                                      GEP.getOperand(1), GEP.getName()), GEP);
7848         // V and GEP are both pointer types --> BitCast
7849         return new BitCastInst(V, GEP.getType());
7850       }
7851       
7852       // Transform things like:
7853       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7854       //   (where tmp = 8*tmp2) into:
7855       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7856       
7857       if (isa<ArrayType>(SrcElTy) &&
7858           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7859         uint64_t ArrayEltSize =
7860             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7861         
7862         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7863         // allow either a mul, shift, or constant here.
7864         Value *NewIdx = 0;
7865         ConstantInt *Scale = 0;
7866         if (ArrayEltSize == 1) {
7867           NewIdx = GEP.getOperand(1);
7868           Scale = ConstantInt::get(NewIdx->getType(), 1);
7869         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7870           NewIdx = ConstantInt::get(CI->getType(), 1);
7871           Scale = CI;
7872         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7873           if (Inst->getOpcode() == Instruction::Shl &&
7874               isa<ConstantInt>(Inst->getOperand(1))) {
7875             unsigned ShAmt =
7876               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7877             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7878             NewIdx = Inst->getOperand(0);
7879           } else if (Inst->getOpcode() == Instruction::Mul &&
7880                      isa<ConstantInt>(Inst->getOperand(1))) {
7881             Scale = cast<ConstantInt>(Inst->getOperand(1));
7882             NewIdx = Inst->getOperand(0);
7883           }
7884         }
7885
7886         // If the index will be to exactly the right offset with the scale taken
7887         // out, perform the transformation.
7888         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7889           if (isa<ConstantInt>(Scale))
7890             Scale = ConstantInt::get(Scale->getType(),
7891                                       Scale->getZExtValue() / ArrayEltSize);
7892           if (Scale->getZExtValue() != 1) {
7893             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7894                                                        true /*SExt*/);
7895             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7896             NewIdx = InsertNewInstBefore(Sc, GEP);
7897           }
7898
7899           // Insert the new GEP instruction.
7900           Instruction *NewGEP =
7901             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7902                                   NewIdx, GEP.getName());
7903           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7904           // The NewGEP must be pointer typed, so must the old one -> BitCast
7905           return new BitCastInst(NewGEP, GEP.getType());
7906         }
7907       }
7908     }
7909   }
7910
7911   return 0;
7912 }
7913
7914 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7915   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7916   if (AI.isArrayAllocation())    // Check C != 1
7917     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7918       const Type *NewTy = 
7919         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7920       AllocationInst *New = 0;
7921
7922       // Create and insert the replacement instruction...
7923       if (isa<MallocInst>(AI))
7924         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7925       else {
7926         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7927         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7928       }
7929
7930       InsertNewInstBefore(New, AI);
7931
7932       // Scan to the end of the allocation instructions, to skip over a block of
7933       // allocas if possible...
7934       //
7935       BasicBlock::iterator It = New;
7936       while (isa<AllocationInst>(*It)) ++It;
7937
7938       // Now that I is pointing to the first non-allocation-inst in the block,
7939       // insert our getelementptr instruction...
7940       //
7941       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7942       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7943                                        New->getName()+".sub", It);
7944
7945       // Now make everything use the getelementptr instead of the original
7946       // allocation.
7947       return ReplaceInstUsesWith(AI, V);
7948     } else if (isa<UndefValue>(AI.getArraySize())) {
7949       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7950     }
7951
7952   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7953   // Note that we only do this for alloca's, because malloc should allocate and
7954   // return a unique pointer, even for a zero byte allocation.
7955   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7956       TD->getTypeSize(AI.getAllocatedType()) == 0)
7957     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7958
7959   return 0;
7960 }
7961
7962 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7963   Value *Op = FI.getOperand(0);
7964
7965   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7966   if (CastInst *CI = dyn_cast<CastInst>(Op))
7967     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7968       FI.setOperand(0, CI->getOperand(0));
7969       return &FI;
7970     }
7971
7972   // free undef -> unreachable.
7973   if (isa<UndefValue>(Op)) {
7974     // Insert a new store to null because we cannot modify the CFG here.
7975     new StoreInst(ConstantInt::getTrue(),
7976                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
7977     return EraseInstFromFunction(FI);
7978   }
7979
7980   // If we have 'free null' delete the instruction.  This can happen in stl code
7981   // when lots of inlining happens.
7982   if (isa<ConstantPointerNull>(Op))
7983     return EraseInstFromFunction(FI);
7984
7985   return 0;
7986 }
7987
7988
7989 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7990 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7991   User *CI = cast<User>(LI.getOperand(0));
7992   Value *CastOp = CI->getOperand(0);
7993
7994   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7995   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7996     const Type *SrcPTy = SrcTy->getElementType();
7997
7998     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7999          isa<PackedType>(DestPTy)) {
8000       // If the source is an array, the code below will not succeed.  Check to
8001       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8002       // constants.
8003       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8004         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8005           if (ASrcTy->getNumElements() != 0) {
8006             Value *Idxs[2];
8007             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8008             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8009             SrcTy = cast<PointerType>(CastOp->getType());
8010             SrcPTy = SrcTy->getElementType();
8011           }
8012
8013       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8014             isa<PackedType>(SrcPTy)) &&
8015           // Do not allow turning this into a load of an integer, which is then
8016           // casted to a pointer, this pessimizes pointer analysis a lot.
8017           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8018           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8019                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8020
8021         // Okay, we are casting from one integer or pointer type to another of
8022         // the same size.  Instead of casting the pointer before the load, cast
8023         // the result of the loaded value.
8024         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8025                                                              CI->getName(),
8026                                                          LI.isVolatile()),LI);
8027         // Now cast the result of the load.
8028         return new BitCastInst(NewLoad, LI.getType());
8029       }
8030     }
8031   }
8032   return 0;
8033 }
8034
8035 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8036 /// from this value cannot trap.  If it is not obviously safe to load from the
8037 /// specified pointer, we do a quick local scan of the basic block containing
8038 /// ScanFrom, to determine if the address is already accessed.
8039 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8040   // If it is an alloca or global variable, it is always safe to load from.
8041   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8042
8043   // Otherwise, be a little bit agressive by scanning the local block where we
8044   // want to check to see if the pointer is already being loaded or stored
8045   // from/to.  If so, the previous load or store would have already trapped,
8046   // so there is no harm doing an extra load (also, CSE will later eliminate
8047   // the load entirely).
8048   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8049
8050   while (BBI != E) {
8051     --BBI;
8052
8053     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8054       if (LI->getOperand(0) == V) return true;
8055     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8056       if (SI->getOperand(1) == V) return true;
8057
8058   }
8059   return false;
8060 }
8061
8062 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8063   Value *Op = LI.getOperand(0);
8064
8065   // load (cast X) --> cast (load X) iff safe
8066   if (isa<CastInst>(Op))
8067     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8068       return Res;
8069
8070   // None of the following transforms are legal for volatile loads.
8071   if (LI.isVolatile()) return 0;
8072   
8073   if (&LI.getParent()->front() != &LI) {
8074     BasicBlock::iterator BBI = &LI; --BBI;
8075     // If the instruction immediately before this is a store to the same
8076     // address, do a simple form of store->load forwarding.
8077     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8078       if (SI->getOperand(1) == LI.getOperand(0))
8079         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8080     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8081       if (LIB->getOperand(0) == LI.getOperand(0))
8082         return ReplaceInstUsesWith(LI, LIB);
8083   }
8084
8085   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8086     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8087         isa<UndefValue>(GEPI->getOperand(0))) {
8088       // Insert a new store to null instruction before the load to indicate
8089       // that this code is not reachable.  We do this instead of inserting
8090       // an unreachable instruction directly because we cannot modify the
8091       // CFG.
8092       new StoreInst(UndefValue::get(LI.getType()),
8093                     Constant::getNullValue(Op->getType()), &LI);
8094       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8095     }
8096
8097   if (Constant *C = dyn_cast<Constant>(Op)) {
8098     // load null/undef -> undef
8099     if ((C->isNullValue() || isa<UndefValue>(C))) {
8100       // Insert a new store to null instruction before the load to indicate that
8101       // this code is not reachable.  We do this instead of inserting an
8102       // unreachable instruction directly because we cannot modify the CFG.
8103       new StoreInst(UndefValue::get(LI.getType()),
8104                     Constant::getNullValue(Op->getType()), &LI);
8105       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8106     }
8107
8108     // Instcombine load (constant global) into the value loaded.
8109     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8110       if (GV->isConstant() && !GV->isDeclaration())
8111         return ReplaceInstUsesWith(LI, GV->getInitializer());
8112
8113     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8114     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8115       if (CE->getOpcode() == Instruction::GetElementPtr) {
8116         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8117           if (GV->isConstant() && !GV->isDeclaration())
8118             if (Constant *V = 
8119                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8120               return ReplaceInstUsesWith(LI, V);
8121         if (CE->getOperand(0)->isNullValue()) {
8122           // Insert a new store to null instruction before the load to indicate
8123           // that this code is not reachable.  We do this instead of inserting
8124           // an unreachable instruction directly because we cannot modify the
8125           // CFG.
8126           new StoreInst(UndefValue::get(LI.getType()),
8127                         Constant::getNullValue(Op->getType()), &LI);
8128           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8129         }
8130
8131       } else if (CE->isCast()) {
8132         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8133           return Res;
8134       }
8135   }
8136
8137   if (Op->hasOneUse()) {
8138     // Change select and PHI nodes to select values instead of addresses: this
8139     // helps alias analysis out a lot, allows many others simplifications, and
8140     // exposes redundancy in the code.
8141     //
8142     // Note that we cannot do the transformation unless we know that the
8143     // introduced loads cannot trap!  Something like this is valid as long as
8144     // the condition is always false: load (select bool %C, int* null, int* %G),
8145     // but it would not be valid if we transformed it to load from null
8146     // unconditionally.
8147     //
8148     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8149       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8150       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8151           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8152         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8153                                      SI->getOperand(1)->getName()+".val"), LI);
8154         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8155                                      SI->getOperand(2)->getName()+".val"), LI);
8156         return new SelectInst(SI->getCondition(), V1, V2);
8157       }
8158
8159       // load (select (cond, null, P)) -> load P
8160       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8161         if (C->isNullValue()) {
8162           LI.setOperand(0, SI->getOperand(2));
8163           return &LI;
8164         }
8165
8166       // load (select (cond, P, null)) -> load P
8167       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8168         if (C->isNullValue()) {
8169           LI.setOperand(0, SI->getOperand(1));
8170           return &LI;
8171         }
8172     }
8173   }
8174   return 0;
8175 }
8176
8177 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8178 /// when possible.
8179 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8180   User *CI = cast<User>(SI.getOperand(1));
8181   Value *CastOp = CI->getOperand(0);
8182
8183   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8184   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8185     const Type *SrcPTy = SrcTy->getElementType();
8186
8187     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8188       // If the source is an array, the code below will not succeed.  Check to
8189       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8190       // constants.
8191       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8192         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8193           if (ASrcTy->getNumElements() != 0) {
8194             Value* Idxs[2];
8195             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8196             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8197             SrcTy = cast<PointerType>(CastOp->getType());
8198             SrcPTy = SrcTy->getElementType();
8199           }
8200
8201       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8202           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8203                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8204
8205         // Okay, we are casting from one integer or pointer type to another of
8206         // the same size.  Instead of casting the pointer before 
8207         // the store, cast the value to be stored.
8208         Value *NewCast;
8209         Value *SIOp0 = SI.getOperand(0);
8210         Instruction::CastOps opcode = Instruction::BitCast;
8211         const Type* CastSrcTy = SIOp0->getType();
8212         const Type* CastDstTy = SrcPTy;
8213         if (isa<PointerType>(CastDstTy)) {
8214           if (CastSrcTy->isInteger())
8215             opcode = Instruction::IntToPtr;
8216         } else if (isa<IntegerType>(CastDstTy)) {
8217           if (isa<PointerType>(SIOp0->getType()))
8218             opcode = Instruction::PtrToInt;
8219         }
8220         if (Constant *C = dyn_cast<Constant>(SIOp0))
8221           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8222         else
8223           NewCast = IC.InsertNewInstBefore(
8224             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8225             SI);
8226         return new StoreInst(NewCast, CastOp);
8227       }
8228     }
8229   }
8230   return 0;
8231 }
8232
8233 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8234   Value *Val = SI.getOperand(0);
8235   Value *Ptr = SI.getOperand(1);
8236
8237   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8238     EraseInstFromFunction(SI);
8239     ++NumCombined;
8240     return 0;
8241   }
8242   
8243   // If the RHS is an alloca with a single use, zapify the store, making the
8244   // alloca dead.
8245   if (Ptr->hasOneUse()) {
8246     if (isa<AllocaInst>(Ptr)) {
8247       EraseInstFromFunction(SI);
8248       ++NumCombined;
8249       return 0;
8250     }
8251     
8252     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8253       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8254           GEP->getOperand(0)->hasOneUse()) {
8255         EraseInstFromFunction(SI);
8256         ++NumCombined;
8257         return 0;
8258       }
8259   }
8260
8261   // Do really simple DSE, to catch cases where there are several consequtive
8262   // stores to the same location, separated by a few arithmetic operations. This
8263   // situation often occurs with bitfield accesses.
8264   BasicBlock::iterator BBI = &SI;
8265   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8266        --ScanInsts) {
8267     --BBI;
8268     
8269     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8270       // Prev store isn't volatile, and stores to the same location?
8271       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8272         ++NumDeadStore;
8273         ++BBI;
8274         EraseInstFromFunction(*PrevSI);
8275         continue;
8276       }
8277       break;
8278     }
8279     
8280     // If this is a load, we have to stop.  However, if the loaded value is from
8281     // the pointer we're loading and is producing the pointer we're storing,
8282     // then *this* store is dead (X = load P; store X -> P).
8283     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8284       if (LI == Val && LI->getOperand(0) == Ptr) {
8285         EraseInstFromFunction(SI);
8286         ++NumCombined;
8287         return 0;
8288       }
8289       // Otherwise, this is a load from some other location.  Stores before it
8290       // may not be dead.
8291       break;
8292     }
8293     
8294     // Don't skip over loads or things that can modify memory.
8295     if (BBI->mayWriteToMemory())
8296       break;
8297   }
8298   
8299   
8300   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8301
8302   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8303   if (isa<ConstantPointerNull>(Ptr)) {
8304     if (!isa<UndefValue>(Val)) {
8305       SI.setOperand(0, UndefValue::get(Val->getType()));
8306       if (Instruction *U = dyn_cast<Instruction>(Val))
8307         WorkList.push_back(U);  // Dropped a use.
8308       ++NumCombined;
8309     }
8310     return 0;  // Do not modify these!
8311   }
8312
8313   // store undef, Ptr -> noop
8314   if (isa<UndefValue>(Val)) {
8315     EraseInstFromFunction(SI);
8316     ++NumCombined;
8317     return 0;
8318   }
8319
8320   // If the pointer destination is a cast, see if we can fold the cast into the
8321   // source instead.
8322   if (isa<CastInst>(Ptr))
8323     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8324       return Res;
8325   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8326     if (CE->isCast())
8327       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8328         return Res;
8329
8330   
8331   // If this store is the last instruction in the basic block, and if the block
8332   // ends with an unconditional branch, try to move it to the successor block.
8333   BBI = &SI; ++BBI;
8334   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8335     if (BI->isUnconditional()) {
8336       // Check to see if the successor block has exactly two incoming edges.  If
8337       // so, see if the other predecessor contains a store to the same location.
8338       // if so, insert a PHI node (if needed) and move the stores down.
8339       BasicBlock *Dest = BI->getSuccessor(0);
8340
8341       pred_iterator PI = pred_begin(Dest);
8342       BasicBlock *Other = 0;
8343       if (*PI != BI->getParent())
8344         Other = *PI;
8345       ++PI;
8346       if (PI != pred_end(Dest)) {
8347         if (*PI != BI->getParent())
8348           if (Other)
8349             Other = 0;
8350           else
8351             Other = *PI;
8352         if (++PI != pred_end(Dest))
8353           Other = 0;
8354       }
8355       if (Other) {  // If only one other pred...
8356         BBI = Other->getTerminator();
8357         // Make sure this other block ends in an unconditional branch and that
8358         // there is an instruction before the branch.
8359         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8360             BBI != Other->begin()) {
8361           --BBI;
8362           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8363           
8364           // If this instruction is a store to the same location.
8365           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8366             // Okay, we know we can perform this transformation.  Insert a PHI
8367             // node now if we need it.
8368             Value *MergedVal = OtherStore->getOperand(0);
8369             if (MergedVal != SI.getOperand(0)) {
8370               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8371               PN->reserveOperandSpace(2);
8372               PN->addIncoming(SI.getOperand(0), SI.getParent());
8373               PN->addIncoming(OtherStore->getOperand(0), Other);
8374               MergedVal = InsertNewInstBefore(PN, Dest->front());
8375             }
8376             
8377             // Advance to a place where it is safe to insert the new store and
8378             // insert it.
8379             BBI = Dest->begin();
8380             while (isa<PHINode>(BBI)) ++BBI;
8381             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8382                                               OtherStore->isVolatile()), *BBI);
8383
8384             // Nuke the old stores.
8385             EraseInstFromFunction(SI);
8386             EraseInstFromFunction(*OtherStore);
8387             ++NumCombined;
8388             return 0;
8389           }
8390         }
8391       }
8392     }
8393   
8394   return 0;
8395 }
8396
8397
8398 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8399   // Change br (not X), label True, label False to: br X, label False, True
8400   Value *X = 0;
8401   BasicBlock *TrueDest;
8402   BasicBlock *FalseDest;
8403   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8404       !isa<Constant>(X)) {
8405     // Swap Destinations and condition...
8406     BI.setCondition(X);
8407     BI.setSuccessor(0, FalseDest);
8408     BI.setSuccessor(1, TrueDest);
8409     return &BI;
8410   }
8411
8412   // Cannonicalize fcmp_one -> fcmp_oeq
8413   FCmpInst::Predicate FPred; Value *Y;
8414   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8415                              TrueDest, FalseDest)))
8416     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8417          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8418       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8419       std::string Name = I->getName(); I->setName("");
8420       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8421       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8422       // Swap Destinations and condition...
8423       BI.setCondition(NewSCC);
8424       BI.setSuccessor(0, FalseDest);
8425       BI.setSuccessor(1, TrueDest);
8426       removeFromWorkList(I);
8427       I->getParent()->getInstList().erase(I);
8428       WorkList.push_back(cast<Instruction>(NewSCC));
8429       return &BI;
8430     }
8431
8432   // Cannonicalize icmp_ne -> icmp_eq
8433   ICmpInst::Predicate IPred;
8434   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8435                       TrueDest, FalseDest)))
8436     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8437          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8438          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8439       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8440       std::string Name = I->getName(); I->setName("");
8441       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8442       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8443       // Swap Destinations and condition...
8444       BI.setCondition(NewSCC);
8445       BI.setSuccessor(0, FalseDest);
8446       BI.setSuccessor(1, TrueDest);
8447       removeFromWorkList(I);
8448       I->getParent()->getInstList().erase(I);
8449       WorkList.push_back(cast<Instruction>(NewSCC));
8450       return &BI;
8451     }
8452
8453   return 0;
8454 }
8455
8456 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8457   Value *Cond = SI.getCondition();
8458   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8459     if (I->getOpcode() == Instruction::Add)
8460       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8461         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8462         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8463           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8464                                                 AddRHS));
8465         SI.setOperand(0, I->getOperand(0));
8466         WorkList.push_back(I);
8467         return &SI;
8468       }
8469   }
8470   return 0;
8471 }
8472
8473 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8474 /// is to leave as a vector operation.
8475 static bool CheapToScalarize(Value *V, bool isConstant) {
8476   if (isa<ConstantAggregateZero>(V)) 
8477     return true;
8478   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8479     if (isConstant) return true;
8480     // If all elts are the same, we can extract.
8481     Constant *Op0 = C->getOperand(0);
8482     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8483       if (C->getOperand(i) != Op0)
8484         return false;
8485     return true;
8486   }
8487   Instruction *I = dyn_cast<Instruction>(V);
8488   if (!I) return false;
8489   
8490   // Insert element gets simplified to the inserted element or is deleted if
8491   // this is constant idx extract element and its a constant idx insertelt.
8492   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8493       isa<ConstantInt>(I->getOperand(2)))
8494     return true;
8495   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8496     return true;
8497   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8498     if (BO->hasOneUse() &&
8499         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8500          CheapToScalarize(BO->getOperand(1), isConstant)))
8501       return true;
8502   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8503     if (CI->hasOneUse() &&
8504         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8505          CheapToScalarize(CI->getOperand(1), isConstant)))
8506       return true;
8507   
8508   return false;
8509 }
8510
8511 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8512 /// elements into values that are larger than the #elts in the input.
8513 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8514   unsigned NElts = SVI->getType()->getNumElements();
8515   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8516     return std::vector<unsigned>(NElts, 0);
8517   if (isa<UndefValue>(SVI->getOperand(2)))
8518     return std::vector<unsigned>(NElts, 2*NElts);
8519
8520   std::vector<unsigned> Result;
8521   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8522   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8523     if (isa<UndefValue>(CP->getOperand(i)))
8524       Result.push_back(NElts*2);  // undef -> 8
8525     else
8526       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8527   return Result;
8528 }
8529
8530 /// FindScalarElement - Given a vector and an element number, see if the scalar
8531 /// value is already around as a register, for example if it were inserted then
8532 /// extracted from the vector.
8533 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8534   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8535   const PackedType *PTy = cast<PackedType>(V->getType());
8536   unsigned Width = PTy->getNumElements();
8537   if (EltNo >= Width)  // Out of range access.
8538     return UndefValue::get(PTy->getElementType());
8539   
8540   if (isa<UndefValue>(V))
8541     return UndefValue::get(PTy->getElementType());
8542   else if (isa<ConstantAggregateZero>(V))
8543     return Constant::getNullValue(PTy->getElementType());
8544   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8545     return CP->getOperand(EltNo);
8546   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8547     // If this is an insert to a variable element, we don't know what it is.
8548     if (!isa<ConstantInt>(III->getOperand(2))) 
8549       return 0;
8550     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8551     
8552     // If this is an insert to the element we are looking for, return the
8553     // inserted value.
8554     if (EltNo == IIElt) 
8555       return III->getOperand(1);
8556     
8557     // Otherwise, the insertelement doesn't modify the value, recurse on its
8558     // vector input.
8559     return FindScalarElement(III->getOperand(0), EltNo);
8560   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8561     unsigned InEl = getShuffleMask(SVI)[EltNo];
8562     if (InEl < Width)
8563       return FindScalarElement(SVI->getOperand(0), InEl);
8564     else if (InEl < Width*2)
8565       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8566     else
8567       return UndefValue::get(PTy->getElementType());
8568   }
8569   
8570   // Otherwise, we don't know.
8571   return 0;
8572 }
8573
8574 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8575
8576   // If packed val is undef, replace extract with scalar undef.
8577   if (isa<UndefValue>(EI.getOperand(0)))
8578     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8579
8580   // If packed val is constant 0, replace extract with scalar 0.
8581   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8582     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8583   
8584   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8585     // If packed val is constant with uniform operands, replace EI
8586     // with that operand
8587     Constant *op0 = C->getOperand(0);
8588     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8589       if (C->getOperand(i) != op0) {
8590         op0 = 0; 
8591         break;
8592       }
8593     if (op0)
8594       return ReplaceInstUsesWith(EI, op0);
8595   }
8596   
8597   // If extracting a specified index from the vector, see if we can recursively
8598   // find a previously computed scalar that was inserted into the vector.
8599   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8600     // This instruction only demands the single element from the input vector.
8601     // If the input vector has a single use, simplify it based on this use
8602     // property.
8603     uint64_t IndexVal = IdxC->getZExtValue();
8604     if (EI.getOperand(0)->hasOneUse()) {
8605       uint64_t UndefElts;
8606       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8607                                                 1 << IndexVal,
8608                                                 UndefElts)) {
8609         EI.setOperand(0, V);
8610         return &EI;
8611       }
8612     }
8613     
8614     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8615       return ReplaceInstUsesWith(EI, Elt);
8616   }
8617   
8618   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8619     if (I->hasOneUse()) {
8620       // Push extractelement into predecessor operation if legal and
8621       // profitable to do so
8622       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8623         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8624         if (CheapToScalarize(BO, isConstantElt)) {
8625           ExtractElementInst *newEI0 = 
8626             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8627                                    EI.getName()+".lhs");
8628           ExtractElementInst *newEI1 =
8629             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8630                                    EI.getName()+".rhs");
8631           InsertNewInstBefore(newEI0, EI);
8632           InsertNewInstBefore(newEI1, EI);
8633           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8634         }
8635       } else if (isa<LoadInst>(I)) {
8636         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8637                                       PointerType::get(EI.getType()), EI);
8638         GetElementPtrInst *GEP = 
8639           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8640         InsertNewInstBefore(GEP, EI);
8641         return new LoadInst(GEP);
8642       }
8643     }
8644     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8645       // Extracting the inserted element?
8646       if (IE->getOperand(2) == EI.getOperand(1))
8647         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8648       // If the inserted and extracted elements are constants, they must not
8649       // be the same value, extract from the pre-inserted value instead.
8650       if (isa<Constant>(IE->getOperand(2)) &&
8651           isa<Constant>(EI.getOperand(1))) {
8652         AddUsesToWorkList(EI);
8653         EI.setOperand(0, IE->getOperand(0));
8654         return &EI;
8655       }
8656     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8657       // If this is extracting an element from a shufflevector, figure out where
8658       // it came from and extract from the appropriate input element instead.
8659       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8660         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8661         Value *Src;
8662         if (SrcIdx < SVI->getType()->getNumElements())
8663           Src = SVI->getOperand(0);
8664         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8665           SrcIdx -= SVI->getType()->getNumElements();
8666           Src = SVI->getOperand(1);
8667         } else {
8668           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8669         }
8670         return new ExtractElementInst(Src, SrcIdx);
8671       }
8672     }
8673   }
8674   return 0;
8675 }
8676
8677 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8678 /// elements from either LHS or RHS, return the shuffle mask and true. 
8679 /// Otherwise, return false.
8680 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8681                                          std::vector<Constant*> &Mask) {
8682   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8683          "Invalid CollectSingleShuffleElements");
8684   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8685
8686   if (isa<UndefValue>(V)) {
8687     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8688     return true;
8689   } else if (V == LHS) {
8690     for (unsigned i = 0; i != NumElts; ++i)
8691       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8692     return true;
8693   } else if (V == RHS) {
8694     for (unsigned i = 0; i != NumElts; ++i)
8695       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8696     return true;
8697   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8698     // If this is an insert of an extract from some other vector, include it.
8699     Value *VecOp    = IEI->getOperand(0);
8700     Value *ScalarOp = IEI->getOperand(1);
8701     Value *IdxOp    = IEI->getOperand(2);
8702     
8703     if (!isa<ConstantInt>(IdxOp))
8704       return false;
8705     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8706     
8707     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8708       // Okay, we can handle this if the vector we are insertinting into is
8709       // transitively ok.
8710       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8711         // If so, update the mask to reflect the inserted undef.
8712         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8713         return true;
8714       }      
8715     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8716       if (isa<ConstantInt>(EI->getOperand(1)) &&
8717           EI->getOperand(0)->getType() == V->getType()) {
8718         unsigned ExtractedIdx =
8719           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8720         
8721         // This must be extracting from either LHS or RHS.
8722         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8723           // Okay, we can handle this if the vector we are insertinting into is
8724           // transitively ok.
8725           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8726             // If so, update the mask to reflect the inserted value.
8727             if (EI->getOperand(0) == LHS) {
8728               Mask[InsertedIdx & (NumElts-1)] = 
8729                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8730             } else {
8731               assert(EI->getOperand(0) == RHS);
8732               Mask[InsertedIdx & (NumElts-1)] = 
8733                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8734               
8735             }
8736             return true;
8737           }
8738         }
8739       }
8740     }
8741   }
8742   // TODO: Handle shufflevector here!
8743   
8744   return false;
8745 }
8746
8747 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8748 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8749 /// that computes V and the LHS value of the shuffle.
8750 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8751                                      Value *&RHS) {
8752   assert(isa<PackedType>(V->getType()) && 
8753          (RHS == 0 || V->getType() == RHS->getType()) &&
8754          "Invalid shuffle!");
8755   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8756
8757   if (isa<UndefValue>(V)) {
8758     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8759     return V;
8760   } else if (isa<ConstantAggregateZero>(V)) {
8761     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8762     return V;
8763   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8764     // If this is an insert of an extract from some other vector, include it.
8765     Value *VecOp    = IEI->getOperand(0);
8766     Value *ScalarOp = IEI->getOperand(1);
8767     Value *IdxOp    = IEI->getOperand(2);
8768     
8769     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8770       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8771           EI->getOperand(0)->getType() == V->getType()) {
8772         unsigned ExtractedIdx =
8773           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8774         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8775         
8776         // Either the extracted from or inserted into vector must be RHSVec,
8777         // otherwise we'd end up with a shuffle of three inputs.
8778         if (EI->getOperand(0) == RHS || RHS == 0) {
8779           RHS = EI->getOperand(0);
8780           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8781           Mask[InsertedIdx & (NumElts-1)] = 
8782             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8783           return V;
8784         }
8785         
8786         if (VecOp == RHS) {
8787           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8788           // Everything but the extracted element is replaced with the RHS.
8789           for (unsigned i = 0; i != NumElts; ++i) {
8790             if (i != InsertedIdx)
8791               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8792           }
8793           return V;
8794         }
8795         
8796         // If this insertelement is a chain that comes from exactly these two
8797         // vectors, return the vector and the effective shuffle.
8798         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8799           return EI->getOperand(0);
8800         
8801       }
8802     }
8803   }
8804   // TODO: Handle shufflevector here!
8805   
8806   // Otherwise, can't do anything fancy.  Return an identity vector.
8807   for (unsigned i = 0; i != NumElts; ++i)
8808     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8809   return V;
8810 }
8811
8812 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8813   Value *VecOp    = IE.getOperand(0);
8814   Value *ScalarOp = IE.getOperand(1);
8815   Value *IdxOp    = IE.getOperand(2);
8816   
8817   // If the inserted element was extracted from some other vector, and if the 
8818   // indexes are constant, try to turn this into a shufflevector operation.
8819   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8820     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8821         EI->getOperand(0)->getType() == IE.getType()) {
8822       unsigned NumVectorElts = IE.getType()->getNumElements();
8823       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8824       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8825       
8826       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8827         return ReplaceInstUsesWith(IE, VecOp);
8828       
8829       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8830         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8831       
8832       // If we are extracting a value from a vector, then inserting it right
8833       // back into the same place, just use the input vector.
8834       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8835         return ReplaceInstUsesWith(IE, VecOp);      
8836       
8837       // We could theoretically do this for ANY input.  However, doing so could
8838       // turn chains of insertelement instructions into a chain of shufflevector
8839       // instructions, and right now we do not merge shufflevectors.  As such,
8840       // only do this in a situation where it is clear that there is benefit.
8841       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8842         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8843         // the values of VecOp, except then one read from EIOp0.
8844         // Build a new shuffle mask.
8845         std::vector<Constant*> Mask;
8846         if (isa<UndefValue>(VecOp))
8847           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8848         else {
8849           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8850           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8851                                                        NumVectorElts));
8852         } 
8853         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8854         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8855                                      ConstantPacked::get(Mask));
8856       }
8857       
8858       // If this insertelement isn't used by some other insertelement, turn it
8859       // (and any insertelements it points to), into one big shuffle.
8860       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8861         std::vector<Constant*> Mask;
8862         Value *RHS = 0;
8863         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8864         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8865         // We now have a shuffle of LHS, RHS, Mask.
8866         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8867       }
8868     }
8869   }
8870
8871   return 0;
8872 }
8873
8874
8875 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8876   Value *LHS = SVI.getOperand(0);
8877   Value *RHS = SVI.getOperand(1);
8878   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8879
8880   bool MadeChange = false;
8881   
8882   // Undefined shuffle mask -> undefined value.
8883   if (isa<UndefValue>(SVI.getOperand(2)))
8884     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8885   
8886   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8887   // the undef, change them to undefs.
8888   if (isa<UndefValue>(SVI.getOperand(1))) {
8889     // Scan to see if there are any references to the RHS.  If so, replace them
8890     // with undef element refs and set MadeChange to true.
8891     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8892       if (Mask[i] >= e && Mask[i] != 2*e) {
8893         Mask[i] = 2*e;
8894         MadeChange = true;
8895       }
8896     }
8897     
8898     if (MadeChange) {
8899       // Remap any references to RHS to use LHS.
8900       std::vector<Constant*> Elts;
8901       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8902         if (Mask[i] == 2*e)
8903           Elts.push_back(UndefValue::get(Type::Int32Ty));
8904         else
8905           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8906       }
8907       SVI.setOperand(2, ConstantPacked::get(Elts));
8908     }
8909   }
8910   
8911   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8912   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8913   if (LHS == RHS || isa<UndefValue>(LHS)) {
8914     if (isa<UndefValue>(LHS) && LHS == RHS) {
8915       // shuffle(undef,undef,mask) -> undef.
8916       return ReplaceInstUsesWith(SVI, LHS);
8917     }
8918     
8919     // Remap any references to RHS to use LHS.
8920     std::vector<Constant*> Elts;
8921     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8922       if (Mask[i] >= 2*e)
8923         Elts.push_back(UndefValue::get(Type::Int32Ty));
8924       else {
8925         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8926             (Mask[i] <  e && isa<UndefValue>(LHS)))
8927           Mask[i] = 2*e;     // Turn into undef.
8928         else
8929           Mask[i] &= (e-1);  // Force to LHS.
8930         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8931       }
8932     }
8933     SVI.setOperand(0, SVI.getOperand(1));
8934     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8935     SVI.setOperand(2, ConstantPacked::get(Elts));
8936     LHS = SVI.getOperand(0);
8937     RHS = SVI.getOperand(1);
8938     MadeChange = true;
8939   }
8940   
8941   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8942   bool isLHSID = true, isRHSID = true;
8943     
8944   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8945     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8946     // Is this an identity shuffle of the LHS value?
8947     isLHSID &= (Mask[i] == i);
8948       
8949     // Is this an identity shuffle of the RHS value?
8950     isRHSID &= (Mask[i]-e == i);
8951   }
8952
8953   // Eliminate identity shuffles.
8954   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8955   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8956   
8957   // If the LHS is a shufflevector itself, see if we can combine it with this
8958   // one without producing an unusual shuffle.  Here we are really conservative:
8959   // we are absolutely afraid of producing a shuffle mask not in the input
8960   // program, because the code gen may not be smart enough to turn a merged
8961   // shuffle into two specific shuffles: it may produce worse code.  As such,
8962   // we only merge two shuffles if the result is one of the two input shuffle
8963   // masks.  In this case, merging the shuffles just removes one instruction,
8964   // which we know is safe.  This is good for things like turning:
8965   // (splat(splat)) -> splat.
8966   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8967     if (isa<UndefValue>(RHS)) {
8968       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8969
8970       std::vector<unsigned> NewMask;
8971       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8972         if (Mask[i] >= 2*e)
8973           NewMask.push_back(2*e);
8974         else
8975           NewMask.push_back(LHSMask[Mask[i]]);
8976       
8977       // If the result mask is equal to the src shuffle or this shuffle mask, do
8978       // the replacement.
8979       if (NewMask == LHSMask || NewMask == Mask) {
8980         std::vector<Constant*> Elts;
8981         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8982           if (NewMask[i] >= e*2) {
8983             Elts.push_back(UndefValue::get(Type::Int32Ty));
8984           } else {
8985             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8986           }
8987         }
8988         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8989                                      LHSSVI->getOperand(1),
8990                                      ConstantPacked::get(Elts));
8991       }
8992     }
8993   }
8994
8995   return MadeChange ? &SVI : 0;
8996 }
8997
8998
8999
9000 void InstCombiner::removeFromWorkList(Instruction *I) {
9001   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
9002                  WorkList.end());
9003 }
9004
9005
9006 /// TryToSinkInstruction - Try to move the specified instruction from its
9007 /// current block into the beginning of DestBlock, which can only happen if it's
9008 /// safe to move the instruction past all of the instructions between it and the
9009 /// end of its block.
9010 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9011   assert(I->hasOneUse() && "Invariants didn't hold!");
9012
9013   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9014   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9015
9016   // Do not sink alloca instructions out of the entry block.
9017   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9018     return false;
9019
9020   // We can only sink load instructions if there is nothing between the load and
9021   // the end of block that could change the value.
9022   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9023     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9024          Scan != E; ++Scan)
9025       if (Scan->mayWriteToMemory())
9026         return false;
9027   }
9028
9029   BasicBlock::iterator InsertPos = DestBlock->begin();
9030   while (isa<PHINode>(InsertPos)) ++InsertPos;
9031
9032   I->moveBefore(InsertPos);
9033   ++NumSunkInst;
9034   return true;
9035 }
9036
9037
9038 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9039 /// all reachable code to the worklist.
9040 ///
9041 /// This has a couple of tricks to make the code faster and more powerful.  In
9042 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9043 /// them to the worklist (this significantly speeds up instcombine on code where
9044 /// many instructions are dead or constant).  Additionally, if we find a branch
9045 /// whose condition is a known constant, we only visit the reachable successors.
9046 ///
9047 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9048                                        std::set<BasicBlock*> &Visited,
9049                                        std::vector<Instruction*> &WorkList,
9050                                        const TargetData *TD) {
9051   // We have now visited this block!  If we've already been here, bail out.
9052   if (!Visited.insert(BB).second) return;
9053     
9054   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9055     Instruction *Inst = BBI++;
9056     
9057     // DCE instruction if trivially dead.
9058     if (isInstructionTriviallyDead(Inst)) {
9059       ++NumDeadInst;
9060       DOUT << "IC: DCE: " << *Inst;
9061       Inst->eraseFromParent();
9062       continue;
9063     }
9064     
9065     // ConstantProp instruction if trivially constant.
9066     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9067       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9068       Inst->replaceAllUsesWith(C);
9069       ++NumConstProp;
9070       Inst->eraseFromParent();
9071       continue;
9072     }
9073     
9074     WorkList.push_back(Inst);
9075   }
9076
9077   // Recursively visit successors.  If this is a branch or switch on a constant,
9078   // only visit the reachable successor.
9079   TerminatorInst *TI = BB->getTerminator();
9080   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9081     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9082       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9083       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9084                                  TD);
9085       return;
9086     }
9087   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9088     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9089       // See if this is an explicit destination.
9090       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9091         if (SI->getCaseValue(i) == Cond) {
9092           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9093           return;
9094         }
9095       
9096       // Otherwise it is the default destination.
9097       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9098       return;
9099     }
9100   }
9101   
9102   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9103     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9104 }
9105
9106 bool InstCombiner::runOnFunction(Function &F) {
9107   bool Changed = false;
9108   TD = &getAnalysis<TargetData>();
9109
9110   {
9111     // Do a depth-first traversal of the function, populate the worklist with
9112     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9113     // track of which blocks we visit.
9114     std::set<BasicBlock*> Visited;
9115     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9116
9117     // Do a quick scan over the function.  If we find any blocks that are
9118     // unreachable, remove any instructions inside of them.  This prevents
9119     // the instcombine code from having to deal with some bad special cases.
9120     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9121       if (!Visited.count(BB)) {
9122         Instruction *Term = BB->getTerminator();
9123         while (Term != BB->begin()) {   // Remove instrs bottom-up
9124           BasicBlock::iterator I = Term; --I;
9125
9126           DOUT << "IC: DCE: " << *I;
9127           ++NumDeadInst;
9128
9129           if (!I->use_empty())
9130             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9131           I->eraseFromParent();
9132         }
9133       }
9134   }
9135
9136   while (!WorkList.empty()) {
9137     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9138     WorkList.pop_back();
9139
9140     // Check to see if we can DCE the instruction.
9141     if (isInstructionTriviallyDead(I)) {
9142       // Add operands to the worklist.
9143       if (I->getNumOperands() < 4)
9144         AddUsesToWorkList(*I);
9145       ++NumDeadInst;
9146
9147       DOUT << "IC: DCE: " << *I;
9148
9149       I->eraseFromParent();
9150       removeFromWorkList(I);
9151       continue;
9152     }
9153
9154     // Instruction isn't dead, see if we can constant propagate it.
9155     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9156       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9157
9158       // Add operands to the worklist.
9159       AddUsesToWorkList(*I);
9160       ReplaceInstUsesWith(*I, C);
9161
9162       ++NumConstProp;
9163       I->eraseFromParent();
9164       removeFromWorkList(I);
9165       continue;
9166     }
9167
9168     // See if we can trivially sink this instruction to a successor basic block.
9169     if (I->hasOneUse()) {
9170       BasicBlock *BB = I->getParent();
9171       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9172       if (UserParent != BB) {
9173         bool UserIsSuccessor = false;
9174         // See if the user is one of our successors.
9175         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9176           if (*SI == UserParent) {
9177             UserIsSuccessor = true;
9178             break;
9179           }
9180
9181         // If the user is one of our immediate successors, and if that successor
9182         // only has us as a predecessors (we'd have to split the critical edge
9183         // otherwise), we can keep going.
9184         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9185             next(pred_begin(UserParent)) == pred_end(UserParent))
9186           // Okay, the CFG is simple enough, try to sink this instruction.
9187           Changed |= TryToSinkInstruction(I, UserParent);
9188       }
9189     }
9190
9191     // Now that we have an instruction, try combining it to simplify it...
9192     if (Instruction *Result = visit(*I)) {
9193       ++NumCombined;
9194       // Should we replace the old instruction with a new one?
9195       if (Result != I) {
9196         DOUT << "IC: Old = " << *I
9197              << "    New = " << *Result;
9198
9199         // Everything uses the new instruction now.
9200         I->replaceAllUsesWith(Result);
9201
9202         // Push the new instruction and any users onto the worklist.
9203         WorkList.push_back(Result);
9204         AddUsersToWorkList(*Result);
9205
9206         // Move the name to the new instruction first...
9207         std::string OldName = I->getName(); I->setName("");
9208         Result->setName(OldName);
9209
9210         // Insert the new instruction into the basic block...
9211         BasicBlock *InstParent = I->getParent();
9212         BasicBlock::iterator InsertPos = I;
9213
9214         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9215           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9216             ++InsertPos;
9217
9218         InstParent->getInstList().insert(InsertPos, Result);
9219
9220         // Make sure that we reprocess all operands now that we reduced their
9221         // use counts.
9222         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9223           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9224             WorkList.push_back(OpI);
9225
9226         // Instructions can end up on the worklist more than once.  Make sure
9227         // we do not process an instruction that has been deleted.
9228         removeFromWorkList(I);
9229
9230         // Erase the old instruction.
9231         InstParent->getInstList().erase(I);
9232       } else {
9233         DOUT << "IC: MOD = " << *I;
9234
9235         // If the instruction was modified, it's possible that it is now dead.
9236         // if so, remove it.
9237         if (isInstructionTriviallyDead(I)) {
9238           // Make sure we process all operands now that we are reducing their
9239           // use counts.
9240           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9241             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9242               WorkList.push_back(OpI);
9243
9244           // Instructions may end up in the worklist more than once.  Erase all
9245           // occurrences of this instruction.
9246           removeFromWorkList(I);
9247           I->eraseFromParent();
9248         } else {
9249           WorkList.push_back(Result);
9250           AddUsersToWorkList(*Result);
9251         }
9252       }
9253       Changed = true;
9254     }
9255   }
9256
9257   return Changed;
9258 }
9259
9260 FunctionPass *llvm::createInstructionCombiningPass() {
9261   return new InstCombiner();
9262 }
9263