205dfef84a82b48302414f6bd150e430a3dcb80e
[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/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62 STATISTIC(NumSunkInst , "Number of instructions sunk");
63
64 namespace {
65   class VISIBILITY_HIDDEN InstCombiner
66     : public FunctionPass,
67       public InstVisitor<InstCombiner, Instruction*> {
68     // Worklist of all of the instructions that need to be simplified.
69     std::vector<Instruction*> WorkList;
70     TargetData *TD;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(Value &I) {
77       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78            UI != UE; ++UI)
79         WorkList.push_back(cast<Instruction>(*UI));
80     }
81
82     /// AddUsesToWorkList - When an instruction is simplified, add operands to
83     /// the work lists because they might get more simplified now.
84     ///
85     void AddUsesToWorkList(Instruction &I) {
86       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88           WorkList.push_back(Op);
89     }
90     
91     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92     /// dead.  Add all of its operands to the worklist, turning them into
93     /// undef's to reduce the number of uses of those instructions.
94     ///
95     /// Return the specified operand before it is turned into an undef.
96     ///
97     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98       Value *R = I.getOperand(op);
99       
100       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102           WorkList.push_back(Op);
103           // Set the operand to undef to drop the use.
104           I.setOperand(i, UndefValue::get(Op->getType()));
105         }
106       
107       return R;
108     }
109
110     // removeFromWorkList - remove all instances of I from the worklist.
111     void removeFromWorkList(Instruction *I);
112   public:
113     virtual bool runOnFunction(Function &F);
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<TargetData>();
117       AU.addPreservedID(LCSSAID);
118       AU.setPreservesCFG();
119     }
120
121     TargetData &getTargetData() const { return *TD; }
122
123     // Visitation implementation - Implement instruction combining for different
124     // instruction types.  The semantics are as follows:
125     // Return Value:
126     //    null        - No change was made
127     //     I          - Change was made, I is still valid, I may be dead though
128     //   otherwise    - Change was made, replace I with returned instruction
129     //
130     Instruction *visitAdd(BinaryOperator &I);
131     Instruction *visitSub(BinaryOperator &I);
132     Instruction *visitMul(BinaryOperator &I);
133     Instruction *visitURem(BinaryOperator &I);
134     Instruction *visitSRem(BinaryOperator &I);
135     Instruction *visitFRem(BinaryOperator &I);
136     Instruction *commonRemTransforms(BinaryOperator &I);
137     Instruction *commonIRemTransforms(BinaryOperator &I);
138     Instruction *commonDivTransforms(BinaryOperator &I);
139     Instruction *commonIDivTransforms(BinaryOperator &I);
140     Instruction *visitUDiv(BinaryOperator &I);
141     Instruction *visitSDiv(BinaryOperator &I);
142     Instruction *visitFDiv(BinaryOperator &I);
143     Instruction *visitAnd(BinaryOperator &I);
144     Instruction *visitOr (BinaryOperator &I);
145     Instruction *visitXor(BinaryOperator &I);
146     Instruction *visitFCmpInst(FCmpInst &I);
147     Instruction *visitICmpInst(ICmpInst &I);
148     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
149
150     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151                              ICmpInst::Predicate Cond, Instruction &I);
152     Instruction *visitShiftInst(ShiftInst &I);
153     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154                                      ShiftInst &I);
155     Instruction *commonCastTransforms(CastInst &CI);
156     Instruction *commonIntCastTransforms(CastInst &CI);
157     Instruction *visitTrunc(CastInst &CI);
158     Instruction *visitZExt(CastInst &CI);
159     Instruction *visitSExt(CastInst &CI);
160     Instruction *visitFPTrunc(CastInst &CI);
161     Instruction *visitFPExt(CastInst &CI);
162     Instruction *visitFPToUI(CastInst &CI);
163     Instruction *visitFPToSI(CastInst &CI);
164     Instruction *visitUIToFP(CastInst &CI);
165     Instruction *visitSIToFP(CastInst &CI);
166     Instruction *visitPtrToInt(CastInst &CI);
167     Instruction *visitIntToPtr(CastInst &CI);
168     Instruction *visitBitCast(CastInst &CI);
169     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170                                 Instruction *FI);
171     Instruction *visitSelectInst(SelectInst &CI);
172     Instruction *visitCallInst(CallInst &CI);
173     Instruction *visitInvokeInst(InvokeInst &II);
174     Instruction *visitPHINode(PHINode &PN);
175     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
176     Instruction *visitAllocationInst(AllocationInst &AI);
177     Instruction *visitFreeInst(FreeInst &FI);
178     Instruction *visitLoadInst(LoadInst &LI);
179     Instruction *visitStoreInst(StoreInst &SI);
180     Instruction *visitBranchInst(BranchInst &BI);
181     Instruction *visitSwitchInst(SwitchInst &SI);
182     Instruction *visitInsertElementInst(InsertElementInst &IE);
183     Instruction *visitExtractElementInst(ExtractElementInst &EI);
184     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
185
186     // visitInstruction - Specify what to return for unhandled instructions...
187     Instruction *visitInstruction(Instruction &I) { return 0; }
188
189   private:
190     Instruction *visitCallSite(CallSite CS);
191     bool transformConstExprCastCall(CallSite CS);
192
193   public:
194     // InsertNewInstBefore - insert an instruction New before instruction Old
195     // in the program.  Add the new instruction to the worklist.
196     //
197     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
198       assert(New && New->getParent() == 0 &&
199              "New instruction already inserted into a basic block!");
200       BasicBlock *BB = Old.getParent();
201       BB->getInstList().insert(&Old, New);  // Insert inst
202       WorkList.push_back(New);              // Add to worklist
203       return New;
204     }
205
206     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207     /// This also adds the cast to the worklist.  Finally, this returns the
208     /// cast.
209     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210                             Instruction &Pos) {
211       if (V->getType() == Ty) return V;
212
213       if (Constant *CV = dyn_cast<Constant>(V))
214         return ConstantExpr::getCast(opc, CV, Ty);
215       
216       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
217       WorkList.push_back(C);
218       return C;
219     }
220
221     // ReplaceInstUsesWith - This method is to be used when an instruction is
222     // found to be dead, replacable with another preexisting expression.  Here
223     // we add all uses of I to the worklist, replace all uses of I with the new
224     // value, then return I, so that the inst combiner will know that I was
225     // modified.
226     //
227     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
228       AddUsersToWorkList(I);         // Add all modified instrs to worklist
229       if (&I != V) {
230         I.replaceAllUsesWith(V);
231         return &I;
232       } else {
233         // If we are replacing the instruction with itself, this must be in a
234         // segment of unreachable code, so just clobber the instruction.
235         I.replaceAllUsesWith(UndefValue::get(I.getType()));
236         return &I;
237       }
238     }
239
240     // UpdateValueUsesWith - This method is to be used when an value is
241     // found to be replacable with another preexisting expression or was
242     // updated.  Here we add all uses of I to the worklist, replace all uses of
243     // I with the new value (unless the instruction was just updated), then
244     // return true, so that the inst combiner will know that I was modified.
245     //
246     bool UpdateValueUsesWith(Value *Old, Value *New) {
247       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
248       if (Old != New)
249         Old->replaceAllUsesWith(New);
250       if (Instruction *I = dyn_cast<Instruction>(Old))
251         WorkList.push_back(I);
252       if (Instruction *I = dyn_cast<Instruction>(New))
253         WorkList.push_back(I);
254       return true;
255     }
256     
257     // EraseInstFromFunction - When dealing with an instruction that has side
258     // effects or produces a void value, we can't rely on DCE to delete the
259     // instruction.  Instead, visit methods should return the value returned by
260     // this function.
261     Instruction *EraseInstFromFunction(Instruction &I) {
262       assert(I.use_empty() && "Cannot erase instruction that is used!");
263       AddUsesToWorkList(I);
264       removeFromWorkList(&I);
265       I.eraseFromParent();
266       return 0;  // Don't do anything with FI
267     }
268
269   private:
270     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
272     /// casts that are known to not do anything...
273     ///
274     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275                                    Value *V, const Type *DestTy,
276                                    Instruction *InsertBefore);
277
278     /// SimplifyCommutative - This performs a few simplifications for 
279     /// commutative operators.
280     bool SimplifyCommutative(BinaryOperator &I);
281
282     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283     /// most-complex to least-complex order.
284     bool SimplifyCompare(CmpInst &I);
285
286     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
287                               uint64_t &KnownZero, uint64_t &KnownOne,
288                               unsigned Depth = 0);
289
290     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291                                       uint64_t &UndefElts, unsigned Depth = 0);
292       
293     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294     // PHI node as operand #0, see if we can fold the instruction into the PHI
295     // (which is only possible if all operands to the PHI are constants).
296     Instruction *FoldOpIntoPhi(Instruction &I);
297
298     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299     // operator and they all are only used by the PHI, PHI together their
300     // inputs, and do the operation once, to the result of the PHI.
301     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
302     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303     
304     
305     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
306                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
307     
308     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
309                               bool isSub, Instruction &I);
310     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
311                                  bool isSigned, bool Inside, Instruction &IB);
312     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
313     Instruction *MatchBSwap(BinaryOperator &I);
314
315     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
316   };
317
318   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
319 }
320
321 // getComplexity:  Assign a complexity or rank value to LLVM Values...
322 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
323 static unsigned getComplexity(Value *V) {
324   if (isa<Instruction>(V)) {
325     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
326       return 3;
327     return 4;
328   }
329   if (isa<Argument>(V)) return 3;
330   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
331 }
332
333 // isOnlyUse - Return true if this instruction will be deleted if we stop using
334 // it.
335 static bool isOnlyUse(Value *V) {
336   return V->hasOneUse() || isa<Constant>(V);
337 }
338
339 // getPromotedType - Return the specified type promoted as it would be to pass
340 // though a va_arg area...
341 static const Type *getPromotedType(const Type *Ty) {
342   switch (Ty->getTypeID()) {
343   case Type::SByteTyID:
344   case Type::ShortTyID:  return Type::IntTy;
345   case Type::UByteTyID:
346   case Type::UShortTyID: return Type::UIntTy;
347   case Type::FloatTyID:  return Type::DoubleTy;
348   default:               return Ty;
349   }
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 a noop cast, it isn't real codegen.
394   if (V->getType()->canLosslesslyBitCastTo(Ty))
395     return false;
396
397   // If this is another cast that can be eliminated, it isn't codegen either.
398   if (const CastInst *CI = dyn_cast<CastInst>(V))
399     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
400       return false;
401   return true;
402 }
403
404 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
405 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
406 /// casts that are known to not do anything...
407 ///
408 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
409                                              Value *V, const Type *DestTy,
410                                              Instruction *InsertBefore) {
411   if (V->getType() == DestTy) return V;
412   if (Constant *C = dyn_cast<Constant>(V))
413     return ConstantExpr::getCast(opcode, C, DestTy);
414   
415   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
416 }
417
418 // SimplifyCommutative - This performs a few simplifications for commutative
419 // operators:
420 //
421 //  1. Order operands such that they are listed from right (least complex) to
422 //     left (most complex).  This puts constants before unary operators before
423 //     binary operators.
424 //
425 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
426 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
427 //
428 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
429   bool Changed = false;
430   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
431     Changed = !I.swapOperands();
432
433   if (!I.isAssociative()) return Changed;
434   Instruction::BinaryOps Opcode = I.getOpcode();
435   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
436     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
437       if (isa<Constant>(I.getOperand(1))) {
438         Constant *Folded = ConstantExpr::get(I.getOpcode(),
439                                              cast<Constant>(I.getOperand(1)),
440                                              cast<Constant>(Op->getOperand(1)));
441         I.setOperand(0, Op->getOperand(0));
442         I.setOperand(1, Folded);
443         return true;
444       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
445         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
446             isOnlyUse(Op) && isOnlyUse(Op1)) {
447           Constant *C1 = cast<Constant>(Op->getOperand(1));
448           Constant *C2 = cast<Constant>(Op1->getOperand(1));
449
450           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
451           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
452           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
453                                                     Op1->getOperand(0),
454                                                     Op1->getName(), &I);
455           WorkList.push_back(New);
456           I.setOperand(0, New);
457           I.setOperand(1, Folded);
458           return true;
459         }
460     }
461   return Changed;
462 }
463
464 /// SimplifyCompare - For a CmpInst this function just orders the operands
465 /// so that theyare listed from right (least complex) to left (most complex).
466 /// This puts constants before unary operators before binary operators.
467 bool InstCombiner::SimplifyCompare(CmpInst &I) {
468   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
469     return false;
470   I.swapOperands();
471   // Compare instructions are not associative so there's nothing else we can do.
472   return true;
473 }
474
475 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
476 // if the LHS is a constant zero (which is the 'negate' form).
477 //
478 static inline Value *dyn_castNegVal(Value *V) {
479   if (BinaryOperator::isNeg(V))
480     return BinaryOperator::getNegArgument(V);
481
482   // Constants can be considered to be negated values if they can be folded.
483   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
484     return ConstantExpr::getNeg(C);
485   return 0;
486 }
487
488 static inline Value *dyn_castNotVal(Value *V) {
489   if (BinaryOperator::isNot(V))
490     return BinaryOperator::getNotArgument(V);
491
492   // Constants can be considered to be not'ed values...
493   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
494     return ConstantExpr::getNot(C);
495   return 0;
496 }
497
498 // dyn_castFoldableMul - If this value is a multiply that can be folded into
499 // other computations (because it has a constant operand), return the
500 // non-constant operand of the multiply, and set CST to point to the multiplier.
501 // Otherwise, return null.
502 //
503 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
504   if (V->hasOneUse() && V->getType()->isInteger())
505     if (Instruction *I = dyn_cast<Instruction>(V)) {
506       if (I->getOpcode() == Instruction::Mul)
507         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
508           return I->getOperand(0);
509       if (I->getOpcode() == Instruction::Shl)
510         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
511           // The multiplier is really 1 << CST.
512           Constant *One = ConstantInt::get(V->getType(), 1);
513           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
514           return I->getOperand(0);
515         }
516     }
517   return 0;
518 }
519
520 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
521 /// expression, return it.
522 static User *dyn_castGetElementPtr(Value *V) {
523   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
524   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
525     if (CE->getOpcode() == Instruction::GetElementPtr)
526       return cast<User>(V);
527   return false;
528 }
529
530 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
531 static ConstantInt *AddOne(ConstantInt *C) {
532   return cast<ConstantInt>(ConstantExpr::getAdd(C,
533                                          ConstantInt::get(C->getType(), 1)));
534 }
535 static ConstantInt *SubOne(ConstantInt *C) {
536   return cast<ConstantInt>(ConstantExpr::getSub(C,
537                                          ConstantInt::get(C->getType(), 1)));
538 }
539
540 /// GetConstantInType - Return a ConstantInt with the specified type and value.
541 ///
542 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
543   if (Ty->isUnsigned()) 
544     return ConstantInt::get(Ty, Val);
545   else if (Ty->getTypeID() == Type::BoolTyID)
546     return ConstantBool::get(Val);
547   int64_t SVal = Val;
548   SVal <<= 64-Ty->getPrimitiveSizeInBits();
549   SVal >>= 64-Ty->getPrimitiveSizeInBits();
550   return ConstantInt::get(Ty, SVal);
551 }
552
553
554 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
555 /// known to be either zero or one and return them in the KnownZero/KnownOne
556 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
557 /// processing.
558 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
559                               uint64_t &KnownOne, unsigned Depth = 0) {
560   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
561   // we cannot optimize based on the assumption that it is zero without changing
562   // it to be an explicit zero.  If we don't change it to zero, other code could
563   // optimized based on the contradictory assumption that it is non-zero.
564   // Because instcombine aggressively folds operations with undef args anyway,
565   // this won't lose us code quality.
566   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
567     // We know all of the bits for a constant!
568     KnownOne = CI->getZExtValue() & Mask;
569     KnownZero = ~KnownOne & Mask;
570     return;
571   }
572
573   KnownZero = KnownOne = 0;   // Don't know anything.
574   if (Depth == 6 || Mask == 0)
575     return;  // Limit search depth.
576
577   uint64_t KnownZero2, KnownOne2;
578   Instruction *I = dyn_cast<Instruction>(V);
579   if (!I) return;
580
581   Mask &= V->getType()->getIntegralTypeMask();
582   
583   switch (I->getOpcode()) {
584   case Instruction::And:
585     // If either the LHS or the RHS are Zero, the result is zero.
586     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
587     Mask &= ~KnownZero;
588     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
589     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
590     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
591     
592     // Output known-1 bits are only known if set in both the LHS & RHS.
593     KnownOne &= KnownOne2;
594     // Output known-0 are known to be clear if zero in either the LHS | RHS.
595     KnownZero |= KnownZero2;
596     return;
597   case Instruction::Or:
598     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
599     Mask &= ~KnownOne;
600     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
601     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
602     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
603     
604     // Output known-0 bits are only known if clear in both the LHS & RHS.
605     KnownZero &= KnownZero2;
606     // Output known-1 are known to be set if set in either the LHS | RHS.
607     KnownOne |= KnownOne2;
608     return;
609   case Instruction::Xor: {
610     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
611     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
612     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
613     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
614     
615     // Output known-0 bits are known if clear or set in both the LHS & RHS.
616     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
617     // Output known-1 are known to be set if set in only one of the LHS, RHS.
618     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
619     KnownZero = KnownZeroOut;
620     return;
621   }
622   case Instruction::Select:
623     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
624     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
625     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
626     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
627
628     // Only known if known in both the LHS and RHS.
629     KnownOne &= KnownOne2;
630     KnownZero &= KnownZero2;
631     return;
632   case Instruction::FPTrunc:
633   case Instruction::FPExt:
634   case Instruction::FPToUI:
635   case Instruction::FPToSI:
636   case Instruction::SIToFP:
637   case Instruction::PtrToInt:
638   case Instruction::UIToFP:
639   case Instruction::IntToPtr:
640     return; // Can't work with floating point or pointers
641   case Instruction::Trunc: 
642     // All these have integer operands
643     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
644     return;
645   case Instruction::BitCast: {
646     const Type *SrcTy = I->getOperand(0)->getType();
647     if (SrcTy->isIntegral()) {
648       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
649       return;
650     }
651     break;
652   }
653   case Instruction::ZExt:  {
654     // Compute the bits in the result that are not present in the input.
655     const Type *SrcTy = I->getOperand(0)->getType();
656     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
657     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
658       
659     Mask &= SrcTy->getIntegralTypeMask();
660     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
661     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
662     // The top bits are known to be zero.
663     KnownZero |= NewBits;
664     return;
665   }
666   case Instruction::SExt: {
667     // Compute the bits in the result that are not present in the input.
668     const Type *SrcTy = I->getOperand(0)->getType();
669     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
670     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
671       
672     Mask &= SrcTy->getIntegralTypeMask();
673     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
674     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
675
676     // If the sign bit of the input is known set or clear, then we know the
677     // top bits of the result.
678     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
679     if (KnownZero & InSignBit) {          // Input sign bit known zero
680       KnownZero |= NewBits;
681       KnownOne &= ~NewBits;
682     } else if (KnownOne & InSignBit) {    // Input sign bit known set
683       KnownOne |= NewBits;
684       KnownZero &= ~NewBits;
685     } else {                              // Input sign bit unknown
686       KnownZero &= ~NewBits;
687       KnownOne &= ~NewBits;
688     }
689     return;
690   }
691   case Instruction::Shl:
692     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
693     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
694       uint64_t ShiftAmt = SA->getZExtValue();
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 |= (1ULL << ShiftAmt)-1;  // low bits known zero.
701       return;
702     }
703     break;
704   case Instruction::LShr:
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       // Unsigned 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       KnownZero |= HighBits;  // high bits known zero.
719       return;
720     }
721     break;
722   case Instruction::AShr:
723     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
724     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
725       // Compute the new bits that are at the top now.
726       uint64_t ShiftAmt = SA->getZExtValue();
727       uint64_t HighBits = (1ULL << ShiftAmt)-1;
728       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
729       
730       // Signed shift right.
731       Mask <<= ShiftAmt;
732       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
733       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
734       KnownZero >>= ShiftAmt;
735       KnownOne  >>= ShiftAmt;
736         
737       // Handle the sign bits.
738       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
739       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
740         
741       if (KnownZero & SignBit) {       // New bits are known zero.
742         KnownZero |= HighBits;
743       } else if (KnownOne & SignBit) { // New bits are known one.
744         KnownOne |= HighBits;
745       }
746       return;
747     }
748     break;
749   }
750 }
751
752 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
753 /// this predicate to simplify operations downstream.  Mask is known to be zero
754 /// for bits that V cannot have.
755 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
756   uint64_t KnownZero, KnownOne;
757   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
758   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
759   return (KnownZero & Mask) == Mask;
760 }
761
762 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
763 /// specified instruction is a constant integer.  If so, check to see if there
764 /// are any bits set in the constant that are not demanded.  If so, shrink the
765 /// constant and return true.
766 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
767                                    uint64_t Demanded) {
768   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
769   if (!OpC) return false;
770
771   // If there are no bits set that aren't demanded, nothing to do.
772   if ((~Demanded & OpC->getZExtValue()) == 0)
773     return false;
774
775   // This is producing any bits that are not needed, shrink the RHS.
776   uint64_t Val = Demanded & OpC->getZExtValue();
777   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
778   return true;
779 }
780
781 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
782 // set of known zero and one bits, compute the maximum and minimum values that
783 // could have the specified known zero and known one bits, returning them in
784 // min/max.
785 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
786                                                    uint64_t KnownZero,
787                                                    uint64_t KnownOne,
788                                                    int64_t &Min, int64_t &Max) {
789   uint64_t TypeBits = Ty->getIntegralTypeMask();
790   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
791
792   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
793   
794   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
795   // bit if it is unknown.
796   Min = KnownOne;
797   Max = KnownOne|UnknownBits;
798   
799   if (SignBit & UnknownBits) { // Sign bit is unknown
800     Min |= SignBit;
801     Max &= ~SignBit;
802   }
803   
804   // Sign extend the min/max values.
805   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
806   Min = (Min << ShAmt) >> ShAmt;
807   Max = (Max << ShAmt) >> ShAmt;
808 }
809
810 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
811 // a set of known zero and one bits, compute the maximum and minimum values that
812 // could have the specified known zero and known one bits, returning them in
813 // min/max.
814 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
815                                                      uint64_t KnownZero,
816                                                      uint64_t KnownOne,
817                                                      uint64_t &Min,
818                                                      uint64_t &Max) {
819   uint64_t TypeBits = Ty->getIntegralTypeMask();
820   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
821   
822   // The minimum value is when the unknown bits are all zeros.
823   Min = KnownOne;
824   // The maximum value is when the unknown bits are all ones.
825   Max = KnownOne|UnknownBits;
826 }
827
828
829 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
830 /// DemandedMask bits of the result of V are ever used downstream.  If we can
831 /// use this information to simplify V, do so and return true.  Otherwise,
832 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
833 /// the expression (used to simplify the caller).  The KnownZero/One bits may
834 /// only be accurate for those bits in the DemandedMask.
835 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
836                                         uint64_t &KnownZero, uint64_t &KnownOne,
837                                         unsigned Depth) {
838   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
839     // We know all of the bits for a constant!
840     KnownOne = CI->getZExtValue() & DemandedMask;
841     KnownZero = ~KnownOne & DemandedMask;
842     return false;
843   }
844   
845   KnownZero = KnownOne = 0;
846   if (!V->hasOneUse()) {    // Other users may use these bits.
847     if (Depth != 0) {       // Not at the root.
848       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
849       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
850       return false;
851     }
852     // If this is the root being simplified, allow it to have multiple uses,
853     // just set the DemandedMask to all bits.
854     DemandedMask = V->getType()->getIntegralTypeMask();
855   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
856     if (V != UndefValue::get(V->getType()))
857       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
858     return false;
859   } else if (Depth == 6) {        // Limit search depth.
860     return false;
861   }
862   
863   Instruction *I = dyn_cast<Instruction>(V);
864   if (!I) return false;        // Only analyze instructions.
865
866   DemandedMask &= V->getType()->getIntegralTypeMask();
867   
868   uint64_t KnownZero2 = 0, KnownOne2 = 0;
869   switch (I->getOpcode()) {
870   default: break;
871   case Instruction::And:
872     // If either the LHS or the RHS are Zero, the result is zero.
873     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
874                              KnownZero, KnownOne, Depth+1))
875       return true;
876     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
877
878     // If something is known zero on the RHS, the bits aren't demanded on the
879     // LHS.
880     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
881                              KnownZero2, KnownOne2, Depth+1))
882       return true;
883     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
884
885     // If all of the demanded bits are known 1 on one side, return the other.
886     // These bits cannot contribute to the result of the 'and'.
887     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
888       return UpdateValueUsesWith(I, I->getOperand(0));
889     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
890       return UpdateValueUsesWith(I, I->getOperand(1));
891     
892     // If all of the demanded bits in the inputs are known zeros, return zero.
893     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
894       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
895       
896     // If the RHS is a constant, see if we can simplify it.
897     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
898       return UpdateValueUsesWith(I, I);
899       
900     // Output known-1 bits are only known if set in both the LHS & RHS.
901     KnownOne &= KnownOne2;
902     // Output known-0 are known to be clear if zero in either the LHS | RHS.
903     KnownZero |= KnownZero2;
904     break;
905   case Instruction::Or:
906     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
907                              KnownZero, KnownOne, Depth+1))
908       return true;
909     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
910     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
911                              KnownZero2, KnownOne2, Depth+1))
912       return true;
913     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
914     
915     // If all of the demanded bits are known zero on one side, return the other.
916     // These bits cannot contribute to the result of the 'or'.
917     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
918       return UpdateValueUsesWith(I, I->getOperand(0));
919     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
920       return UpdateValueUsesWith(I, I->getOperand(1));
921
922     // If all of the potentially set bits on one side are known to be set on
923     // the other side, just use the 'other' side.
924     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
925         (DemandedMask & (~KnownZero)))
926       return UpdateValueUsesWith(I, I->getOperand(0));
927     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
928         (DemandedMask & (~KnownZero2)))
929       return UpdateValueUsesWith(I, I->getOperand(1));
930         
931     // If the RHS is a constant, see if we can simplify it.
932     if (ShrinkDemandedConstant(I, 1, DemandedMask))
933       return UpdateValueUsesWith(I, I);
934           
935     // Output known-0 bits are only known if clear in both the LHS & RHS.
936     KnownZero &= KnownZero2;
937     // Output known-1 are known to be set if set in either the LHS | RHS.
938     KnownOne |= KnownOne2;
939     break;
940   case Instruction::Xor: {
941     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
942                              KnownZero, KnownOne, Depth+1))
943       return true;
944     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
945     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
946                              KnownZero2, KnownOne2, Depth+1))
947       return true;
948     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
949     
950     // If all of the demanded bits are known zero on one side, return the other.
951     // These bits cannot contribute to the result of the 'xor'.
952     if ((DemandedMask & KnownZero) == DemandedMask)
953       return UpdateValueUsesWith(I, I->getOperand(0));
954     if ((DemandedMask & KnownZero2) == DemandedMask)
955       return UpdateValueUsesWith(I, I->getOperand(1));
956     
957     // Output known-0 bits are known if clear or set in both the LHS & RHS.
958     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
959     // Output known-1 are known to be set if set in only one of the LHS, RHS.
960     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
961     
962     // If all of the demanded bits are known to be zero on one side or the
963     // other, turn this into an *inclusive* or.
964     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
965     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
966       Instruction *Or =
967         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
968                                  I->getName());
969       InsertNewInstBefore(Or, *I);
970       return UpdateValueUsesWith(I, Or);
971     }
972     
973     // If all of the demanded bits on one side are known, and all of the set
974     // bits on that side are also known to be set on the other side, turn this
975     // into an AND, as we know the bits will be cleared.
976     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
977     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
978       if ((KnownOne & KnownOne2) == KnownOne) {
979         Constant *AndC = GetConstantInType(I->getType(), 
980                                            ~KnownOne & DemandedMask);
981         Instruction *And = 
982           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
983         InsertNewInstBefore(And, *I);
984         return UpdateValueUsesWith(I, And);
985       }
986     }
987     
988     // If the RHS is a constant, see if we can simplify it.
989     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
990     if (ShrinkDemandedConstant(I, 1, DemandedMask))
991       return UpdateValueUsesWith(I, I);
992     
993     KnownZero = KnownZeroOut;
994     KnownOne  = KnownOneOut;
995     break;
996   }
997   case Instruction::Select:
998     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
999                              KnownZero, KnownOne, Depth+1))
1000       return true;
1001     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1002                              KnownZero2, KnownOne2, Depth+1))
1003       return true;
1004     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1005     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1006     
1007     // If the operands are constants, see if we can simplify them.
1008     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1009       return UpdateValueUsesWith(I, I);
1010     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1011       return UpdateValueUsesWith(I, I);
1012     
1013     // Only known if known in both the LHS and RHS.
1014     KnownOne &= KnownOne2;
1015     KnownZero &= KnownZero2;
1016     break;
1017   case Instruction::Trunc:
1018     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1019                              KnownZero, KnownOne, Depth+1))
1020       return true;
1021     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1022     break;
1023   case Instruction::BitCast:
1024     if (!I->getOperand(0)->getType()->isIntegral())
1025       return false;
1026       
1027     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1028                              KnownZero, KnownOne, Depth+1))
1029       return true;
1030     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1031     break;
1032   case Instruction::ZExt: {
1033     // Compute the bits in the result that are not present in the input.
1034     const Type *SrcTy = I->getOperand(0)->getType();
1035     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1036     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1037     
1038     DemandedMask &= SrcTy->getIntegralTypeMask();
1039     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1040                              KnownZero, KnownOne, Depth+1))
1041       return true;
1042     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1043     // The top bits are known to be zero.
1044     KnownZero |= NewBits;
1045     break;
1046   }
1047   case Instruction::SExt: {
1048     // Compute the bits in the result that are not present in the input.
1049     const Type *SrcTy = I->getOperand(0)->getType();
1050     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1051     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1052     
1053     // Get the sign bit for the source type
1054     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1055     int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1056
1057     // If any of the sign extended bits are demanded, we know that the sign
1058     // bit is demanded.
1059     if (NewBits & DemandedMask)
1060       InputDemandedBits |= InSignBit;
1061       
1062     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1063                              KnownZero, KnownOne, Depth+1))
1064       return true;
1065     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1066       
1067     // If the sign bit of the input is known set or clear, then we know the
1068     // top bits of the result.
1069
1070     // If the input sign bit is known zero, or if the NewBits are not demanded
1071     // convert this into a zero extension.
1072     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1073       // Convert to ZExt cast
1074       CastInst *NewCast = CastInst::create(
1075         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1076       return UpdateValueUsesWith(I, NewCast);
1077     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1078       KnownOne |= NewBits;
1079       KnownZero &= ~NewBits;
1080     } else {                              // Input sign bit unknown
1081       KnownZero &= ~NewBits;
1082       KnownOne &= ~NewBits;
1083     }
1084     break;
1085   }
1086   case Instruction::Add:
1087     // If there is a constant on the RHS, there are a variety of xformations
1088     // we can do.
1089     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1090       // If null, this should be simplified elsewhere.  Some of the xforms here
1091       // won't work if the RHS is zero.
1092       if (RHS->isNullValue())
1093         break;
1094       
1095       // Figure out what the input bits are.  If the top bits of the and result
1096       // are not demanded, then the add doesn't demand them from its input
1097       // either.
1098       
1099       // Shift the demanded mask up so that it's at the top of the uint64_t.
1100       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1101       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1102       
1103       // If the top bit of the output is demanded, demand everything from the
1104       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1105       uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1106
1107       // Find information about known zero/one bits in the input.
1108       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1109                                KnownZero2, KnownOne2, Depth+1))
1110         return true;
1111
1112       // If the RHS of the add has bits set that can't affect the input, reduce
1113       // the constant.
1114       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1115         return UpdateValueUsesWith(I, I);
1116       
1117       // Avoid excess work.
1118       if (KnownZero2 == 0 && KnownOne2 == 0)
1119         break;
1120       
1121       // Turn it into OR if input bits are zero.
1122       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1123         Instruction *Or =
1124           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1125                                    I->getName());
1126         InsertNewInstBefore(Or, *I);
1127         return UpdateValueUsesWith(I, Or);
1128       }
1129       
1130       // We can say something about the output known-zero and known-one bits,
1131       // depending on potential carries from the input constant and the
1132       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1133       // bits set and the RHS constant is 0x01001, then we know we have a known
1134       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1135       
1136       // To compute this, we first compute the potential carry bits.  These are
1137       // the bits which may be modified.  I'm not aware of a better way to do
1138       // this scan.
1139       uint64_t RHSVal = RHS->getZExtValue();
1140       
1141       bool CarryIn = false;
1142       uint64_t CarryBits = 0;
1143       uint64_t CurBit = 1;
1144       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1145         // Record the current carry in.
1146         if (CarryIn) CarryBits |= CurBit;
1147         
1148         bool CarryOut;
1149         
1150         // This bit has a carry out unless it is "zero + zero" or
1151         // "zero + anything" with no carry in.
1152         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1153           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1154         } else if (!CarryIn &&
1155                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1156           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1157         } else {
1158           // Otherwise, we have to assume we have a carry out.
1159           CarryOut = true;
1160         }
1161         
1162         // This stage's carry out becomes the next stage's carry-in.
1163         CarryIn = CarryOut;
1164       }
1165       
1166       // Now that we know which bits have carries, compute the known-1/0 sets.
1167       
1168       // Bits are known one if they are known zero in one operand and one in the
1169       // other, and there is no input carry.
1170       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1171       
1172       // Bits are known zero if they are known zero in both operands and there
1173       // is no input carry.
1174       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1175     }
1176     break;
1177   case Instruction::Shl:
1178     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179       uint64_t ShiftAmt = SA->getZExtValue();
1180       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1181                                KnownZero, KnownOne, Depth+1))
1182         return true;
1183       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1184       KnownZero <<= ShiftAmt;
1185       KnownOne  <<= ShiftAmt;
1186       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1187     }
1188     break;
1189   case Instruction::LShr:
1190     // For a logical shift right
1191     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1192       unsigned ShiftAmt = SA->getZExtValue();
1193       
1194       // Compute the new bits that are at the top now.
1195       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1196       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1197       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1198       // Unsigned shift right.
1199       if (SimplifyDemandedBits(I->getOperand(0),
1200                               (DemandedMask << ShiftAmt) & TypeMask,
1201                                KnownZero, KnownOne, Depth+1))
1202         return true;
1203       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1204       KnownZero &= TypeMask;
1205       KnownOne  &= TypeMask;
1206       KnownZero >>= ShiftAmt;
1207       KnownOne  >>= ShiftAmt;
1208       KnownZero |= HighBits;  // high bits known zero.
1209     }
1210     break;
1211   case Instruction::AShr:
1212     // If this is an arithmetic shift right and only the low-bit is set, we can
1213     // always convert this into a logical shr, even if the shift amount is
1214     // variable.  The low bit of the shift cannot be an input sign bit unless
1215     // the shift amount is >= the size of the datatype, which is undefined.
1216     if (DemandedMask == 1) {
1217       // Perform the logical shift right.
1218       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1219                                     I->getOperand(1), I->getName());
1220       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1221       return UpdateValueUsesWith(I, NewVal);
1222     }    
1223     
1224     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225       unsigned ShiftAmt = SA->getZExtValue();
1226       
1227       // Compute the new bits that are at the top now.
1228       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1229       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1230       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1231       // Signed shift right.
1232       if (SimplifyDemandedBits(I->getOperand(0),
1233                                (DemandedMask << ShiftAmt) & TypeMask,
1234                                KnownZero, KnownOne, Depth+1))
1235         return true;
1236       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1237       KnownZero &= TypeMask;
1238       KnownOne  &= TypeMask;
1239       KnownZero >>= ShiftAmt;
1240       KnownOne  >>= ShiftAmt;
1241         
1242       // Handle the sign bits.
1243       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1244       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1245         
1246       // If the input sign bit is known to be zero, or if none of the top bits
1247       // are demanded, turn this into an unsigned shift right.
1248       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1249         // Perform the logical shift right.
1250         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1251                                       SA, I->getName());
1252         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1253         return UpdateValueUsesWith(I, NewVal);
1254       } else if (KnownOne & SignBit) { // New bits are known one.
1255         KnownOne |= HighBits;
1256       }
1257     }
1258     break;
1259   }
1260   
1261   // If the client is only demanding bits that we know, return the known
1262   // constant.
1263   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1264     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1265   return false;
1266 }  
1267
1268
1269 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1270 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1271 /// actually used by the caller.  This method analyzes which elements of the
1272 /// operand are undef and returns that information in UndefElts.
1273 ///
1274 /// If the information about demanded elements can be used to simplify the
1275 /// operation, the operation is simplified, then the resultant value is
1276 /// returned.  This returns null if no change was made.
1277 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1278                                                 uint64_t &UndefElts,
1279                                                 unsigned Depth) {
1280   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1281   assert(VWidth <= 64 && "Vector too wide to analyze!");
1282   uint64_t EltMask = ~0ULL >> (64-VWidth);
1283   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1284          "Invalid DemandedElts!");
1285
1286   if (isa<UndefValue>(V)) {
1287     // If the entire vector is undefined, just return this info.
1288     UndefElts = EltMask;
1289     return 0;
1290   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1291     UndefElts = EltMask;
1292     return UndefValue::get(V->getType());
1293   }
1294   
1295   UndefElts = 0;
1296   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1297     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1298     Constant *Undef = UndefValue::get(EltTy);
1299
1300     std::vector<Constant*> Elts;
1301     for (unsigned i = 0; i != VWidth; ++i)
1302       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1303         Elts.push_back(Undef);
1304         UndefElts |= (1ULL << i);
1305       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1306         Elts.push_back(Undef);
1307         UndefElts |= (1ULL << i);
1308       } else {                               // Otherwise, defined.
1309         Elts.push_back(CP->getOperand(i));
1310       }
1311         
1312     // If we changed the constant, return it.
1313     Constant *NewCP = ConstantPacked::get(Elts);
1314     return NewCP != CP ? NewCP : 0;
1315   } else if (isa<ConstantAggregateZero>(V)) {
1316     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1317     // set to undef.
1318     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1319     Constant *Zero = Constant::getNullValue(EltTy);
1320     Constant *Undef = UndefValue::get(EltTy);
1321     std::vector<Constant*> Elts;
1322     for (unsigned i = 0; i != VWidth; ++i)
1323       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1324     UndefElts = DemandedElts ^ EltMask;
1325     return ConstantPacked::get(Elts);
1326   }
1327   
1328   if (!V->hasOneUse()) {    // Other users may use these bits.
1329     if (Depth != 0) {       // Not at the root.
1330       // TODO: Just compute the UndefElts information recursively.
1331       return false;
1332     }
1333     return false;
1334   } else if (Depth == 10) {        // Limit search depth.
1335     return false;
1336   }
1337   
1338   Instruction *I = dyn_cast<Instruction>(V);
1339   if (!I) return false;        // Only analyze instructions.
1340   
1341   bool MadeChange = false;
1342   uint64_t UndefElts2;
1343   Value *TmpV;
1344   switch (I->getOpcode()) {
1345   default: break;
1346     
1347   case Instruction::InsertElement: {
1348     // If this is a variable index, we don't know which element it overwrites.
1349     // demand exactly the same input as we produce.
1350     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1351     if (Idx == 0) {
1352       // Note that we can't propagate undef elt info, because we don't know
1353       // which elt is getting updated.
1354       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1355                                         UndefElts2, Depth+1);
1356       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1357       break;
1358     }
1359     
1360     // If this is inserting an element that isn't demanded, remove this
1361     // insertelement.
1362     unsigned IdxNo = Idx->getZExtValue();
1363     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1364       return AddSoonDeadInstToWorklist(*I, 0);
1365     
1366     // Otherwise, the element inserted overwrites whatever was there, so the
1367     // input demanded set is simpler than the output set.
1368     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1369                                       DemandedElts & ~(1ULL << IdxNo),
1370                                       UndefElts, Depth+1);
1371     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1372
1373     // The inserted element is defined.
1374     UndefElts |= 1ULL << IdxNo;
1375     break;
1376   }
1377     
1378   case Instruction::And:
1379   case Instruction::Or:
1380   case Instruction::Xor:
1381   case Instruction::Add:
1382   case Instruction::Sub:
1383   case Instruction::Mul:
1384     // div/rem demand all inputs, because they don't want divide by zero.
1385     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1386                                       UndefElts, Depth+1);
1387     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1388     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1389                                       UndefElts2, Depth+1);
1390     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1391       
1392     // Output elements are undefined if both are undefined.  Consider things
1393     // like undef&0.  The result is known zero, not undef.
1394     UndefElts &= UndefElts2;
1395     break;
1396     
1397   case Instruction::Call: {
1398     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1399     if (!II) break;
1400     switch (II->getIntrinsicID()) {
1401     default: break;
1402       
1403     // Binary vector operations that work column-wise.  A dest element is a
1404     // function of the corresponding input elements from the two inputs.
1405     case Intrinsic::x86_sse_sub_ss:
1406     case Intrinsic::x86_sse_mul_ss:
1407     case Intrinsic::x86_sse_min_ss:
1408     case Intrinsic::x86_sse_max_ss:
1409     case Intrinsic::x86_sse2_sub_sd:
1410     case Intrinsic::x86_sse2_mul_sd:
1411     case Intrinsic::x86_sse2_min_sd:
1412     case Intrinsic::x86_sse2_max_sd:
1413       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1414                                         UndefElts, Depth+1);
1415       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1416       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1417                                         UndefElts2, Depth+1);
1418       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1419
1420       // If only the low elt is demanded and this is a scalarizable intrinsic,
1421       // scalarize it now.
1422       if (DemandedElts == 1) {
1423         switch (II->getIntrinsicID()) {
1424         default: break;
1425         case Intrinsic::x86_sse_sub_ss:
1426         case Intrinsic::x86_sse_mul_ss:
1427         case Intrinsic::x86_sse2_sub_sd:
1428         case Intrinsic::x86_sse2_mul_sd:
1429           // TODO: Lower MIN/MAX/ABS/etc
1430           Value *LHS = II->getOperand(1);
1431           Value *RHS = II->getOperand(2);
1432           // Extract the element as scalars.
1433           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1434           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1435           
1436           switch (II->getIntrinsicID()) {
1437           default: assert(0 && "Case stmts out of sync!");
1438           case Intrinsic::x86_sse_sub_ss:
1439           case Intrinsic::x86_sse2_sub_sd:
1440             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1441                                                         II->getName()), *II);
1442             break;
1443           case Intrinsic::x86_sse_mul_ss:
1444           case Intrinsic::x86_sse2_mul_sd:
1445             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1446                                                          II->getName()), *II);
1447             break;
1448           }
1449           
1450           Instruction *New =
1451             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1452                                   II->getName());
1453           InsertNewInstBefore(New, *II);
1454           AddSoonDeadInstToWorklist(*II, 0);
1455           return New;
1456         }            
1457       }
1458         
1459       // Output elements are undefined if both are undefined.  Consider things
1460       // like undef&0.  The result is known zero, not undef.
1461       UndefElts &= UndefElts2;
1462       break;
1463     }
1464     break;
1465   }
1466   }
1467   return MadeChange ? I : 0;
1468 }
1469
1470 /// @returns true if the specified compare instruction is
1471 /// true when both operands are equal...
1472 /// @brief Determine if the ICmpInst returns true if both operands are equal
1473 static bool isTrueWhenEqual(ICmpInst &ICI) {
1474   ICmpInst::Predicate pred = ICI.getPredicate();
1475   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1476          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1477          pred == ICmpInst::ICMP_SLE;
1478 }
1479
1480 /// @returns true if the specified compare instruction is
1481 /// true when both operands are equal...
1482 /// @brief Determine if the FCmpInst returns true if both operands are equal
1483 static bool isTrueWhenEqual(FCmpInst &FCI) {
1484   FCmpInst::Predicate pred = FCI.getPredicate();
1485   return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1486          pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1487          pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
1488 }
1489
1490 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1491 /// function is designed to check a chain of associative operators for a
1492 /// potential to apply a certain optimization.  Since the optimization may be
1493 /// applicable if the expression was reassociated, this checks the chain, then
1494 /// reassociates the expression as necessary to expose the optimization
1495 /// opportunity.  This makes use of a special Functor, which must define
1496 /// 'shouldApply' and 'apply' methods.
1497 ///
1498 template<typename Functor>
1499 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1500   unsigned Opcode = Root.getOpcode();
1501   Value *LHS = Root.getOperand(0);
1502
1503   // Quick check, see if the immediate LHS matches...
1504   if (F.shouldApply(LHS))
1505     return F.apply(Root);
1506
1507   // Otherwise, if the LHS is not of the same opcode as the root, return.
1508   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1509   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1510     // Should we apply this transform to the RHS?
1511     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1512
1513     // If not to the RHS, check to see if we should apply to the LHS...
1514     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1515       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1516       ShouldApply = true;
1517     }
1518
1519     // If the functor wants to apply the optimization to the RHS of LHSI,
1520     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1521     if (ShouldApply) {
1522       BasicBlock *BB = Root.getParent();
1523
1524       // Now all of the instructions are in the current basic block, go ahead
1525       // and perform the reassociation.
1526       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1527
1528       // First move the selected RHS to the LHS of the root...
1529       Root.setOperand(0, LHSI->getOperand(1));
1530
1531       // Make what used to be the LHS of the root be the user of the root...
1532       Value *ExtraOperand = TmpLHSI->getOperand(1);
1533       if (&Root == TmpLHSI) {
1534         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1535         return 0;
1536       }
1537       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1538       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1539       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1540       BasicBlock::iterator ARI = &Root; ++ARI;
1541       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1542       ARI = Root;
1543
1544       // Now propagate the ExtraOperand down the chain of instructions until we
1545       // get to LHSI.
1546       while (TmpLHSI != LHSI) {
1547         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1548         // Move the instruction to immediately before the chain we are
1549         // constructing to avoid breaking dominance properties.
1550         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1551         BB->getInstList().insert(ARI, NextLHSI);
1552         ARI = NextLHSI;
1553
1554         Value *NextOp = NextLHSI->getOperand(1);
1555         NextLHSI->setOperand(1, ExtraOperand);
1556         TmpLHSI = NextLHSI;
1557         ExtraOperand = NextOp;
1558       }
1559
1560       // Now that the instructions are reassociated, have the functor perform
1561       // the transformation...
1562       return F.apply(Root);
1563     }
1564
1565     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1566   }
1567   return 0;
1568 }
1569
1570
1571 // AddRHS - Implements: X + X --> X << 1
1572 struct AddRHS {
1573   Value *RHS;
1574   AddRHS(Value *rhs) : RHS(rhs) {}
1575   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1576   Instruction *apply(BinaryOperator &Add) const {
1577     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1578                          ConstantInt::get(Type::UByteTy, 1));
1579   }
1580 };
1581
1582 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1583 //                 iff C1&C2 == 0
1584 struct AddMaskingAnd {
1585   Constant *C2;
1586   AddMaskingAnd(Constant *c) : C2(c) {}
1587   bool shouldApply(Value *LHS) const {
1588     ConstantInt *C1;
1589     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1590            ConstantExpr::getAnd(C1, C2)->isNullValue();
1591   }
1592   Instruction *apply(BinaryOperator &Add) const {
1593     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1594   }
1595 };
1596
1597 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1598                                              InstCombiner *IC) {
1599   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1600     if (Constant *SOC = dyn_cast<Constant>(SO))
1601       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1602
1603     return IC->InsertNewInstBefore(CastInst::create(
1604           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1605   }
1606
1607   // Figure out if the constant is the left or the right argument.
1608   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1609   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1610
1611   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1612     if (ConstIsRHS)
1613       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1614     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1615   }
1616
1617   Value *Op0 = SO, *Op1 = ConstOperand;
1618   if (!ConstIsRHS)
1619     std::swap(Op0, Op1);
1620   Instruction *New;
1621   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1622     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1623   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1624     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1625                           SO->getName()+".cmp");
1626   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1627     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1628   else {
1629     assert(0 && "Unknown binary instruction type!");
1630     abort();
1631   }
1632   return IC->InsertNewInstBefore(New, I);
1633 }
1634
1635 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1636 // constant as the other operand, try to fold the binary operator into the
1637 // select arguments.  This also works for Cast instructions, which obviously do
1638 // not have a second operand.
1639 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1640                                      InstCombiner *IC) {
1641   // Don't modify shared select instructions
1642   if (!SI->hasOneUse()) return 0;
1643   Value *TV = SI->getOperand(1);
1644   Value *FV = SI->getOperand(2);
1645
1646   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1647     // Bool selects with constant operands can be folded to logical ops.
1648     if (SI->getType() == Type::BoolTy) return 0;
1649
1650     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1651     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1652
1653     return new SelectInst(SI->getCondition(), SelectTrueVal,
1654                           SelectFalseVal);
1655   }
1656   return 0;
1657 }
1658
1659
1660 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1661 /// node as operand #0, see if we can fold the instruction into the PHI (which
1662 /// is only possible if all operands to the PHI are constants).
1663 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1664   PHINode *PN = cast<PHINode>(I.getOperand(0));
1665   unsigned NumPHIValues = PN->getNumIncomingValues();
1666   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1667
1668   // Check to see if all of the operands of the PHI are constants.  If there is
1669   // one non-constant value, remember the BB it is.  If there is more than one
1670   // bail out.
1671   BasicBlock *NonConstBB = 0;
1672   for (unsigned i = 0; i != NumPHIValues; ++i)
1673     if (!isa<Constant>(PN->getIncomingValue(i))) {
1674       if (NonConstBB) return 0;  // More than one non-const value.
1675       NonConstBB = PN->getIncomingBlock(i);
1676       
1677       // If the incoming non-constant value is in I's block, we have an infinite
1678       // loop.
1679       if (NonConstBB == I.getParent())
1680         return 0;
1681     }
1682   
1683   // If there is exactly one non-constant value, we can insert a copy of the
1684   // operation in that block.  However, if this is a critical edge, we would be
1685   // inserting the computation one some other paths (e.g. inside a loop).  Only
1686   // do this if the pred block is unconditionally branching into the phi block.
1687   if (NonConstBB) {
1688     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1689     if (!BI || !BI->isUnconditional()) return 0;
1690   }
1691
1692   // Okay, we can do the transformation: create the new PHI node.
1693   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1694   I.setName("");
1695   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1696   InsertNewInstBefore(NewPN, *PN);
1697
1698   // Next, add all of the operands to the PHI.
1699   if (I.getNumOperands() == 2) {
1700     Constant *C = cast<Constant>(I.getOperand(1));
1701     for (unsigned i = 0; i != NumPHIValues; ++i) {
1702       Value *InV;
1703       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1704         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1705           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1706         else
1707           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1708       } else {
1709         assert(PN->getIncomingBlock(i) == NonConstBB);
1710         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1711           InV = BinaryOperator::create(BO->getOpcode(),
1712                                        PN->getIncomingValue(i), C, "phitmp",
1713                                        NonConstBB->getTerminator());
1714         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1715           InV = CmpInst::create(CI->getOpcode(), 
1716                                 CI->getPredicate(),
1717                                 PN->getIncomingValue(i), C, "phitmp",
1718                                 NonConstBB->getTerminator());
1719         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1720           InV = new ShiftInst(SI->getOpcode(),
1721                               PN->getIncomingValue(i), C, "phitmp",
1722                               NonConstBB->getTerminator());
1723         else
1724           assert(0 && "Unknown binop!");
1725         
1726         WorkList.push_back(cast<Instruction>(InV));
1727       }
1728       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1729     }
1730   } else { 
1731     CastInst *CI = cast<CastInst>(&I);
1732     const Type *RetTy = CI->getType();
1733     for (unsigned i = 0; i != NumPHIValues; ++i) {
1734       Value *InV;
1735       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1736         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1737       } else {
1738         assert(PN->getIncomingBlock(i) == NonConstBB);
1739         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1740                                I.getType(), "phitmp", 
1741                                NonConstBB->getTerminator());
1742         WorkList.push_back(cast<Instruction>(InV));
1743       }
1744       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1745     }
1746   }
1747   return ReplaceInstUsesWith(I, NewPN);
1748 }
1749
1750 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1751   bool Changed = SimplifyCommutative(I);
1752   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1753
1754   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1755     // X + undef -> undef
1756     if (isa<UndefValue>(RHS))
1757       return ReplaceInstUsesWith(I, RHS);
1758
1759     // X + 0 --> X
1760     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1761       if (RHSC->isNullValue())
1762         return ReplaceInstUsesWith(I, LHS);
1763     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1764       if (CFP->isExactlyValue(-0.0))
1765         return ReplaceInstUsesWith(I, LHS);
1766     }
1767
1768     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1769       // X + (signbit) --> X ^ signbit
1770       uint64_t Val = CI->getZExtValue();
1771       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1772         return BinaryOperator::createXor(LHS, RHS);
1773       
1774       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1775       // (X & 254)+1 -> (X&254)|1
1776       uint64_t KnownZero, KnownOne;
1777       if (!isa<PackedType>(I.getType()) &&
1778           SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1779                                KnownZero, KnownOne))
1780         return &I;
1781     }
1782
1783     if (isa<PHINode>(LHS))
1784       if (Instruction *NV = FoldOpIntoPhi(I))
1785         return NV;
1786     
1787     ConstantInt *XorRHS = 0;
1788     Value *XorLHS = 0;
1789     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1790       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1791       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1792       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1793       
1794       uint64_t C0080Val = 1ULL << 31;
1795       int64_t CFF80Val = -C0080Val;
1796       unsigned Size = 32;
1797       do {
1798         if (TySizeBits > Size) {
1799           bool Found = false;
1800           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1801           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1802           if (RHSSExt == CFF80Val) {
1803             if (XorRHS->getZExtValue() == C0080Val)
1804               Found = true;
1805           } else if (RHSZExt == C0080Val) {
1806             if (XorRHS->getSExtValue() == CFF80Val)
1807               Found = true;
1808           }
1809           if (Found) {
1810             // This is a sign extend if the top bits are known zero.
1811             uint64_t Mask = ~0ULL;
1812             Mask <<= 64-(TySizeBits-Size);
1813             Mask &= XorLHS->getType()->getIntegralTypeMask();
1814             if (!MaskedValueIsZero(XorLHS, Mask))
1815               Size = 0;  // Not a sign ext, but can't be any others either.
1816             goto FoundSExt;
1817           }
1818         }
1819         Size >>= 1;
1820         C0080Val >>= Size;
1821         CFF80Val >>= Size;
1822       } while (Size >= 8);
1823       
1824 FoundSExt:
1825       const Type *MiddleType = 0;
1826       switch (Size) {
1827       default: break;
1828       case 32: MiddleType = Type::IntTy; break;
1829       case 16: MiddleType = Type::ShortTy; break;
1830       case 8:  MiddleType = Type::SByteTy; break;
1831       }
1832       if (MiddleType) {
1833         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1834         InsertNewInstBefore(NewTrunc, I);
1835         return new SExtInst(NewTrunc, I.getType());
1836       }
1837     }
1838   }
1839
1840   // X + X --> X << 1
1841   if (I.getType()->isInteger()) {
1842     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1843
1844     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1845       if (RHSI->getOpcode() == Instruction::Sub)
1846         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1847           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1848     }
1849     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1850       if (LHSI->getOpcode() == Instruction::Sub)
1851         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1852           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1853     }
1854   }
1855
1856   // -A + B  -->  B - A
1857   if (Value *V = dyn_castNegVal(LHS))
1858     return BinaryOperator::createSub(RHS, V);
1859
1860   // A + -B  -->  A - B
1861   if (!isa<Constant>(RHS))
1862     if (Value *V = dyn_castNegVal(RHS))
1863       return BinaryOperator::createSub(LHS, V);
1864
1865
1866   ConstantInt *C2;
1867   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1868     if (X == RHS)   // X*C + X --> X * (C+1)
1869       return BinaryOperator::createMul(RHS, AddOne(C2));
1870
1871     // X*C1 + X*C2 --> X * (C1+C2)
1872     ConstantInt *C1;
1873     if (X == dyn_castFoldableMul(RHS, C1))
1874       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1875   }
1876
1877   // X + X*C --> X * (C+1)
1878   if (dyn_castFoldableMul(RHS, C2) == LHS)
1879     return BinaryOperator::createMul(LHS, AddOne(C2));
1880
1881
1882   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1883   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1884     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1885
1886   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1887     Value *X = 0;
1888     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1889       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1890       return BinaryOperator::createSub(C, X);
1891     }
1892
1893     // (X & FF00) + xx00  -> (X+xx00) & FF00
1894     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1895       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1896       if (Anded == CRHS) {
1897         // See if all bits from the first bit set in the Add RHS up are included
1898         // in the mask.  First, get the rightmost bit.
1899         uint64_t AddRHSV = CRHS->getZExtValue();
1900
1901         // Form a mask of all bits from the lowest bit added through the top.
1902         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1903         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1904
1905         // See if the and mask includes all of these bits.
1906         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1907
1908         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1909           // Okay, the xform is safe.  Insert the new add pronto.
1910           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1911                                                             LHS->getName()), I);
1912           return BinaryOperator::createAnd(NewAdd, C2);
1913         }
1914       }
1915     }
1916
1917     // Try to fold constant add into select arguments.
1918     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1919       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1920         return R;
1921   }
1922
1923   // add (cast *A to intptrtype) B -> 
1924   //   cast (GEP (cast *A to sbyte*) B) -> 
1925   //     intptrtype
1926   {
1927     CastInst *CI = dyn_cast<CastInst>(LHS);
1928     Value *Other = RHS;
1929     if (!CI) {
1930       CI = dyn_cast<CastInst>(RHS);
1931       Other = LHS;
1932     }
1933     if (CI && CI->getType()->isSized() && 
1934         (CI->getType()->getPrimitiveSize() == 
1935          TD->getIntPtrType()->getPrimitiveSize()) 
1936         && isa<PointerType>(CI->getOperand(0)->getType())) {
1937       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1938                                    PointerType::get(Type::SByteTy), I);
1939       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1940       return new PtrToIntInst(I2, CI->getType());
1941     }
1942   }
1943
1944   return Changed ? &I : 0;
1945 }
1946
1947 // isSignBit - Return true if the value represented by the constant only has the
1948 // highest order bit set.
1949 static bool isSignBit(ConstantInt *CI) {
1950   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1951   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1952 }
1953
1954 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1955 ///
1956 static Value *RemoveNoopCast(Value *V) {
1957   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1958     const Type *CTy = CI->getType();
1959     const Type *OpTy = CI->getOperand(0)->getType();
1960     if (CTy->isInteger() && OpTy->isInteger()) {
1961       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1962         return RemoveNoopCast(CI->getOperand(0));
1963     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1964       return RemoveNoopCast(CI->getOperand(0));
1965   }
1966   return V;
1967 }
1968
1969 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1970   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1971
1972   if (Op0 == Op1)         // sub X, X  -> 0
1973     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1974
1975   // If this is a 'B = x-(-A)', change to B = x+A...
1976   if (Value *V = dyn_castNegVal(Op1))
1977     return BinaryOperator::createAdd(Op0, V);
1978
1979   if (isa<UndefValue>(Op0))
1980     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1981   if (isa<UndefValue>(Op1))
1982     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1983
1984   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1985     // Replace (-1 - A) with (~A)...
1986     if (C->isAllOnesValue())
1987       return BinaryOperator::createNot(Op1);
1988
1989     // C - ~X == X + (1+C)
1990     Value *X = 0;
1991     if (match(Op1, m_Not(m_Value(X))))
1992       return BinaryOperator::createAdd(X,
1993                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1994     // -((uint)X >> 31) -> ((int)X >> 31)
1995     // -((int)X >> 31) -> ((uint)X >> 31)
1996     if (C->isNullValue()) {
1997       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1998       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1999         if (SI->getOpcode() == Instruction::LShr) {
2000           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2001             // Check to see if we are shifting out everything but the sign bit.
2002             if (CU->getZExtValue() == 
2003                 SI->getType()->getPrimitiveSizeInBits()-1) {
2004               // Ok, the transformation is safe.  Insert AShr.
2005               return new ShiftInst(Instruction::AShr, SI->getOperand(0),
2006                                     CU, SI->getName());
2007             }
2008           }
2009         }
2010         else if (SI->getOpcode() == Instruction::AShr) {
2011           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2012             // Check to see if we are shifting out everything but the sign bit.
2013             if (CU->getZExtValue() == 
2014                 SI->getType()->getPrimitiveSizeInBits()-1) {
2015               // Ok, the transformation is safe.  Insert LShr.
2016               return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2017                                     CU, SI->getName());
2018             }
2019           }
2020         } 
2021     }
2022
2023     // Try to fold constant sub into select arguments.
2024     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2025       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2026         return R;
2027
2028     if (isa<PHINode>(Op0))
2029       if (Instruction *NV = FoldOpIntoPhi(I))
2030         return NV;
2031   }
2032
2033   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2034     if (Op1I->getOpcode() == Instruction::Add &&
2035         !Op0->getType()->isFPOrFPVector()) {
2036       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2037         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2038       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2039         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2040       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2041         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2042           // C1-(X+C2) --> (C1-C2)-X
2043           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2044                                            Op1I->getOperand(0));
2045       }
2046     }
2047
2048     if (Op1I->hasOneUse()) {
2049       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2050       // is not used by anyone else...
2051       //
2052       if (Op1I->getOpcode() == Instruction::Sub &&
2053           !Op1I->getType()->isFPOrFPVector()) {
2054         // Swap the two operands of the subexpr...
2055         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2056         Op1I->setOperand(0, IIOp1);
2057         Op1I->setOperand(1, IIOp0);
2058
2059         // Create the new top level add instruction...
2060         return BinaryOperator::createAdd(Op0, Op1);
2061       }
2062
2063       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2064       //
2065       if (Op1I->getOpcode() == Instruction::And &&
2066           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2067         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2068
2069         Value *NewNot =
2070           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2071         return BinaryOperator::createAnd(Op0, NewNot);
2072       }
2073
2074       // 0 - (X sdiv C)  -> (X sdiv -C)
2075       if (Op1I->getOpcode() == Instruction::SDiv)
2076         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2077           if (CSI->isNullValue())
2078             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2079               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2080                                                ConstantExpr::getNeg(DivRHS));
2081
2082       // X - X*C --> X * (1-C)
2083       ConstantInt *C2 = 0;
2084       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2085         Constant *CP1 =
2086           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2087         return BinaryOperator::createMul(Op0, CP1);
2088       }
2089     }
2090   }
2091
2092   if (!Op0->getType()->isFPOrFPVector())
2093     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2094       if (Op0I->getOpcode() == Instruction::Add) {
2095         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2096           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2097         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2098           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2099       } else if (Op0I->getOpcode() == Instruction::Sub) {
2100         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2101           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2102       }
2103
2104   ConstantInt *C1;
2105   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2106     if (X == Op1) { // X*C - X --> X * (C-1)
2107       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2108       return BinaryOperator::createMul(Op1, CP1);
2109     }
2110
2111     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2112     if (X == dyn_castFoldableMul(Op1, C2))
2113       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2114   }
2115   return 0;
2116 }
2117
2118 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2119 /// really just returns true if the most significant (sign) bit is set.
2120 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2121   switch (pred) {
2122     case ICmpInst::ICMP_SLT: 
2123       // True if LHS s< RHS and RHS == 0
2124       return RHS->isNullValue();
2125     case ICmpInst::ICMP_SLE: 
2126       // True if LHS s<= RHS and RHS == -1
2127       return RHS->isAllOnesValue();
2128     case ICmpInst::ICMP_UGE: 
2129       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2130       return RHS->getZExtValue() == (1ULL << 
2131         (RHS->getType()->getPrimitiveSizeInBits()-1));
2132     case ICmpInst::ICMP_UGT:
2133       // True if LHS u> RHS and RHS == high-bit-mask - 1
2134       return RHS->getZExtValue() ==
2135         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2136     default:
2137       return false;
2138   }
2139 }
2140
2141 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2142   bool Changed = SimplifyCommutative(I);
2143   Value *Op0 = I.getOperand(0);
2144
2145   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2146     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2147
2148   // Simplify mul instructions with a constant RHS...
2149   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2150     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2151
2152       // ((X << C1)*C2) == (X * (C2 << C1))
2153       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2154         if (SI->getOpcode() == Instruction::Shl)
2155           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2156             return BinaryOperator::createMul(SI->getOperand(0),
2157                                              ConstantExpr::getShl(CI, ShOp));
2158
2159       if (CI->isNullValue())
2160         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2161       if (CI->equalsInt(1))                  // X * 1  == X
2162         return ReplaceInstUsesWith(I, Op0);
2163       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2164         return BinaryOperator::createNeg(Op0, I.getName());
2165
2166       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2167       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2168         uint64_t C = Log2_64(Val);
2169         return new ShiftInst(Instruction::Shl, Op0,
2170                              ConstantInt::get(Type::UByteTy, C));
2171       }
2172     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2173       if (Op1F->isNullValue())
2174         return ReplaceInstUsesWith(I, Op1);
2175
2176       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2177       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2178       if (Op1F->getValue() == 1.0)
2179         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2180     }
2181     
2182     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2183       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2184           isa<ConstantInt>(Op0I->getOperand(1))) {
2185         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2186         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2187                                                      Op1, "tmp");
2188         InsertNewInstBefore(Add, I);
2189         Value *C1C2 = ConstantExpr::getMul(Op1, 
2190                                            cast<Constant>(Op0I->getOperand(1)));
2191         return BinaryOperator::createAdd(Add, C1C2);
2192         
2193       }
2194
2195     // Try to fold constant mul into select arguments.
2196     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2197       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2198         return R;
2199
2200     if (isa<PHINode>(Op0))
2201       if (Instruction *NV = FoldOpIntoPhi(I))
2202         return NV;
2203   }
2204
2205   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2206     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2207       return BinaryOperator::createMul(Op0v, Op1v);
2208
2209   // If one of the operands of the multiply is a cast from a boolean value, then
2210   // we know the bool is either zero or one, so this is a 'masking' multiply.
2211   // See if we can simplify things based on how the boolean was originally
2212   // formed.
2213   CastInst *BoolCast = 0;
2214   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2215     if (CI->getOperand(0)->getType() == Type::BoolTy)
2216       BoolCast = CI;
2217   if (!BoolCast)
2218     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2219       if (CI->getOperand(0)->getType() == Type::BoolTy)
2220         BoolCast = CI;
2221   if (BoolCast) {
2222     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2223       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2224       const Type *SCOpTy = SCIOp0->getType();
2225
2226       // If the icmp is true iff the sign bit of X is set, then convert this
2227       // multiply into a shift/and combination.
2228       if (isa<ConstantInt>(SCIOp1) &&
2229           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2230         // Shift the X value right to turn it into "all signbits".
2231         Constant *Amt = ConstantInt::get(Type::UByteTy,
2232                                           SCOpTy->getPrimitiveSizeInBits()-1);
2233         Value *V =
2234           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2235                                             BoolCast->getOperand(0)->getName()+
2236                                             ".mask"), I);
2237
2238         // If the multiply type is not the same as the source type, sign extend
2239         // or truncate to the multiply type.
2240         if (I.getType() != V->getType()) {
2241           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2242           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2243           Instruction::CastOps opcode = 
2244             (SrcBits == DstBits ? Instruction::BitCast : 
2245              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2246           V = InsertCastBefore(opcode, V, I.getType(), I);
2247         }
2248
2249         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2250         return BinaryOperator::createAnd(V, OtherOp);
2251       }
2252     }
2253   }
2254
2255   return Changed ? &I : 0;
2256 }
2257
2258 /// This function implements the transforms on div instructions that work
2259 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2260 /// used by the visitors to those instructions.
2261 /// @brief Transforms common to all three div instructions
2262 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2263   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2264
2265   // undef / X -> 0
2266   if (isa<UndefValue>(Op0))
2267     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2268
2269   // X / undef -> undef
2270   if (isa<UndefValue>(Op1))
2271     return ReplaceInstUsesWith(I, Op1);
2272
2273   // Handle cases involving: div X, (select Cond, Y, Z)
2274   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2275     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2276     // same basic block, then we replace the select with Y, and the condition 
2277     // of the select with false (if the cond value is in the same BB).  If the
2278     // select has uses other than the div, this allows them to be simplified
2279     // also. Note that div X, Y is just as good as div X, 0 (undef)
2280     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2281       if (ST->isNullValue()) {
2282         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2283         if (CondI && CondI->getParent() == I.getParent())
2284           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2285         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2286           I.setOperand(1, SI->getOperand(2));
2287         else
2288           UpdateValueUsesWith(SI, SI->getOperand(2));
2289         return &I;
2290       }
2291
2292     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2293     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2294       if (ST->isNullValue()) {
2295         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2296         if (CondI && CondI->getParent() == I.getParent())
2297           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2298         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2299           I.setOperand(1, SI->getOperand(1));
2300         else
2301           UpdateValueUsesWith(SI, SI->getOperand(1));
2302         return &I;
2303       }
2304   }
2305
2306   return 0;
2307 }
2308
2309 /// This function implements the transforms common to both integer division
2310 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2311 /// division instructions.
2312 /// @brief Common integer divide transforms
2313 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2314   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2315
2316   if (Instruction *Common = commonDivTransforms(I))
2317     return Common;
2318
2319   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2320     // div X, 1 == X
2321     if (RHS->equalsInt(1))
2322       return ReplaceInstUsesWith(I, Op0);
2323
2324     // (X / C1) / C2  -> X / (C1*C2)
2325     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2326       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2327         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2328           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2329                                         ConstantExpr::getMul(RHS, LHSRHS));
2330         }
2331
2332     if (!RHS->isNullValue()) { // avoid X udiv 0
2333       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2334         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2335           return R;
2336       if (isa<PHINode>(Op0))
2337         if (Instruction *NV = FoldOpIntoPhi(I))
2338           return NV;
2339     }
2340   }
2341
2342   // 0 / X == 0, we don't need to preserve faults!
2343   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2344     if (LHS->equalsInt(0))
2345       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2346
2347   return 0;
2348 }
2349
2350 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2351   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2352
2353   // Handle the integer div common cases
2354   if (Instruction *Common = commonIDivTransforms(I))
2355     return Common;
2356
2357   // X udiv C^2 -> X >> C
2358   // Check to see if this is an unsigned division with an exact power of 2,
2359   // if so, convert to a right shift.
2360   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2361     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2362       if (isPowerOf2_64(Val)) {
2363         uint64_t ShiftAmt = Log2_64(Val);
2364         return new ShiftInst(Instruction::LShr, Op0, 
2365                               ConstantInt::get(Type::UByteTy, ShiftAmt));
2366       }
2367   }
2368
2369   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2370   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2371     if (RHSI->getOpcode() == Instruction::Shl &&
2372         isa<ConstantInt>(RHSI->getOperand(0))) {
2373       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2374       if (isPowerOf2_64(C1)) {
2375         Value *N = RHSI->getOperand(1);
2376         const Type *NTy = N->getType();
2377         if (uint64_t C2 = Log2_64(C1)) {
2378           Constant *C2V = ConstantInt::get(NTy, C2);
2379           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2380         }
2381         return new ShiftInst(Instruction::LShr, Op0, N);
2382       }
2383     }
2384   }
2385   
2386   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2387   // where C1&C2 are powers of two.
2388   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2389     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2390       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2391         if (!STO->isNullValue() && !STO->isNullValue()) {
2392           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2393           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2394             // Compute the shift amounts
2395             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2396             // Construct the "on true" case of the select
2397             Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2398             Instruction *TSI = 
2399               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2400             TSI = InsertNewInstBefore(TSI, I);
2401     
2402             // Construct the "on false" case of the select
2403             Constant *FC = ConstantInt::get(Type::UByteTy, FSA); 
2404             Instruction *FSI = 
2405               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2406             FSI = InsertNewInstBefore(FSI, I);
2407
2408             // construct the select instruction and return it.
2409             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2410           }
2411         }
2412   }
2413   return 0;
2414 }
2415
2416 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2417   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2418
2419   // Handle the integer div common cases
2420   if (Instruction *Common = commonIDivTransforms(I))
2421     return Common;
2422
2423   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2424     // sdiv X, -1 == -X
2425     if (RHS->isAllOnesValue())
2426       return BinaryOperator::createNeg(Op0);
2427
2428     // -X/C -> X/-C
2429     if (Value *LHSNeg = dyn_castNegVal(Op0))
2430       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2431   }
2432
2433   // If the sign bits of both operands are zero (i.e. we can prove they are
2434   // unsigned inputs), turn this into a udiv.
2435   if (I.getType()->isInteger()) {
2436     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2437     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2438       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2439     }
2440   }      
2441   
2442   return 0;
2443 }
2444
2445 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2446   return commonDivTransforms(I);
2447 }
2448
2449 /// GetFactor - If we can prove that the specified value is at least a multiple
2450 /// of some factor, return that factor.
2451 static Constant *GetFactor(Value *V) {
2452   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2453     return CI;
2454   
2455   // Unless we can be tricky, we know this is a multiple of 1.
2456   Constant *Result = ConstantInt::get(V->getType(), 1);
2457   
2458   Instruction *I = dyn_cast<Instruction>(V);
2459   if (!I) return Result;
2460   
2461   if (I->getOpcode() == Instruction::Mul) {
2462     // Handle multiplies by a constant, etc.
2463     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2464                                 GetFactor(I->getOperand(1)));
2465   } else if (I->getOpcode() == Instruction::Shl) {
2466     // (X<<C) -> X * (1 << C)
2467     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2468       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2469       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2470     }
2471   } else if (I->getOpcode() == Instruction::And) {
2472     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2473       // X & 0xFFF0 is known to be a multiple of 16.
2474       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2475       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2476         return ConstantExpr::getShl(Result, 
2477                                     ConstantInt::get(Type::UByteTy, Zeros));
2478     }
2479   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2480     // Only handle int->int casts.
2481     if (!CI->isIntegerCast())
2482       return Result;
2483     Value *Op = CI->getOperand(0);
2484     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2485   }    
2486   return Result;
2487 }
2488
2489 /// This function implements the transforms on rem instructions that work
2490 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2491 /// is used by the visitors to those instructions.
2492 /// @brief Transforms common to all three rem instructions
2493 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2494   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2495
2496   // 0 % X == 0, we don't need to preserve faults!
2497   if (Constant *LHS = dyn_cast<Constant>(Op0))
2498     if (LHS->isNullValue())
2499       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2500
2501   if (isa<UndefValue>(Op0))              // undef % X -> 0
2502     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2503   if (isa<UndefValue>(Op1))
2504     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2505
2506   // Handle cases involving: rem X, (select Cond, Y, Z)
2507   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2508     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2509     // the same basic block, then we replace the select with Y, and the
2510     // condition of the select with false (if the cond value is in the same
2511     // BB).  If the select has uses other than the div, this allows them to be
2512     // simplified also.
2513     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2514       if (ST->isNullValue()) {
2515         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2516         if (CondI && CondI->getParent() == I.getParent())
2517           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2518         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2519           I.setOperand(1, SI->getOperand(2));
2520         else
2521           UpdateValueUsesWith(SI, SI->getOperand(2));
2522         return &I;
2523       }
2524     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2525     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2526       if (ST->isNullValue()) {
2527         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2528         if (CondI && CondI->getParent() == I.getParent())
2529           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2530         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2531           I.setOperand(1, SI->getOperand(1));
2532         else
2533           UpdateValueUsesWith(SI, SI->getOperand(1));
2534         return &I;
2535       }
2536   }
2537
2538   return 0;
2539 }
2540
2541 /// This function implements the transforms common to both integer remainder
2542 /// instructions (urem and srem). It is called by the visitors to those integer
2543 /// remainder instructions.
2544 /// @brief Common integer remainder transforms
2545 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2546   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2547
2548   if (Instruction *common = commonRemTransforms(I))
2549     return common;
2550
2551   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2552     // X % 0 == undef, we don't need to preserve faults!
2553     if (RHS->equalsInt(0))
2554       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2555     
2556     if (RHS->equalsInt(1))  // X % 1 == 0
2557       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2558
2559     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2560       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2561         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2562           return R;
2563       } else if (isa<PHINode>(Op0I)) {
2564         if (Instruction *NV = FoldOpIntoPhi(I))
2565           return NV;
2566       }
2567       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2568       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2569         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2570     }
2571   }
2572
2573   return 0;
2574 }
2575
2576 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2577   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2578
2579   if (Instruction *common = commonIRemTransforms(I))
2580     return common;
2581   
2582   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2583     // X urem C^2 -> X and C
2584     // Check to see if this is an unsigned remainder with an exact power of 2,
2585     // if so, convert to a bitwise and.
2586     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2587       if (isPowerOf2_64(C->getZExtValue()))
2588         return BinaryOperator::createAnd(Op0, SubOne(C));
2589   }
2590
2591   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2592     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2593     if (RHSI->getOpcode() == Instruction::Shl &&
2594         isa<ConstantInt>(RHSI->getOperand(0))) {
2595       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2596       if (isPowerOf2_64(C1)) {
2597         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2598         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2599                                                                    "tmp"), I);
2600         return BinaryOperator::createAnd(Op0, Add);
2601       }
2602     }
2603   }
2604
2605   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2606   // where C1&C2 are powers of two.
2607   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2608     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2609       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2610         // STO == 0 and SFO == 0 handled above.
2611         if (isPowerOf2_64(STO->getZExtValue()) && 
2612             isPowerOf2_64(SFO->getZExtValue())) {
2613           Value *TrueAnd = InsertNewInstBefore(
2614             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2615           Value *FalseAnd = InsertNewInstBefore(
2616             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2617           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2618         }
2619       }
2620   }
2621   
2622   return 0;
2623 }
2624
2625 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2626   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2627
2628   if (Instruction *common = commonIRemTransforms(I))
2629     return common;
2630   
2631   if (Value *RHSNeg = dyn_castNegVal(Op1))
2632     if (!isa<ConstantInt>(RHSNeg) || 
2633         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2634       // X % -Y -> X % Y
2635       AddUsesToWorkList(I);
2636       I.setOperand(1, RHSNeg);
2637       return &I;
2638     }
2639  
2640   // If the top bits of both operands are zero (i.e. we can prove they are
2641   // unsigned inputs), turn this into a urem.
2642   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2643   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2644     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2645     return BinaryOperator::createURem(Op0, Op1, I.getName());
2646   }
2647
2648   return 0;
2649 }
2650
2651 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2652   return commonRemTransforms(I);
2653 }
2654
2655 // isMaxValueMinusOne - return true if this is Max-1
2656 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2657   if (isSigned) {
2658     // Calculate 0111111111..11111
2659     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2660     int64_t Val = INT64_MAX;             // All ones
2661     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2662     return C->getSExtValue() == Val-1;
2663   }
2664   return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2665 }
2666
2667 // isMinValuePlusOne - return true if this is Min+1
2668 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2669   if (isSigned) {
2670     // Calculate 1111111111000000000000
2671     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2672     int64_t Val = -1;                    // All ones
2673     Val <<= TypeBits-1;                  // Shift over to the right spot
2674     return C->getSExtValue() == Val+1;
2675   }
2676   return C->getZExtValue() == 1; // unsigned
2677 }
2678
2679 // isOneBitSet - Return true if there is exactly one bit set in the specified
2680 // constant.
2681 static bool isOneBitSet(const ConstantInt *CI) {
2682   uint64_t V = CI->getZExtValue();
2683   return V && (V & (V-1)) == 0;
2684 }
2685
2686 #if 0   // Currently unused
2687 // isLowOnes - Return true if the constant is of the form 0+1+.
2688 static bool isLowOnes(const ConstantInt *CI) {
2689   uint64_t V = CI->getZExtValue();
2690
2691   // There won't be bits set in parts that the type doesn't contain.
2692   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2693
2694   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2695   return U && V && (U & V) == 0;
2696 }
2697 #endif
2698
2699 // isHighOnes - Return true if the constant is of the form 1+0+.
2700 // This is the same as lowones(~X).
2701 static bool isHighOnes(const ConstantInt *CI) {
2702   uint64_t V = ~CI->getZExtValue();
2703   if (~V == 0) return false;  // 0's does not match "1+"
2704
2705   // There won't be bits set in parts that the type doesn't contain.
2706   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2707
2708   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2709   return U && V && (U & V) == 0;
2710 }
2711
2712 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2713 /// are carefully arranged to allow folding of expressions such as:
2714 ///
2715 ///      (A < B) | (A > B) --> (A != B)
2716 ///
2717 /// Note that this is only valid if the first and second predicates have the
2718 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2719 ///
2720 /// Three bits are used to represent the condition, as follows:
2721 ///   0  A > B
2722 ///   1  A == B
2723 ///   2  A < B
2724 ///
2725 /// <=>  Value  Definition
2726 /// 000     0   Always false
2727 /// 001     1   A >  B
2728 /// 010     2   A == B
2729 /// 011     3   A >= B
2730 /// 100     4   A <  B
2731 /// 101     5   A != B
2732 /// 110     6   A <= B
2733 /// 111     7   Always true
2734 ///  
2735 static unsigned getICmpCode(const ICmpInst *ICI) {
2736   switch (ICI->getPredicate()) {
2737     // False -> 0
2738   case ICmpInst::ICMP_UGT: return 1;  // 001
2739   case ICmpInst::ICMP_SGT: return 1;  // 001
2740   case ICmpInst::ICMP_EQ:  return 2;  // 010
2741   case ICmpInst::ICMP_UGE: return 3;  // 011
2742   case ICmpInst::ICMP_SGE: return 3;  // 011
2743   case ICmpInst::ICMP_ULT: return 4;  // 100
2744   case ICmpInst::ICMP_SLT: return 4;  // 100
2745   case ICmpInst::ICMP_NE:  return 5;  // 101
2746   case ICmpInst::ICMP_ULE: return 6;  // 110
2747   case ICmpInst::ICMP_SLE: return 6;  // 110
2748     // True -> 7
2749   default:
2750     assert(0 && "Invalid ICmp predicate!");
2751     return 0;
2752   }
2753 }
2754
2755 /// getICmpValue - This is the complement of getICmpCode, which turns an
2756 /// opcode and two operands into either a constant true or false, or a brand 
2757 /// new /// ICmp instruction. The sign is passed in to determine which kind
2758 /// of predicate to use in new icmp instructions.
2759 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2760   switch (code) {
2761   default: assert(0 && "Illegal ICmp code!");
2762   case  0: return ConstantBool::getFalse();
2763   case  1: 
2764     if (sign)
2765       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2766     else
2767       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2768   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2769   case  3: 
2770     if (sign)
2771       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2772     else
2773       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2774   case  4: 
2775     if (sign)
2776       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2777     else
2778       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2779   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2780   case  6: 
2781     if (sign)
2782       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2783     else
2784       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2785   case  7: return ConstantBool::getTrue();
2786   }
2787 }
2788
2789 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2790   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2791     (ICmpInst::isSignedPredicate(p1) && 
2792      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2793     (ICmpInst::isSignedPredicate(p2) && 
2794      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2795 }
2796
2797 namespace { 
2798 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2799 struct FoldICmpLogical {
2800   InstCombiner &IC;
2801   Value *LHS, *RHS;
2802   ICmpInst::Predicate pred;
2803   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2804     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2805       pred(ICI->getPredicate()) {}
2806   bool shouldApply(Value *V) const {
2807     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2808       if (PredicatesFoldable(pred, ICI->getPredicate()))
2809         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2810                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2811     return false;
2812   }
2813   Instruction *apply(Instruction &Log) const {
2814     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2815     if (ICI->getOperand(0) != LHS) {
2816       assert(ICI->getOperand(1) == LHS);
2817       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2818     }
2819
2820     unsigned LHSCode = getICmpCode(ICI);
2821     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2822     unsigned Code;
2823     switch (Log.getOpcode()) {
2824     case Instruction::And: Code = LHSCode & RHSCode; break;
2825     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2826     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2827     default: assert(0 && "Illegal logical opcode!"); return 0;
2828     }
2829
2830     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2831     if (Instruction *I = dyn_cast<Instruction>(RV))
2832       return I;
2833     // Otherwise, it's a constant boolean value...
2834     return IC.ReplaceInstUsesWith(Log, RV);
2835   }
2836 };
2837 } // end anonymous namespace
2838
2839 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2840 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2841 // guaranteed to be either a shift instruction or a binary operator.
2842 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2843                                     ConstantIntegral *OpRHS,
2844                                     ConstantIntegral *AndRHS,
2845                                     BinaryOperator &TheAnd) {
2846   Value *X = Op->getOperand(0);
2847   Constant *Together = 0;
2848   if (!isa<ShiftInst>(Op))
2849     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2850
2851   switch (Op->getOpcode()) {
2852   case Instruction::Xor:
2853     if (Op->hasOneUse()) {
2854       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2855       std::string OpName = Op->getName(); Op->setName("");
2856       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2857       InsertNewInstBefore(And, TheAnd);
2858       return BinaryOperator::createXor(And, Together);
2859     }
2860     break;
2861   case Instruction::Or:
2862     if (Together == AndRHS) // (X | C) & C --> C
2863       return ReplaceInstUsesWith(TheAnd, AndRHS);
2864
2865     if (Op->hasOneUse() && Together != OpRHS) {
2866       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2867       std::string Op0Name = Op->getName(); Op->setName("");
2868       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2869       InsertNewInstBefore(Or, TheAnd);
2870       return BinaryOperator::createAnd(Or, AndRHS);
2871     }
2872     break;
2873   case Instruction::Add:
2874     if (Op->hasOneUse()) {
2875       // Adding a one to a single bit bit-field should be turned into an XOR
2876       // of the bit.  First thing to check is to see if this AND is with a
2877       // single bit constant.
2878       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2879
2880       // Clear bits that are not part of the constant.
2881       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2882
2883       // If there is only one bit set...
2884       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2885         // Ok, at this point, we know that we are masking the result of the
2886         // ADD down to exactly one bit.  If the constant we are adding has
2887         // no bits set below this bit, then we can eliminate the ADD.
2888         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2889
2890         // Check to see if any bits below the one bit set in AndRHSV are set.
2891         if ((AddRHS & (AndRHSV-1)) == 0) {
2892           // If not, the only thing that can effect the output of the AND is
2893           // the bit specified by AndRHSV.  If that bit is set, the effect of
2894           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2895           // no effect.
2896           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2897             TheAnd.setOperand(0, X);
2898             return &TheAnd;
2899           } else {
2900             std::string Name = Op->getName(); Op->setName("");
2901             // Pull the XOR out of the AND.
2902             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2903             InsertNewInstBefore(NewAnd, TheAnd);
2904             return BinaryOperator::createXor(NewAnd, AndRHS);
2905           }
2906         }
2907       }
2908     }
2909     break;
2910
2911   case Instruction::Shl: {
2912     // We know that the AND will not produce any of the bits shifted in, so if
2913     // the anded constant includes them, clear them now!
2914     //
2915     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2916     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2917     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2918
2919     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2920       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2921     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2922       TheAnd.setOperand(1, CI);
2923       return &TheAnd;
2924     }
2925     break;
2926   }
2927   case Instruction::LShr:
2928   {
2929     // We know that the AND will not produce any of the bits shifted in, so if
2930     // the anded constant includes them, clear them now!  This only applies to
2931     // unsigned shifts, because a signed shr may bring in set bits!
2932     //
2933     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2934     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2935     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2936
2937     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2938       return ReplaceInstUsesWith(TheAnd, Op);
2939     } else if (CI != AndRHS) {
2940       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2941       return &TheAnd;
2942     }
2943     break;
2944   }
2945   case Instruction::AShr:
2946     // Signed shr.
2947     // See if this is shifting in some sign extension, then masking it out
2948     // with an and.
2949     if (Op->hasOneUse()) {
2950       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2951       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2952       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2953       if (C == AndRHS) {          // Masking out bits shifted in.
2954         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2955         // Make the argument unsigned.
2956         Value *ShVal = Op->getOperand(0);
2957         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2958                                     OpRHS, Op->getName()), TheAnd);
2959         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2960       }
2961     }
2962     break;
2963   }
2964   return 0;
2965 }
2966
2967
2968 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2969 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2970 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2971 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2972 /// insert new instructions.
2973 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2974                                            bool isSigned, bool Inside, 
2975                                            Instruction &IB) {
2976   assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ? 
2977             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
2978          "Lo is not <= Hi in range emission code!");
2979     
2980   if (Inside) {
2981     if (Lo == Hi)  // Trivially false.
2982       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2983
2984     // V >= Min && V < Hi --> V < Hi
2985     if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2986     ICmpInst::Predicate pred = (isSigned ? 
2987         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2988       return new ICmpInst(pred, V, Hi);
2989     }
2990
2991     // Emit V-Lo <u Hi-Lo
2992     Constant *NegLo = ConstantExpr::getNeg(Lo);
2993     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2994     InsertNewInstBefore(Add, IB);
2995     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2996     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2997   }
2998
2999   if (Lo == Hi)  // Trivially true.
3000     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3001
3002   // V < Min || V >= Hi ->'V > Hi-1'
3003   Hi = SubOne(cast<ConstantInt>(Hi));
3004   if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3005     ICmpInst::Predicate pred = (isSigned ? 
3006         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3007     return new ICmpInst(pred, V, Hi);
3008   }
3009
3010   // Emit V-Lo > Hi-1-Lo
3011   Constant *NegLo = ConstantExpr::getNeg(Lo);
3012   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3013   InsertNewInstBefore(Add, IB);
3014   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3015   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3016 }
3017
3018 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3019 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3020 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3021 // not, since all 1s are not contiguous.
3022 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
3023   uint64_t V = Val->getZExtValue();
3024   if (!isShiftedMask_64(V)) return false;
3025
3026   // look for the first zero bit after the run of ones
3027   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3028   // look for the first non-zero bit
3029   ME = 64-CountLeadingZeros_64(V);
3030   return true;
3031 }
3032
3033
3034
3035 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3036 /// where isSub determines whether the operator is a sub.  If we can fold one of
3037 /// the following xforms:
3038 /// 
3039 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3040 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3041 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3042 ///
3043 /// return (A +/- B).
3044 ///
3045 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3046                                         ConstantIntegral *Mask, bool isSub,
3047                                         Instruction &I) {
3048   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3049   if (!LHSI || LHSI->getNumOperands() != 2 ||
3050       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3051
3052   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3053
3054   switch (LHSI->getOpcode()) {
3055   default: return 0;
3056   case Instruction::And:
3057     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3058       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3059       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3060         break;
3061
3062       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3063       // part, we don't need any explicit masks to take them out of A.  If that
3064       // is all N is, ignore it.
3065       unsigned MB, ME;
3066       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3067         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3068         Mask >>= 64-MB+1;
3069         if (MaskedValueIsZero(RHS, Mask))
3070           break;
3071       }
3072     }
3073     return 0;
3074   case Instruction::Or:
3075   case Instruction::Xor:
3076     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3077     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3078         ConstantExpr::getAnd(N, Mask)->isNullValue())
3079       break;
3080     return 0;
3081   }
3082   
3083   Instruction *New;
3084   if (isSub)
3085     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3086   else
3087     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3088   return InsertNewInstBefore(New, I);
3089 }
3090
3091 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3092   bool Changed = SimplifyCommutative(I);
3093   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3094
3095   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3096     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3097
3098   // and X, X = X
3099   if (Op0 == Op1)
3100     return ReplaceInstUsesWith(I, Op1);
3101
3102   // See if we can simplify any instructions used by the instruction whose sole 
3103   // purpose is to compute bits we don't care about.
3104   uint64_t KnownZero, KnownOne;
3105   if (!isa<PackedType>(I.getType()) &&
3106       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3107                            KnownZero, KnownOne))
3108     return &I;
3109   
3110   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3111     uint64_t AndRHSMask = AndRHS->getZExtValue();
3112     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3113     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3114
3115     // Optimize a variety of ((val OP C1) & C2) combinations...
3116     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3117       Instruction *Op0I = cast<Instruction>(Op0);
3118       Value *Op0LHS = Op0I->getOperand(0);
3119       Value *Op0RHS = Op0I->getOperand(1);
3120       switch (Op0I->getOpcode()) {
3121       case Instruction::Xor:
3122       case Instruction::Or:
3123         // If the mask is only needed on one incoming arm, push it up.
3124         if (Op0I->hasOneUse()) {
3125           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3126             // Not masking anything out for the LHS, move to RHS.
3127             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3128                                                    Op0RHS->getName()+".masked");
3129             InsertNewInstBefore(NewRHS, I);
3130             return BinaryOperator::create(
3131                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3132           }
3133           if (!isa<Constant>(Op0RHS) &&
3134               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3135             // Not masking anything out for the RHS, move to LHS.
3136             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3137                                                    Op0LHS->getName()+".masked");
3138             InsertNewInstBefore(NewLHS, I);
3139             return BinaryOperator::create(
3140                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3141           }
3142         }
3143
3144         break;
3145       case Instruction::Add:
3146         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3147         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3148         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3149         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3150           return BinaryOperator::createAnd(V, AndRHS);
3151         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3152           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3153         break;
3154
3155       case Instruction::Sub:
3156         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3157         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3158         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3159         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3160           return BinaryOperator::createAnd(V, AndRHS);
3161         break;
3162       }
3163
3164       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3165         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3166           return Res;
3167     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3168       // If this is an integer truncation or change from signed-to-unsigned, and
3169       // if the source is an and/or with immediate, transform it.  This
3170       // frequently occurs for bitfield accesses.
3171       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3172         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3173             CastOp->getNumOperands() == 2)
3174           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3175             if (CastOp->getOpcode() == Instruction::And) {
3176               // Change: and (cast (and X, C1) to T), C2
3177               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3178               // This will fold the two constants together, which may allow 
3179               // other simplifications.
3180               Instruction *NewCast = CastInst::createTruncOrBitCast(
3181                 CastOp->getOperand(0), I.getType(), 
3182                 CastOp->getName()+".shrunk");
3183               NewCast = InsertNewInstBefore(NewCast, I);
3184               // trunc_or_bitcast(C1)&C2
3185               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3186               C3 = ConstantExpr::getAnd(C3, AndRHS);
3187               return BinaryOperator::createAnd(NewCast, C3);
3188             } else if (CastOp->getOpcode() == Instruction::Or) {
3189               // Change: and (cast (or X, C1) to T), C2
3190               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3191               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3192               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3193                 return ReplaceInstUsesWith(I, AndRHS);
3194             }
3195       }
3196     }
3197
3198     // Try to fold constant and into select arguments.
3199     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3200       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3201         return R;
3202     if (isa<PHINode>(Op0))
3203       if (Instruction *NV = FoldOpIntoPhi(I))
3204         return NV;
3205   }
3206
3207   Value *Op0NotVal = dyn_castNotVal(Op0);
3208   Value *Op1NotVal = dyn_castNotVal(Op1);
3209
3210   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3211     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3212
3213   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3214   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3215     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3216                                                I.getName()+".demorgan");
3217     InsertNewInstBefore(Or, I);
3218     return BinaryOperator::createNot(Or);
3219   }
3220   
3221   {
3222     Value *A = 0, *B = 0;
3223     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3224       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3225         return ReplaceInstUsesWith(I, Op1);
3226     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3227       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3228         return ReplaceInstUsesWith(I, Op0);
3229     
3230     if (Op0->hasOneUse() &&
3231         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3232       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3233         I.swapOperands();     // Simplify below
3234         std::swap(Op0, Op1);
3235       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3236         cast<BinaryOperator>(Op0)->swapOperands();
3237         I.swapOperands();     // Simplify below
3238         std::swap(Op0, Op1);
3239       }
3240     }
3241     if (Op1->hasOneUse() &&
3242         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3243       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3244         cast<BinaryOperator>(Op1)->swapOperands();
3245         std::swap(A, B);
3246       }
3247       if (A == Op0) {                                // A&(A^B) -> A & ~B
3248         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3249         InsertNewInstBefore(NotB, I);
3250         return BinaryOperator::createAnd(A, NotB);
3251       }
3252     }
3253   }
3254   
3255   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3256     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3257     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3258       return R;
3259
3260     Value *LHSVal, *RHSVal;
3261     ConstantInt *LHSCst, *RHSCst;
3262     ICmpInst::Predicate LHSCC, RHSCC;
3263     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3264       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3265         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3266             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3267             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3268             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3269             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3270             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3271           // Ensure that the larger constant is on the RHS.
3272           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3273             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3274           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3275           ICmpInst *LHS = cast<ICmpInst>(Op0);
3276           if (cast<ConstantBool>(Cmp)->getValue()) {
3277             std::swap(LHS, RHS);
3278             std::swap(LHSCst, RHSCst);
3279             std::swap(LHSCC, RHSCC);
3280           }
3281
3282           // At this point, we know we have have two icmp instructions
3283           // comparing a value against two constants and and'ing the result
3284           // together.  Because of the above check, we know that we only have
3285           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3286           // (from the FoldICmpLogical check above), that the two constants 
3287           // are not equal and that the larger constant is on the RHS
3288           assert(LHSCst != RHSCst && "Compares not folded above?");
3289
3290           switch (LHSCC) {
3291           default: assert(0 && "Unknown integer condition code!");
3292           case ICmpInst::ICMP_EQ:
3293             switch (RHSCC) {
3294             default: assert(0 && "Unknown integer condition code!");
3295             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3296             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3297             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3298               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3299             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3300             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3301             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3302               return ReplaceInstUsesWith(I, LHS);
3303             }
3304           case ICmpInst::ICMP_NE:
3305             switch (RHSCC) {
3306             default: assert(0 && "Unknown integer condition code!");
3307             case ICmpInst::ICMP_ULT:
3308               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3309                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3310               break;                        // (X != 13 & X u< 15) -> no change
3311             case ICmpInst::ICMP_SLT:
3312               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3313                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3314               break;                        // (X != 13 & X s< 15) -> no change
3315             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3316             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3317             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3318               return ReplaceInstUsesWith(I, RHS);
3319             case ICmpInst::ICMP_NE:
3320               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3321                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3322                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3323                                                       LHSVal->getName()+".off");
3324                 InsertNewInstBefore(Add, I);
3325                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3326                 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3327                                                     UnsType, I);
3328                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3329                 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
3330                 return new ICmpInst(ICmpInst::ICMP_UGT, OffsetVal, AddCST);
3331               }
3332               break;                        // (X != 13 & X != 15) -> no change
3333             }
3334             break;
3335           case ICmpInst::ICMP_ULT:
3336             switch (RHSCC) {
3337             default: assert(0 && "Unknown integer condition code!");
3338             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3339             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3340               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3341             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3342               break;
3343             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3344             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3345               return ReplaceInstUsesWith(I, LHS);
3346             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3347               break;
3348             }
3349             break;
3350           case ICmpInst::ICMP_SLT:
3351             switch (RHSCC) {
3352             default: assert(0 && "Unknown integer condition code!");
3353             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3354             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3355               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3356             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3357               break;
3358             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3359             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3360               return ReplaceInstUsesWith(I, LHS);
3361             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3362               break;
3363             }
3364             break;
3365           case ICmpInst::ICMP_UGT:
3366             switch (RHSCC) {
3367             default: assert(0 && "Unknown integer condition code!");
3368             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3369               return ReplaceInstUsesWith(I, LHS);
3370             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3371               return ReplaceInstUsesWith(I, RHS);
3372             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3373               break;
3374             case ICmpInst::ICMP_NE:
3375               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3376                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3377               break;                        // (X u> 13 & X != 15) -> no change
3378             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3379               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3380                                      true, I);
3381             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3382               break;
3383             }
3384             break;
3385           case ICmpInst::ICMP_SGT:
3386             switch (RHSCC) {
3387             default: assert(0 && "Unknown integer condition code!");
3388             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3389               return ReplaceInstUsesWith(I, LHS);
3390             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3391               return ReplaceInstUsesWith(I, RHS);
3392             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3393               break;
3394             case ICmpInst::ICMP_NE:
3395               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3396                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3397               break;                        // (X s> 13 & X != 15) -> no change
3398             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3399               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3400                                      true, I);
3401             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3402               break;
3403             }
3404             break;
3405           }
3406         }
3407   }
3408
3409   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3410   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3411     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3412       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3413         const Type *SrcTy = Op0C->getOperand(0)->getType();
3414         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3415             // Only do this if the casts both really cause code to be generated.
3416             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3417                               I.getType(), TD) &&
3418             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3419                               I.getType(), TD)) {
3420           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3421                                                          Op1C->getOperand(0),
3422                                                          I.getName());
3423           InsertNewInstBefore(NewOp, I);
3424           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3425         }
3426       }
3427     
3428   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3429   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3430     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3431       if (SI0->getOpcode() == SI1->getOpcode() && 
3432           SI0->getOperand(1) == SI1->getOperand(1) &&
3433           (SI0->hasOneUse() || SI1->hasOneUse())) {
3434         Instruction *NewOp =
3435           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3436                                                         SI1->getOperand(0),
3437                                                         SI0->getName()), I);
3438         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3439       }
3440   }
3441
3442   return Changed ? &I : 0;
3443 }
3444
3445 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3446 /// in the result.  If it does, and if the specified byte hasn't been filled in
3447 /// yet, fill it in and return false.
3448 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3449   Instruction *I = dyn_cast<Instruction>(V);
3450   if (I == 0) return true;
3451
3452   // If this is an or instruction, it is an inner node of the bswap.
3453   if (I->getOpcode() == Instruction::Or)
3454     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3455            CollectBSwapParts(I->getOperand(1), ByteValues);
3456   
3457   // If this is a shift by a constant int, and it is "24", then its operand
3458   // defines a byte.  We only handle unsigned types here.
3459   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3460     // Not shifting the entire input by N-1 bytes?
3461     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3462         8*(ByteValues.size()-1))
3463       return true;
3464     
3465     unsigned DestNo;
3466     if (I->getOpcode() == Instruction::Shl) {
3467       // X << 24 defines the top byte with the lowest of the input bytes.
3468       DestNo = ByteValues.size()-1;
3469     } else {
3470       // X >>u 24 defines the low byte with the highest of the input bytes.
3471       DestNo = 0;
3472     }
3473     
3474     // If the destination byte value is already defined, the values are or'd
3475     // together, which isn't a bswap (unless it's an or of the same bits).
3476     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3477       return true;
3478     ByteValues[DestNo] = I->getOperand(0);
3479     return false;
3480   }
3481   
3482   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3483   // don't have this.
3484   Value *Shift = 0, *ShiftLHS = 0;
3485   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3486   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3487       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3488     return true;
3489   Instruction *SI = cast<Instruction>(Shift);
3490
3491   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3492   if (ShiftAmt->getZExtValue() & 7 ||
3493       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3494     return true;
3495   
3496   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3497   unsigned DestByte;
3498   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3499     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3500       break;
3501   // Unknown mask for bswap.
3502   if (DestByte == ByteValues.size()) return true;
3503   
3504   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3505   unsigned SrcByte;
3506   if (SI->getOpcode() == Instruction::Shl)
3507     SrcByte = DestByte - ShiftBytes;
3508   else
3509     SrcByte = DestByte + ShiftBytes;
3510   
3511   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3512   if (SrcByte != ByteValues.size()-DestByte-1)
3513     return true;
3514   
3515   // If the destination byte value is already defined, the values are or'd
3516   // together, which isn't a bswap (unless it's an or of the same bits).
3517   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3518     return true;
3519   ByteValues[DestByte] = SI->getOperand(0);
3520   return false;
3521 }
3522
3523 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3524 /// If so, insert the new bswap intrinsic and return it.
3525 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3526   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3527   if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3528     return 0;
3529   
3530   /// ByteValues - For each byte of the result, we keep track of which value
3531   /// defines each byte.
3532   std::vector<Value*> ByteValues;
3533   ByteValues.resize(I.getType()->getPrimitiveSize());
3534     
3535   // Try to find all the pieces corresponding to the bswap.
3536   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3537       CollectBSwapParts(I.getOperand(1), ByteValues))
3538     return 0;
3539   
3540   // Check to see if all of the bytes come from the same value.
3541   Value *V = ByteValues[0];
3542   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3543   
3544   // Check to make sure that all of the bytes come from the same value.
3545   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3546     if (ByteValues[i] != V)
3547       return 0;
3548     
3549   // If they do then *success* we can turn this into a bswap.  Figure out what
3550   // bswap to make it into.
3551   Module *M = I.getParent()->getParent()->getParent();
3552   const char *FnName = 0;
3553   if (I.getType() == Type::UShortTy)
3554     FnName = "llvm.bswap.i16";
3555   else if (I.getType() == Type::UIntTy)
3556     FnName = "llvm.bswap.i32";
3557   else if (I.getType() == Type::ULongTy)
3558     FnName = "llvm.bswap.i64";
3559   else
3560     assert(0 && "Unknown integer type!");
3561   Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3562   
3563   return new CallInst(F, V);
3564 }
3565
3566
3567 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3568   bool Changed = SimplifyCommutative(I);
3569   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3570
3571   if (isa<UndefValue>(Op1))
3572     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3573                                ConstantIntegral::getAllOnesValue(I.getType()));
3574
3575   // or X, X = X
3576   if (Op0 == Op1)
3577     return ReplaceInstUsesWith(I, Op0);
3578
3579   // See if we can simplify any instructions used by the instruction whose sole 
3580   // purpose is to compute bits we don't care about.
3581   uint64_t KnownZero, KnownOne;
3582   if (!isa<PackedType>(I.getType()) &&
3583       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3584                            KnownZero, KnownOne))
3585     return &I;
3586   
3587   // or X, -1 == -1
3588   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3589     ConstantInt *C1 = 0; Value *X = 0;
3590     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3591     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3592       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3593       Op0->setName("");
3594       InsertNewInstBefore(Or, I);
3595       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3596     }
3597
3598     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3599     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3600       std::string Op0Name = Op0->getName(); Op0->setName("");
3601       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3602       InsertNewInstBefore(Or, I);
3603       return BinaryOperator::createXor(Or,
3604                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3605     }
3606
3607     // Try to fold constant and into select arguments.
3608     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3609       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3610         return R;
3611     if (isa<PHINode>(Op0))
3612       if (Instruction *NV = FoldOpIntoPhi(I))
3613         return NV;
3614   }
3615
3616   Value *A = 0, *B = 0;
3617   ConstantInt *C1 = 0, *C2 = 0;
3618
3619   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3620     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3621       return ReplaceInstUsesWith(I, Op1);
3622   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3623     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3624       return ReplaceInstUsesWith(I, Op0);
3625
3626   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3627   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3628   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3629       match(Op1, m_Or(m_Value(), m_Value())) ||
3630       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3631        match(Op1, m_Shift(m_Value(), m_Value())))) {
3632     if (Instruction *BSwap = MatchBSwap(I))
3633       return BSwap;
3634   }
3635   
3636   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3637   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3638       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3639     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3640     Op0->setName("");
3641     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3642   }
3643
3644   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3645   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3646       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3647     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3648     Op0->setName("");
3649     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3650   }
3651
3652   // (A & C1)|(B & C2)
3653   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3654       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3655
3656     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3657       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3658
3659
3660     // If we have: ((V + N) & C1) | (V & C2)
3661     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3662     // replace with V+N.
3663     if (C1 == ConstantExpr::getNot(C2)) {
3664       Value *V1 = 0, *V2 = 0;
3665       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3666           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3667         // Add commutes, try both ways.
3668         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3669           return ReplaceInstUsesWith(I, A);
3670         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3671           return ReplaceInstUsesWith(I, A);
3672       }
3673       // Or commutes, try both ways.
3674       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3675           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3676         // Add commutes, try both ways.
3677         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3678           return ReplaceInstUsesWith(I, B);
3679         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3680           return ReplaceInstUsesWith(I, B);
3681       }
3682     }
3683   }
3684   
3685   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3686   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3687     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3688       if (SI0->getOpcode() == SI1->getOpcode() && 
3689           SI0->getOperand(1) == SI1->getOperand(1) &&
3690           (SI0->hasOneUse() || SI1->hasOneUse())) {
3691         Instruction *NewOp =
3692         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3693                                                      SI1->getOperand(0),
3694                                                      SI0->getName()), I);
3695         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3696       }
3697   }
3698
3699   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3700     if (A == Op1)   // ~A | A == -1
3701       return ReplaceInstUsesWith(I,
3702                                 ConstantIntegral::getAllOnesValue(I.getType()));
3703   } else {
3704     A = 0;
3705   }
3706   // Note, A is still live here!
3707   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3708     if (Op0 == B)
3709       return ReplaceInstUsesWith(I,
3710                                 ConstantIntegral::getAllOnesValue(I.getType()));
3711
3712     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3713     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3714       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3715                                               I.getName()+".demorgan"), I);
3716       return BinaryOperator::createNot(And);
3717     }
3718   }
3719
3720   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3721   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3722     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3723       return R;
3724
3725     Value *LHSVal, *RHSVal;
3726     ConstantInt *LHSCst, *RHSCst;
3727     ICmpInst::Predicate LHSCC, RHSCC;
3728     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3729       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3730         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3731             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3732             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3733             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3734             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3735             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3736           // Ensure that the larger constant is on the RHS.
3737           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3738             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3739           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3740           ICmpInst *LHS = cast<ICmpInst>(Op0);
3741           if (cast<ConstantBool>(Cmp)->getValue()) {
3742             std::swap(LHS, RHS);
3743             std::swap(LHSCst, RHSCst);
3744             std::swap(LHSCC, RHSCC);
3745           }
3746
3747           // At this point, we know we have have two icmp instructions
3748           // comparing a value against two constants and or'ing the result
3749           // together.  Because of the above check, we know that we only have
3750           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3751           // FoldICmpLogical check above), that the two constants are not
3752           // equal.
3753           assert(LHSCst != RHSCst && "Compares not folded above?");
3754
3755           switch (LHSCC) {
3756           default: assert(0 && "Unknown integer condition code!");
3757           case ICmpInst::ICMP_EQ:
3758             switch (RHSCC) {
3759             default: assert(0 && "Unknown integer condition code!");
3760             case ICmpInst::ICMP_EQ:
3761               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3762                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3763                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3764                                                       LHSVal->getName()+".off");
3765                 InsertNewInstBefore(Add, I);
3766                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3767                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3768               }
3769               break;                         // (X == 13 | X == 15) -> no change
3770             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3771             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3772               break;
3773             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3774             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3775             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3776               return ReplaceInstUsesWith(I, RHS);
3777             }
3778             break;
3779           case ICmpInst::ICMP_NE:
3780             switch (RHSCC) {
3781             default: assert(0 && "Unknown integer condition code!");
3782             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3783             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3784             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3785               return ReplaceInstUsesWith(I, LHS);
3786             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3787             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3788             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3789               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3790             }
3791             break;
3792           case ICmpInst::ICMP_ULT:
3793             switch (RHSCC) {
3794             default: assert(0 && "Unknown integer condition code!");
3795             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3796               break;
3797             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3798               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3799                                      false, I);
3800             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3801               break;
3802             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3803             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3804               return ReplaceInstUsesWith(I, RHS);
3805             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3806               break;
3807             }
3808             break;
3809           case ICmpInst::ICMP_SLT:
3810             switch (RHSCC) {
3811             default: assert(0 && "Unknown integer condition code!");
3812             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3813               break;
3814             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3815               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3816                                      false, I);
3817             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3818               break;
3819             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3820             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3821               return ReplaceInstUsesWith(I, RHS);
3822             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3823               break;
3824             }
3825             break;
3826           case ICmpInst::ICMP_UGT:
3827             switch (RHSCC) {
3828             default: assert(0 && "Unknown integer condition code!");
3829             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3830             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3831               return ReplaceInstUsesWith(I, LHS);
3832             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3833               break;
3834             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3835             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3836               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3837             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3838               break;
3839             }
3840             break;
3841           case ICmpInst::ICMP_SGT:
3842             switch (RHSCC) {
3843             default: assert(0 && "Unknown integer condition code!");
3844             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3845             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3846               return ReplaceInstUsesWith(I, LHS);
3847             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3848               break;
3849             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3850             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3851               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3852             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3853               break;
3854             }
3855             break;
3856           }
3857         }
3858   }
3859     
3860   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3861   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3862     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3863       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3864         const Type *SrcTy = Op0C->getOperand(0)->getType();
3865         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3866             // Only do this if the casts both really cause code to be generated.
3867             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3868                               I.getType(), TD) &&
3869             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3870                               I.getType(), TD)) {
3871           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3872                                                         Op1C->getOperand(0),
3873                                                         I.getName());
3874           InsertNewInstBefore(NewOp, I);
3875           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3876         }
3877       }
3878       
3879
3880   return Changed ? &I : 0;
3881 }
3882
3883 // XorSelf - Implements: X ^ X --> 0
3884 struct XorSelf {
3885   Value *RHS;
3886   XorSelf(Value *rhs) : RHS(rhs) {}
3887   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3888   Instruction *apply(BinaryOperator &Xor) const {
3889     return &Xor;
3890   }
3891 };
3892
3893
3894 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3895   bool Changed = SimplifyCommutative(I);
3896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3897
3898   if (isa<UndefValue>(Op1))
3899     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3900
3901   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3902   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3903     assert(Result == &I && "AssociativeOpt didn't work?");
3904     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3905   }
3906   
3907   // See if we can simplify any instructions used by the instruction whose sole 
3908   // purpose is to compute bits we don't care about.
3909   uint64_t KnownZero, KnownOne;
3910   if (!isa<PackedType>(I.getType()) &&
3911       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3912                            KnownZero, KnownOne))
3913     return &I;
3914
3915   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3916     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3917     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3918       if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3919         return new ICmpInst(ICI->getInversePredicate(),
3920                             ICI->getOperand(0), ICI->getOperand(1));
3921
3922     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3923       // ~(c-X) == X-c-1 == X+(-c-1)
3924       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3925         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3926           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3927           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3928                                               ConstantInt::get(I.getType(), 1));
3929           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3930         }
3931
3932       // ~(~X & Y) --> (X | ~Y)
3933       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3934         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3935         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3936           Instruction *NotY =
3937             BinaryOperator::createNot(Op0I->getOperand(1),
3938                                       Op0I->getOperand(1)->getName()+".not");
3939           InsertNewInstBefore(NotY, I);
3940           return BinaryOperator::createOr(Op0NotVal, NotY);
3941         }
3942       }
3943
3944       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3945         if (Op0I->getOpcode() == Instruction::Add) {
3946           // ~(X-c) --> (-c-1)-X
3947           if (RHS->isAllOnesValue()) {
3948             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3949             return BinaryOperator::createSub(
3950                            ConstantExpr::getSub(NegOp0CI,
3951                                              ConstantInt::get(I.getType(), 1)),
3952                                           Op0I->getOperand(0));
3953           }
3954         } else if (Op0I->getOpcode() == Instruction::Or) {
3955           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3956           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3957             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3958             // Anything in both C1 and C2 is known to be zero, remove it from
3959             // NewRHS.
3960             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3961             NewRHS = ConstantExpr::getAnd(NewRHS, 
3962                                           ConstantExpr::getNot(CommonBits));
3963             WorkList.push_back(Op0I);
3964             I.setOperand(0, Op0I->getOperand(0));
3965             I.setOperand(1, NewRHS);
3966             return &I;
3967           }
3968         }
3969     }
3970
3971     // Try to fold constant and into select arguments.
3972     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3973       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3974         return R;
3975     if (isa<PHINode>(Op0))
3976       if (Instruction *NV = FoldOpIntoPhi(I))
3977         return NV;
3978   }
3979
3980   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3981     if (X == Op1)
3982       return ReplaceInstUsesWith(I,
3983                                 ConstantIntegral::getAllOnesValue(I.getType()));
3984
3985   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3986     if (X == Op0)
3987       return ReplaceInstUsesWith(I,
3988                                 ConstantIntegral::getAllOnesValue(I.getType()));
3989
3990   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3991     if (Op1I->getOpcode() == Instruction::Or) {
3992       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3993         Op1I->swapOperands();
3994         I.swapOperands();
3995         std::swap(Op0, Op1);
3996       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3997         I.swapOperands();     // Simplified below.
3998         std::swap(Op0, Op1);
3999       }
4000     } else if (Op1I->getOpcode() == Instruction::Xor) {
4001       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
4002         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4003       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
4004         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
4005     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4006       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
4007         Op1I->swapOperands();
4008       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
4009         I.swapOperands();     // Simplified below.
4010         std::swap(Op0, Op1);
4011       }
4012     }
4013
4014   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4015     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4016       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4017         Op0I->swapOperands();
4018       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4019         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4020         InsertNewInstBefore(NotB, I);
4021         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4022       }
4023     } else if (Op0I->getOpcode() == Instruction::Xor) {
4024       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4025         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4026       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4027         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4028     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4029       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4030         Op0I->swapOperands();
4031       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4032           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4033         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4034         InsertNewInstBefore(N, I);
4035         return BinaryOperator::createAnd(N, Op1);
4036       }
4037     }
4038
4039   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4040   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4041     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4042       return R;
4043
4044   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4045   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4046     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4047       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4048         const Type *SrcTy = Op0C->getOperand(0)->getType();
4049         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4050             // Only do this if the casts both really cause code to be generated.
4051             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4052                               I.getType(), TD) &&
4053             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4054                               I.getType(), TD)) {
4055           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4056                                                          Op1C->getOperand(0),
4057                                                          I.getName());
4058           InsertNewInstBefore(NewOp, I);
4059           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4060         }
4061       }
4062
4063   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4064   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4065     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4066       if (SI0->getOpcode() == SI1->getOpcode() && 
4067           SI0->getOperand(1) == SI1->getOperand(1) &&
4068           (SI0->hasOneUse() || SI1->hasOneUse())) {
4069         Instruction *NewOp =
4070         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4071                                                       SI1->getOperand(0),
4072                                                       SI0->getName()), I);
4073         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4074       }
4075   }
4076     
4077   return Changed ? &I : 0;
4078 }
4079
4080 static bool isPositive(ConstantInt *C) {
4081   return C->getSExtValue() >= 0;
4082 }
4083
4084 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4085 /// overflowed for this type.
4086 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4087                             ConstantInt *In2) {
4088   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4089
4090   if (In1->getType()->isUnsigned())
4091     return cast<ConstantInt>(Result)->getZExtValue() <
4092            cast<ConstantInt>(In1)->getZExtValue();
4093   if (isPositive(In1) != isPositive(In2))
4094     return false;
4095   if (isPositive(In1))
4096     return cast<ConstantInt>(Result)->getSExtValue() <
4097            cast<ConstantInt>(In1)->getSExtValue();
4098   return cast<ConstantInt>(Result)->getSExtValue() >
4099          cast<ConstantInt>(In1)->getSExtValue();
4100 }
4101
4102 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4103 /// code necessary to compute the offset from the base pointer (without adding
4104 /// in the base pointer).  Return the result as a signed integer of intptr size.
4105 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4106   TargetData &TD = IC.getTargetData();
4107   gep_type_iterator GTI = gep_type_begin(GEP);
4108   const Type *IntPtrTy = TD.getIntPtrType();
4109   Value *Result = Constant::getNullValue(IntPtrTy);
4110
4111   // Build a mask for high order bits.
4112   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4113
4114   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4115     Value *Op = GEP->getOperand(i);
4116     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4117     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4118     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4119       if (!OpC->isNullValue()) {
4120         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4121         Scale = ConstantExpr::getMul(OpC, Scale);
4122         if (Constant *RC = dyn_cast<Constant>(Result))
4123           Result = ConstantExpr::getAdd(RC, Scale);
4124         else {
4125           // Emit an add instruction.
4126           Result = IC.InsertNewInstBefore(
4127              BinaryOperator::createAdd(Result, Scale,
4128                                        GEP->getName()+".offs"), I);
4129         }
4130       }
4131     } else {
4132       // Convert to correct type.
4133       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4134                                                Op->getName()+".c"), I);
4135       if (Size != 1)
4136         // We'll let instcombine(mul) convert this to a shl if possible.
4137         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4138                                                     GEP->getName()+".idx"), I);
4139
4140       // Emit an add instruction.
4141       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4142                                                     GEP->getName()+".offs"), I);
4143     }
4144   }
4145   return Result;
4146 }
4147
4148 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4149 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4150 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4151                                        ICmpInst::Predicate Cond,
4152                                        Instruction &I) {
4153   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4154
4155   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4156     if (isa<PointerType>(CI->getOperand(0)->getType()))
4157       RHS = CI->getOperand(0);
4158
4159   Value *PtrBase = GEPLHS->getOperand(0);
4160   if (PtrBase == RHS) {
4161     // As an optimization, we don't actually have to compute the actual value of
4162     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4163     // each index is zero or not.
4164     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4165       Instruction *InVal = 0;
4166       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4167       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4168         bool EmitIt = true;
4169         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4170           if (isa<UndefValue>(C))  // undef index -> undef.
4171             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4172           if (C->isNullValue())
4173             EmitIt = false;
4174           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4175             EmitIt = false;  // This is indexing into a zero sized array?
4176           } else if (isa<ConstantInt>(C))
4177             return ReplaceInstUsesWith(I, // No comparison is needed here.
4178                                  ConstantBool::get(Cond == ICmpInst::ICMP_NE));
4179         }
4180
4181         if (EmitIt) {
4182           Instruction *Comp =
4183             new ICmpInst(Cond, GEPLHS->getOperand(i),
4184                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4185           if (InVal == 0)
4186             InVal = Comp;
4187           else {
4188             InVal = InsertNewInstBefore(InVal, I);
4189             InsertNewInstBefore(Comp, I);
4190             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4191               InVal = BinaryOperator::createOr(InVal, Comp);
4192             else                              // True if all are equal
4193               InVal = BinaryOperator::createAnd(InVal, Comp);
4194           }
4195         }
4196       }
4197
4198       if (InVal)
4199         return InVal;
4200       else
4201         // No comparison is needed here, all indexes = 0
4202         ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4203     }
4204
4205     // Only lower this if the icmp is the only user of the GEP or if we expect
4206     // the result to fold to a constant!
4207     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4208       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4209       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4210       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4211                           Constant::getNullValue(Offset->getType()));
4212     }
4213   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4214     // If the base pointers are different, but the indices are the same, just
4215     // compare the base pointer.
4216     if (PtrBase != GEPRHS->getOperand(0)) {
4217       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4218       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4219                         GEPRHS->getOperand(0)->getType();
4220       if (IndicesTheSame)
4221         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4222           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4223             IndicesTheSame = false;
4224             break;
4225           }
4226
4227       // If all indices are the same, just compare the base pointers.
4228       if (IndicesTheSame)
4229         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4230                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4231
4232       // Otherwise, the base pointers are different and the indices are
4233       // different, bail out.
4234       return 0;
4235     }
4236
4237     // If one of the GEPs has all zero indices, recurse.
4238     bool AllZeros = true;
4239     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4240       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4241           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4242         AllZeros = false;
4243         break;
4244       }
4245     if (AllZeros)
4246       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4247                           ICmpInst::getSwappedPredicate(Cond), I);
4248
4249     // If the other GEP has all zero indices, recurse.
4250     AllZeros = true;
4251     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4252       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4253           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4254         AllZeros = false;
4255         break;
4256       }
4257     if (AllZeros)
4258       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4259
4260     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4261       // If the GEPs only differ by one index, compare it.
4262       unsigned NumDifferences = 0;  // Keep track of # differences.
4263       unsigned DiffOperand = 0;     // The operand that differs.
4264       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4265         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4266           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4267                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4268             // Irreconcilable differences.
4269             NumDifferences = 2;
4270             break;
4271           } else {
4272             if (NumDifferences++) break;
4273             DiffOperand = i;
4274           }
4275         }
4276
4277       if (NumDifferences == 0)   // SAME GEP?
4278         return ReplaceInstUsesWith(I, // No comparison is needed here.
4279                                  ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4280       else if (NumDifferences == 1) {
4281         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4282         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4283         if (LHSV->getType() != RHSV->getType())
4284           // Doesn't matter which one we bitconvert here.
4285           LHSV = InsertCastBefore(Instruction::BitCast, LHSV, RHSV->getType(),
4286                                   I);
4287         // Make sure we do a signed comparison here.
4288         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4289       }
4290     }
4291
4292     // Only lower this if the icmp is the only user of the GEP or if we expect
4293     // the result to fold to a constant!
4294     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4295         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4296       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4297       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4298       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4299       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4300     }
4301   }
4302   return 0;
4303 }
4304
4305 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4306   bool Changed = SimplifyCompare(I);
4307   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4308
4309   // fcmp pred X, X
4310   if (Op0 == Op1)
4311     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4312
4313   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4314     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4315
4316   // Handle fcmp with constant RHS
4317   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4318     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4319       switch (LHSI->getOpcode()) {
4320       case Instruction::PHI:
4321         if (Instruction *NV = FoldOpIntoPhi(I))
4322           return NV;
4323         break;
4324       case Instruction::Select:
4325         // If either operand of the select is a constant, we can fold the
4326         // comparison into the select arms, which will cause one to be
4327         // constant folded and the select turned into a bitwise or.
4328         Value *Op1 = 0, *Op2 = 0;
4329         if (LHSI->hasOneUse()) {
4330           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4331             // Fold the known value into the constant operand.
4332             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4333             // Insert a new FCmp of the other select operand.
4334             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4335                                                       LHSI->getOperand(2), RHSC,
4336                                                       I.getName()), I);
4337           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4338             // Fold the known value into the constant operand.
4339             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4340             // Insert a new FCmp of the other select operand.
4341             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4342                                                       LHSI->getOperand(1), RHSC,
4343                                                       I.getName()), I);
4344           }
4345         }
4346
4347         if (Op1)
4348           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4349         break;
4350       }
4351   }
4352
4353   return Changed ? &I : 0;
4354 }
4355
4356 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4357   bool Changed = SimplifyCompare(I);
4358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4359   const Type *Ty = Op0->getType();
4360
4361   // icmp X, X
4362   if (Op0 == Op1)
4363     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4364
4365   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4366     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4367
4368   // icmp of GlobalValues can never equal each other as long as they aren't
4369   // external weak linkage type.
4370   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4371     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4372       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4373         return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4374
4375   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4376   // addresses never equal each other!  We already know that Op0 != Op1.
4377   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4378        isa<ConstantPointerNull>(Op0)) &&
4379       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4380        isa<ConstantPointerNull>(Op1)))
4381     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4382
4383   // icmp's with boolean values can always be turned into bitwise operations
4384   if (Ty == Type::BoolTy) {
4385     switch (I.getPredicate()) {
4386     default: assert(0 && "Invalid icmp instruction!");
4387     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4388       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4389       InsertNewInstBefore(Xor, I);
4390       return BinaryOperator::createNot(Xor);
4391     }
4392     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4393       return BinaryOperator::createXor(Op0, Op1);
4394
4395     case ICmpInst::ICMP_UGT:
4396     case ICmpInst::ICMP_SGT:
4397       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4398       // FALL THROUGH
4399     case ICmpInst::ICMP_ULT:
4400     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4401       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4402       InsertNewInstBefore(Not, I);
4403       return BinaryOperator::createAnd(Not, Op1);
4404     }
4405     case ICmpInst::ICMP_UGE:
4406     case ICmpInst::ICMP_SGE:
4407       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4408       // FALL THROUGH
4409     case ICmpInst::ICMP_ULE:
4410     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4411       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4412       InsertNewInstBefore(Not, I);
4413       return BinaryOperator::createOr(Not, Op1);
4414     }
4415     }
4416   }
4417
4418   // See if we are doing a comparison between a constant and an instruction that
4419   // can be folded into the comparison.
4420   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4421     switch (I.getPredicate()) {
4422     default: break;
4423     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4424       if (CI->isMinValue(false))
4425         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4426       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4427         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4428       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4429         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4430       break;
4431
4432     case ICmpInst::ICMP_SLT:
4433       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4434         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4435       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4436         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4437       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4438         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4439       break;
4440
4441     case ICmpInst::ICMP_UGT:
4442       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4443         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4444       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4445         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4446       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4447         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4448       break;
4449
4450     case ICmpInst::ICMP_SGT:
4451       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4452         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4453       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4454         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4455       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4456         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4457       break;
4458
4459     case ICmpInst::ICMP_ULE:
4460       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4461         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4462       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4463         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4464       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4465         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4466       break;
4467
4468     case ICmpInst::ICMP_SLE:
4469       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4470         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4471       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4472         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4473       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4474         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4475       break;
4476
4477     case ICmpInst::ICMP_UGE:
4478       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4479         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4480       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4481         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4482       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4483         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4484       break;
4485
4486     case ICmpInst::ICMP_SGE:
4487       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4488         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4489       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4490         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4491       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4492         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4493       break;
4494     }
4495
4496     // If we still have a icmp le or icmp ge instruction, turn it into the
4497     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4498     // already been handled above, this requires little checking.
4499     //
4500     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4501       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4502     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4503       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4504     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4505       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4506     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4507       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4508     
4509     // See if we can fold the comparison based on bits known to be zero or one
4510     // in the input.
4511     uint64_t KnownZero, KnownOne;
4512     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4513                              KnownZero, KnownOne, 0))
4514       return &I;
4515         
4516     // Given the known and unknown bits, compute a range that the LHS could be
4517     // in.
4518     if (KnownOne | KnownZero) {
4519       // Compute the Min, Max and RHS values based on the known bits. For the
4520       // EQ and NE we use unsigned values.
4521       uint64_t UMin, UMax, URHSVal;
4522       int64_t SMin, SMax, SRHSVal;
4523       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4524         SRHSVal = CI->getSExtValue();
4525         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4526                                                SMax);
4527       } else {
4528         URHSVal = CI->getZExtValue();
4529         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4530                                                  UMax);
4531       }
4532       switch (I.getPredicate()) {  // LE/GE have been folded already.
4533       default: assert(0 && "Unknown icmp opcode!");
4534       case ICmpInst::ICMP_EQ:
4535         if (UMax < URHSVal || UMin > URHSVal)
4536           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4537         break;
4538       case ICmpInst::ICMP_NE:
4539         if (UMax < URHSVal || UMin > URHSVal)
4540           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4541         break;
4542       case ICmpInst::ICMP_ULT:
4543         if (UMax < URHSVal)
4544           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4545         if (UMin > URHSVal)
4546           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4547         break;
4548       case ICmpInst::ICMP_UGT:
4549         if (UMin > URHSVal)
4550           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4551         if (UMax < URHSVal)
4552           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4553         break;
4554       case ICmpInst::ICMP_SLT:
4555         if (SMax < SRHSVal)
4556           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4557         if (SMin > SRHSVal)
4558           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4559         break;
4560       case ICmpInst::ICMP_SGT: 
4561         if (SMin > SRHSVal)
4562           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4563         if (SMax < SRHSVal)
4564           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4565         break;
4566       }
4567     }
4568           
4569     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4570     // instruction, see if that instruction also has constants so that the 
4571     // instruction can be folded into the icmp 
4572     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4573       switch (LHSI->getOpcode()) {
4574       case Instruction::And:
4575         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4576             LHSI->getOperand(0)->hasOneUse()) {
4577           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4578
4579           // If the LHS is an AND of a truncating cast, we can widen the
4580           // and/compare to be the input width without changing the value
4581           // produced, eliminating a cast.
4582           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4583             // We can do this transformation if either the AND constant does not
4584             // have its sign bit set or if it is an equality comparison. 
4585             // Extending a relational comparison when we're checking the sign
4586             // bit would not work.
4587             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4588                 (I.isEquality() ||
4589                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4590                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4591               ConstantInt *NewCST;
4592               ConstantInt *NewCI;
4593               if (Cast->getOperand(0)->getType()->isSigned()) {
4594                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4595                                            AndCST->getZExtValue());
4596                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4597                                           CI->getZExtValue());
4598               } else {
4599                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4600                                            AndCST->getZExtValue());
4601                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4602                                           CI->getZExtValue());
4603               }
4604               Instruction *NewAnd = 
4605                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4606                                           LHSI->getName());
4607               InsertNewInstBefore(NewAnd, I);
4608               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4609             }
4610           }
4611           
4612           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4613           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4614           // happens a LOT in code produced by the C front-end, for bitfield
4615           // access.
4616           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4617
4618           // Check to see if there is a noop-cast between the shift and the and.
4619           if (!Shift) {
4620             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4621               if (CI->getOpcode() == Instruction::BitCast)
4622                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4623           }
4624
4625           ConstantInt *ShAmt;
4626           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4627           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4628           const Type *AndTy = AndCST->getType();          // Type of the and.
4629
4630           // We can fold this as long as we can't shift unknown bits
4631           // into the mask.  This can only happen with signed shift
4632           // rights, as they sign-extend.
4633           if (ShAmt) {
4634             bool CanFold = Shift->isLogicalShift();
4635             if (!CanFold) {
4636               // To test for the bad case of the signed shr, see if any
4637               // of the bits shifted in could be tested after the mask.
4638               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4639               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4640
4641               Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4642               Constant *ShVal =
4643                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4644                                      OShAmt);
4645               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4646                 CanFold = true;
4647             }
4648
4649             if (CanFold) {
4650               Constant *NewCst;
4651               if (Shift->getOpcode() == Instruction::Shl)
4652                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4653               else
4654                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4655
4656               // Check to see if we are shifting out any of the bits being
4657               // compared.
4658               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4659                 // If we shifted bits out, the fold is not going to work out.
4660                 // As a special case, check to see if this means that the
4661                 // result is always true or false now.
4662                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4663                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4664                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4665                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4666               } else {
4667                 I.setOperand(1, NewCst);
4668                 Constant *NewAndCST;
4669                 if (Shift->getOpcode() == Instruction::Shl)
4670                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4671                 else
4672                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4673                 LHSI->setOperand(1, NewAndCST);
4674                 if (AndTy == Ty) 
4675                   LHSI->setOperand(0, Shift->getOperand(0));
4676                 else {
4677                   Value *NewCast = InsertCastBefore(Instruction::BitCast,
4678                                                     Shift->getOperand(0), AndTy,
4679                                                     *Shift);
4680                   LHSI->setOperand(0, NewCast);
4681                 }
4682                 WorkList.push_back(Shift); // Shift is dead.
4683                 AddUsesToWorkList(I);
4684                 return &I;
4685               }
4686             }
4687           }
4688           
4689           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4690           // preferable because it allows the C<<Y expression to be hoisted out
4691           // of a loop if Y is invariant and X is not.
4692           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4693               I.isEquality() && !Shift->isArithmeticShift() &&
4694               isa<Instruction>(Shift->getOperand(0))) {
4695             // Compute C << Y.
4696             Value *NS;
4697             if (Shift->getOpcode() == Instruction::LShr) {
4698               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4699                                  "tmp");
4700             } else {
4701               // Insert a logical shift.
4702               NS = new ShiftInst(Instruction::LShr, AndCST,
4703                                  Shift->getOperand(1), "tmp");
4704             }
4705             InsertNewInstBefore(cast<Instruction>(NS), I);
4706
4707             // If C's sign doesn't agree with the and, insert a cast now.
4708             if (NS->getType() != LHSI->getType())
4709               NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4710                                     I);
4711
4712             Value *ShiftOp = Shift->getOperand(0);
4713             if (ShiftOp->getType() != LHSI->getType())
4714               ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp, 
4715                                          LHSI->getType(), I);
4716               
4717             // Compute X & (C << Y).
4718             Instruction *NewAnd =
4719               BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4720             InsertNewInstBefore(NewAnd, I);
4721             
4722             I.setOperand(0, NewAnd);
4723             return &I;
4724           }
4725         }
4726         break;
4727
4728       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4729         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4730           if (I.isEquality()) {
4731             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4732
4733             // Check that the shift amount is in range.  If not, don't perform
4734             // undefined shifts.  When the shift is visited it will be
4735             // simplified.
4736             if (ShAmt->getZExtValue() >= TypeBits)
4737               break;
4738
4739             // If we are comparing against bits always shifted out, the
4740             // comparison cannot succeed.
4741             Constant *Comp =
4742               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4743             if (Comp != CI) {// Comparing against a bit that we know is zero.
4744               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4745               Constant *Cst = ConstantBool::get(IsICMP_NE);
4746               return ReplaceInstUsesWith(I, Cst);
4747             }
4748
4749             if (LHSI->hasOneUse()) {
4750               // Otherwise strength reduce the shift into an and.
4751               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4752               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4753
4754               Constant *Mask;
4755               if (CI->getType()->isUnsigned()) {
4756                 Mask = ConstantInt::get(CI->getType(), Val);
4757               } else if (ShAmtVal != 0) {
4758                 Mask = ConstantInt::get(CI->getType(), Val);
4759               } else {
4760                 Mask = ConstantInt::getAllOnesValue(CI->getType());
4761               }
4762
4763               Instruction *AndI =
4764                 BinaryOperator::createAnd(LHSI->getOperand(0),
4765                                           Mask, LHSI->getName()+".mask");
4766               Value *And = InsertNewInstBefore(AndI, I);
4767               return new ICmpInst(I.getPredicate(), And,
4768                                      ConstantExpr::getLShr(CI, ShAmt));
4769             }
4770           }
4771         }
4772         break;
4773
4774       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4775       case Instruction::AShr:
4776         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4777           if (I.isEquality()) {
4778             // Check that the shift amount is in range.  If not, don't perform
4779             // undefined shifts.  When the shift is visited it will be
4780             // simplified.
4781             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4782             if (ShAmt->getZExtValue() >= TypeBits)
4783               break;
4784
4785             // If we are comparing against bits always shifted out, the
4786             // comparison cannot succeed.
4787             Constant *Comp;
4788             if (CI->getType()->isUnsigned())
4789               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4790                                            ShAmt);
4791             else
4792               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4793                                            ShAmt);
4794
4795             if (Comp != CI) {// Comparing against a bit that we know is zero.
4796               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4797               Constant *Cst = ConstantBool::get(IsICMP_NE);
4798               return ReplaceInstUsesWith(I, Cst);
4799             }
4800
4801             if (LHSI->hasOneUse() || CI->isNullValue()) {
4802               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4803
4804               // Otherwise strength reduce the shift into an and.
4805               uint64_t Val = ~0ULL;          // All ones.
4806               Val <<= ShAmtVal;              // Shift over to the right spot.
4807
4808               Constant *Mask;
4809               if (CI->getType()->isUnsigned()) {
4810                 Val &= ~0ULL >> (64-TypeBits);
4811                 Mask = ConstantInt::get(CI->getType(), Val);
4812               } else {
4813                 Mask = ConstantInt::get(CI->getType(), Val);
4814               }
4815
4816               Instruction *AndI =
4817                 BinaryOperator::createAnd(LHSI->getOperand(0),
4818                                           Mask, LHSI->getName()+".mask");
4819               Value *And = InsertNewInstBefore(AndI, I);
4820               return new ICmpInst(I.getPredicate(), And,
4821                                      ConstantExpr::getShl(CI, ShAmt));
4822             }
4823           }
4824         }
4825         break;
4826
4827       case Instruction::SDiv:
4828       case Instruction::UDiv:
4829         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4830         // Fold this div into the comparison, producing a range check. 
4831         // Determine, based on the divide type, what the range is being 
4832         // checked.  If there is an overflow on the low or high side, remember 
4833         // it, otherwise compute the range [low, hi) bounding the new value.
4834         // See: InsertRangeTest above for the kinds of replacements possible.
4835         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4836           // FIXME: If the operand types don't match the type of the divide 
4837           // then don't attempt this transform. The code below doesn't have the
4838           // logic to deal with a signed divide and an unsigned compare (and
4839           // vice versa). This is because (x /s C1) <s C2  produces different 
4840           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4841           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4842           // work. :(  The if statement below tests that condition and bails 
4843           // if it finds it. 
4844           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4845           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4846             break;
4847
4848           // Initialize the variables that will indicate the nature of the
4849           // range check.
4850           bool LoOverflow = false, HiOverflow = false;
4851           ConstantInt *LoBound = 0, *HiBound = 0;
4852
4853           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4854           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4855           // C2 (CI). By solving for X we can turn this into a range check 
4856           // instead of computing a divide. 
4857           ConstantInt *Prod = 
4858             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4859
4860           // Determine if the product overflows by seeing if the product is
4861           // not equal to the divide. Make sure we do the same kind of divide
4862           // as in the LHS instruction that we're folding. 
4863           bool ProdOV = !DivRHS->isNullValue() && 
4864             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4865               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4866
4867           // Get the ICmp opcode
4868           ICmpInst::Predicate predicate = I.getPredicate();
4869
4870           if (DivRHS->isNullValue()) {  
4871             // Don't hack on divide by zeros!
4872           } else if (!DivIsSigned) {  // udiv
4873             LoBound = Prod;
4874             LoOverflow = ProdOV;
4875             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4876           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4877             if (CI->isNullValue()) {       // (X / pos) op 0
4878               // Can't overflow.
4879               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4880               HiBound = DivRHS;
4881             } else if (isPositive(CI)) {   // (X / pos) op pos
4882               LoBound = Prod;
4883               LoOverflow = ProdOV;
4884               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4885             } else {                       // (X / pos) op neg
4886               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4887               LoOverflow = AddWithOverflow(LoBound, Prod,
4888                                            cast<ConstantInt>(DivRHSH));
4889               HiBound = Prod;
4890               HiOverflow = ProdOV;
4891             }
4892           } else {                         // Divisor is < 0.
4893             if (CI->isNullValue()) {       // (X / neg) op 0
4894               LoBound = AddOne(DivRHS);
4895               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4896               if (HiBound == DivRHS)
4897                 LoBound = 0;               // - INTMIN = INTMIN
4898             } else if (isPositive(CI)) {   // (X / neg) op pos
4899               HiOverflow = LoOverflow = ProdOV;
4900               if (!LoOverflow)
4901                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4902               HiBound = AddOne(Prod);
4903             } else {                       // (X / neg) op neg
4904               LoBound = Prod;
4905               LoOverflow = HiOverflow = ProdOV;
4906               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4907             }
4908
4909             // Dividing by a negate swaps the condition.
4910             predicate = ICmpInst::getSwappedPredicate(predicate);
4911           }
4912
4913           if (LoBound) {
4914             Value *X = LHSI->getOperand(0);
4915             switch (predicate) {
4916             default: assert(0 && "Unhandled icmp opcode!");
4917             case ICmpInst::ICMP_EQ:
4918               if (LoOverflow && HiOverflow)
4919                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4920               else if (HiOverflow)
4921                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4922                                     ICmpInst::ICMP_UGE, X, LoBound);
4923               else if (LoOverflow)
4924                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4925                                     ICmpInst::ICMP_ULT, X, HiBound);
4926               else
4927                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4928                                        true, I);
4929             case ICmpInst::ICMP_NE:
4930               if (LoOverflow && HiOverflow)
4931                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4932               else if (HiOverflow)
4933                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4934                                     ICmpInst::ICMP_ULT, X, LoBound);
4935               else if (LoOverflow)
4936                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4937                                     ICmpInst::ICMP_UGE, X, HiBound);
4938               else
4939                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4940                                        false, I);
4941             case ICmpInst::ICMP_ULT:
4942             case ICmpInst::ICMP_SLT:
4943               if (LoOverflow)
4944                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4945               return new ICmpInst(predicate, X, LoBound);
4946             case ICmpInst::ICMP_UGT:
4947             case ICmpInst::ICMP_SGT:
4948               if (HiOverflow)
4949                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4950               if (predicate == ICmpInst::ICMP_UGT)
4951                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4952               else
4953                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4954             }
4955           }
4956         }
4957         break;
4958       }
4959
4960     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4961     if (I.isEquality()) {
4962       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4963
4964       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4965       // the second operand is a constant, simplify a bit.
4966       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4967         switch (BO->getOpcode()) {
4968         case Instruction::SRem:
4969           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4970           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4971               BO->hasOneUse()) {
4972             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4973             if (V > 1 && isPowerOf2_64(V)) {
4974               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4975                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4976               return new ICmpInst(I.getPredicate(), NewRem, 
4977                                   Constant::getNullValue(BO->getType()));
4978             }
4979           }
4980           break;
4981         case Instruction::Add:
4982           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4983           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4984             if (BO->hasOneUse())
4985               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4986                                   ConstantExpr::getSub(CI, BOp1C));
4987           } else if (CI->isNullValue()) {
4988             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4989             // efficiently invertible, or if the add has just this one use.
4990             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4991
4992             if (Value *NegVal = dyn_castNegVal(BOp1))
4993               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4994             else if (Value *NegVal = dyn_castNegVal(BOp0))
4995               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4996             else if (BO->hasOneUse()) {
4997               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4998               BO->setName("");
4999               InsertNewInstBefore(Neg, I);
5000               return new ICmpInst(I.getPredicate(), BOp0, Neg);
5001             }
5002           }
5003           break;
5004         case Instruction::Xor:
5005           // For the xor case, we can xor two constants together, eliminating
5006           // the explicit xor.
5007           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5008             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
5009                                 ConstantExpr::getXor(CI, BOC));
5010
5011           // FALLTHROUGH
5012         case Instruction::Sub:
5013           // Replace (([sub|xor] A, B) != 0) with (A != B)
5014           if (CI->isNullValue())
5015             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5016                                 BO->getOperand(1));
5017           break;
5018
5019         case Instruction::Or:
5020           // If bits are being or'd in that are not present in the constant we
5021           // are comparing against, then the comparison could never succeed!
5022           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5023             Constant *NotCI = ConstantExpr::getNot(CI);
5024             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5025               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
5026           }
5027           break;
5028
5029         case Instruction::And:
5030           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5031             // If bits are being compared against that are and'd out, then the
5032             // comparison can never succeed!
5033             if (!ConstantExpr::getAnd(CI,
5034                                       ConstantExpr::getNot(BOC))->isNullValue())
5035               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
5036
5037             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5038             if (CI == BOC && isOneBitSet(CI))
5039               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5040                                   ICmpInst::ICMP_NE, Op0,
5041                                   Constant::getNullValue(CI->getType()));
5042
5043             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5044             if (isSignBit(BOC)) {
5045               Value *X = BO->getOperand(0);
5046               // If 'X' is not signed, insert a cast now...
5047               if (!BOC->getType()->isSigned()) {
5048                 const Type *DestTy = BOC->getType()->getSignedVersion();
5049                 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
5050               }
5051               Constant *Zero = Constant::getNullValue(X->getType());
5052               ICmpInst::Predicate pred = isICMP_NE ? 
5053                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5054               return new ICmpInst(pred, X, Zero);
5055             }
5056
5057             // ((X & ~7) == 0) --> X < 8
5058             if (CI->isNullValue() && isHighOnes(BOC)) {
5059               Value *X = BO->getOperand(0);
5060               Constant *NegX = ConstantExpr::getNeg(BOC);
5061               ICmpInst::Predicate pred = isICMP_NE ? 
5062                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5063               return new ICmpInst(pred, X, NegX);
5064             }
5065
5066           }
5067         default: break;
5068         }
5069       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5070         // Handle set{eq|ne} <intrinsic>, intcst.
5071         switch (II->getIntrinsicID()) {
5072         default: break;
5073         case Intrinsic::bswap_i16: 
5074           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5075           WorkList.push_back(II);  // Dead?
5076           I.setOperand(0, II->getOperand(1));
5077           I.setOperand(1, ConstantInt::get(Type::UShortTy,
5078                                            ByteSwap_16(CI->getZExtValue())));
5079           return &I;
5080         case Intrinsic::bswap_i32:   
5081           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5082           WorkList.push_back(II);  // Dead?
5083           I.setOperand(0, II->getOperand(1));
5084           I.setOperand(1, ConstantInt::get(Type::UIntTy,
5085                                            ByteSwap_32(CI->getZExtValue())));
5086           return &I;
5087         case Intrinsic::bswap_i64:   
5088           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5089           WorkList.push_back(II);  // Dead?
5090           I.setOperand(0, II->getOperand(1));
5091           I.setOperand(1, ConstantInt::get(Type::ULongTy,
5092                                            ByteSwap_64(CI->getZExtValue())));
5093           return &I;
5094         }
5095       }
5096     } else {  // Not a ICMP_EQ/ICMP_NE
5097       // If the LHS is a cast from an integral value of the same size, then 
5098       // since we know the RHS is a constant, try to simlify.
5099       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5100         Value *CastOp = Cast->getOperand(0);
5101         const Type *SrcTy = CastOp->getType();
5102         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5103         if (SrcTy->isInteger() && 
5104             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5105           // If this is an unsigned comparison, try to make the comparison use
5106           // smaller constant values.
5107           switch (I.getPredicate()) {
5108             default: break;
5109             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5110               ConstantInt *CUI = cast<ConstantInt>(CI);
5111               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5112                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5113                                     ConstantInt::get(SrcTy, -1));
5114               break;
5115             }
5116             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5117               ConstantInt *CUI = cast<ConstantInt>(CI);
5118               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5119                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5120                                     Constant::getNullValue(SrcTy));
5121               break;
5122             }
5123           }
5124
5125         }
5126       }
5127     }
5128   }
5129
5130   // Handle icmp with constant RHS
5131   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5132     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5133       switch (LHSI->getOpcode()) {
5134       case Instruction::GetElementPtr:
5135         if (RHSC->isNullValue()) {
5136           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5137           bool isAllZeros = true;
5138           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5139             if (!isa<Constant>(LHSI->getOperand(i)) ||
5140                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5141               isAllZeros = false;
5142               break;
5143             }
5144           if (isAllZeros)
5145             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5146                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5147         }
5148         break;
5149
5150       case Instruction::PHI:
5151         if (Instruction *NV = FoldOpIntoPhi(I))
5152           return NV;
5153         break;
5154       case Instruction::Select:
5155         // If either operand of the select is a constant, we can fold the
5156         // comparison into the select arms, which will cause one to be
5157         // constant folded and the select turned into a bitwise or.
5158         Value *Op1 = 0, *Op2 = 0;
5159         if (LHSI->hasOneUse()) {
5160           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5161             // Fold the known value into the constant operand.
5162             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5163             // Insert a new ICmp of the other select operand.
5164             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5165                                                    LHSI->getOperand(2), RHSC,
5166                                                    I.getName()), I);
5167           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5168             // Fold the known value into the constant operand.
5169             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5170             // Insert a new ICmp of the other select operand.
5171             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5172                                                    LHSI->getOperand(1), RHSC,
5173                                                    I.getName()), I);
5174           }
5175         }
5176
5177         if (Op1)
5178           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5179         break;
5180       }
5181   }
5182
5183   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5184   if (User *GEP = dyn_castGetElementPtr(Op0))
5185     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5186       return NI;
5187   if (User *GEP = dyn_castGetElementPtr(Op1))
5188     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5189                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5190       return NI;
5191
5192   // Test to see if the operands of the icmp are casted versions of other
5193   // values.  If the cast can be stripped off both arguments, we do so now.
5194   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5195     Value *CastOp0 = CI->getOperand(0);
5196     if (CI->isLosslessCast() && I.isEquality() && 
5197         (isa<Constant>(Op1) || isa<CastInst>(Op1))) { 
5198       // We keep moving the cast from the left operand over to the right
5199       // operand, where it can often be eliminated completely.
5200       Op0 = CastOp0;
5201
5202       // If operand #1 is a cast instruction, see if we can eliminate it as
5203       // well.
5204       if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) { 
5205         Value *CI2Op0 = CI2->getOperand(0);
5206         if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5207           Op1 = CI2Op0;
5208       }
5209
5210       // If Op1 is a constant, we can fold the cast into the constant.
5211       if (Op1->getType() != Op0->getType())
5212         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5213           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5214         } else {
5215           // Otherwise, cast the RHS right before the icmp
5216           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5217         }
5218       return new ICmpInst(I.getPredicate(), Op0, Op1);
5219     }
5220
5221     // Handle the special case of: icmp (cast bool to X), <cst>
5222     // This comes up when you have code like
5223     //   int X = A < B;
5224     //   if (X) ...
5225     // For generality, we handle any zero-extension of any operand comparison
5226     // with a constant or another cast from the same type.
5227     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5228       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5229         return R;
5230   }
5231   
5232   if (I.isEquality()) {
5233     Value *A, *B;
5234     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
5235         (A == Op1 || B == Op1)) {
5236       // (A^B) == A  ->  B == 0
5237       Value *OtherVal = A == Op1 ? B : A;
5238       return new ICmpInst(I.getPredicate(), OtherVal,
5239                           Constant::getNullValue(A->getType()));
5240     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5241                (A == Op0 || B == Op0)) {
5242       // A == (A^B)  ->  B == 0
5243       Value *OtherVal = A == Op0 ? B : A;
5244       return new ICmpInst(I.getPredicate(), OtherVal,
5245                           Constant::getNullValue(A->getType()));
5246     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5247       // (A-B) == A  ->  B == 0
5248       return new ICmpInst(I.getPredicate(), B,
5249                           Constant::getNullValue(B->getType()));
5250     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5251       // A == (A-B)  ->  B == 0
5252       return new ICmpInst(I.getPredicate(), B,
5253                           Constant::getNullValue(B->getType()));
5254     }
5255     
5256     Value *C, *D;
5257     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5258     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5259         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5260         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5261       Value *X = 0, *Y = 0, *Z = 0;
5262       
5263       if (A == C) {
5264         X = B; Y = D; Z = A;
5265       } else if (A == D) {
5266         X = B; Y = C; Z = A;
5267       } else if (B == C) {
5268         X = A; Y = D; Z = B;
5269       } else if (B == D) {
5270         X = A; Y = C; Z = B;
5271       }
5272       
5273       if (X) {   // Build (X^Y) & Z
5274         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5275         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5276         I.setOperand(0, Op1);
5277         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5278         return &I;
5279       }
5280     }
5281   }
5282   return Changed ? &I : 0;
5283 }
5284
5285 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5286 // We only handle extending casts so far.
5287 //
5288 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5289   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5290   Value *LHSCIOp        = LHSCI->getOperand(0);
5291   const Type *SrcTy     = LHSCIOp->getType();
5292   const Type *DestTy    = LHSCI->getType();
5293   Value *RHSCIOp;
5294
5295   // We only handle extension cast instructions, so far. Enforce this.
5296   if (LHSCI->getOpcode() != Instruction::ZExt &&
5297       LHSCI->getOpcode() != Instruction::SExt)
5298     return 0;
5299
5300   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5301   bool isSignedCmp = ICI.isSignedPredicate();
5302
5303   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5304     // Not an extension from the same type?
5305     RHSCIOp = CI->getOperand(0);
5306     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5307       return 0;
5308     else
5309       // Okay, just insert a compare of the reduced operands now!
5310       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5311   }
5312
5313   // If we aren't dealing with a constant on the RHS, exit early
5314   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5315   if (!CI)
5316     return 0;
5317
5318   // Compute the constant that would happen if we truncated to SrcTy then
5319   // reextended to DestTy.
5320   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5321   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5322
5323   // If the re-extended constant didn't change...
5324   if (Res2 == CI) {
5325     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5326     // For example, we might have:
5327     //    %A = sext short %X to uint
5328     //    %B = icmp ugt uint %A, 1330
5329     // It is incorrect to transform this into 
5330     //    %B = icmp ugt short %X, 1330 
5331     // because %A may have negative value. 
5332     //
5333     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5334     // OR operation is EQ/NE.
5335     if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5336       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5337     else
5338       return 0;
5339   }
5340
5341   // The re-extended constant changed so the constant cannot be represented 
5342   // in the shorter type. Consequently, we cannot emit a simple comparison.
5343
5344   // First, handle some easy cases. We know the result cannot be equal at this
5345   // point so handle the ICI.isEquality() cases
5346   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5347     return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5348   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5349     return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5350
5351   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5352   // should have been folded away previously and not enter in here.
5353   Value *Result;
5354   if (isSignedCmp) {
5355     // We're performing a signed comparison.
5356     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5357       Result = ConstantBool::getFalse();          // X < (small) --> false
5358     else
5359       Result = ConstantBool::getTrue();           // X < (large) --> true
5360   } else {
5361     // We're performing an unsigned comparison.
5362     if (isSignedExt) {
5363       // We're performing an unsigned comp with a sign extended value.
5364       // This is true if the input is >= 0. [aka >s -1]
5365       Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5366       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5367                                    NegOne, ICI.getName()), ICI);
5368     } else {
5369       // Unsigned extend & unsigned compare -> always true.
5370       Result = ConstantBool::getTrue();
5371     }
5372   }
5373
5374   // Finally, return the value computed.
5375   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5376       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5377     return ReplaceInstUsesWith(ICI, Result);
5378   } else {
5379     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5380             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5381            "ICmp should be folded!");
5382     if (Constant *CI = dyn_cast<Constant>(Result))
5383       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5384     else
5385       return BinaryOperator::createNot(Result);
5386   }
5387 }
5388
5389 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5390   assert(I.getOperand(1)->getType() == Type::UByteTy);
5391   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5392
5393   // shl X, 0 == X and shr X, 0 == X
5394   // shl 0, X == 0 and shr 0, X == 0
5395   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
5396       Op0 == Constant::getNullValue(Op0->getType()))
5397     return ReplaceInstUsesWith(I, Op0);
5398   
5399   if (isa<UndefValue>(Op0)) {            
5400     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5401       return ReplaceInstUsesWith(I, Op0);
5402     else                                    // undef << X -> 0, undef >>u X -> 0
5403       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5404   }
5405   if (isa<UndefValue>(Op1)) {
5406     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5407       return ReplaceInstUsesWith(I, Op0);          
5408     else                                     // X << undef, X >>u undef -> 0
5409       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5410   }
5411
5412   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5413   if (I.getOpcode() == Instruction::AShr)
5414     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5415       if (CSI->isAllOnesValue())
5416         return ReplaceInstUsesWith(I, CSI);
5417
5418   // Try to fold constant and into select arguments.
5419   if (isa<Constant>(Op0))
5420     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5421       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5422         return R;
5423
5424   // See if we can turn a signed shr into an unsigned shr.
5425   if (I.isArithmeticShift()) {
5426     if (MaskedValueIsZero(Op0,
5427                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5428       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5429     }
5430   }
5431
5432   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5433     if (CUI->getType()->isUnsigned())
5434       if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5435         return Res;
5436   return 0;
5437 }
5438
5439 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5440                                                ShiftInst &I) {
5441   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5442   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5443   bool isUnsignedShift = !isSignedShift;
5444
5445   // See if we can simplify any instructions used by the instruction whose sole 
5446   // purpose is to compute bits we don't care about.
5447   uint64_t KnownZero, KnownOne;
5448   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5449                            KnownZero, KnownOne))
5450     return &I;
5451   
5452   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5453   // of a signed value.
5454   //
5455   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5456   if (Op1->getZExtValue() >= TypeBits) {
5457     if (isUnsignedShift || isLeftShift)
5458       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5459     else {
5460       I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
5461       return &I;
5462     }
5463   }
5464   
5465   // ((X*C1) << C2) == (X * (C1 << C2))
5466   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5467     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5468       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5469         return BinaryOperator::createMul(BO->getOperand(0),
5470                                          ConstantExpr::getShl(BOOp, Op1));
5471   
5472   // Try to fold constant and into select arguments.
5473   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5474     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5475       return R;
5476   if (isa<PHINode>(Op0))
5477     if (Instruction *NV = FoldOpIntoPhi(I))
5478       return NV;
5479   
5480   if (Op0->hasOneUse()) {
5481     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5482       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5483       Value *V1, *V2;
5484       ConstantInt *CC;
5485       switch (Op0BO->getOpcode()) {
5486         default: break;
5487         case Instruction::Add:
5488         case Instruction::And:
5489         case Instruction::Or:
5490         case Instruction::Xor:
5491           // These operators commute.
5492           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5493           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5494               match(Op0BO->getOperand(1),
5495                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5496             Instruction *YS = new ShiftInst(Instruction::Shl, 
5497                                             Op0BO->getOperand(0), Op1,
5498                                             Op0BO->getName());
5499             InsertNewInstBefore(YS, I); // (Y << C)
5500             Instruction *X = 
5501               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5502                                      Op0BO->getOperand(1)->getName());
5503             InsertNewInstBefore(X, I);  // (X + (Y << C))
5504             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5505             C2 = ConstantExpr::getShl(C2, Op1);
5506             return BinaryOperator::createAnd(X, C2);
5507           }
5508           
5509           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5510           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5511               match(Op0BO->getOperand(1),
5512                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5513                           m_ConstantInt(CC))) && V2 == Op1 &&
5514       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5515             Instruction *YS = new ShiftInst(Instruction::Shl, 
5516                                             Op0BO->getOperand(0), Op1,
5517                                             Op0BO->getName());
5518             InsertNewInstBefore(YS, I); // (Y << C)
5519             Instruction *XM =
5520               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5521                                         V1->getName()+".mask");
5522             InsertNewInstBefore(XM, I); // X & (CC << C)
5523             
5524             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5525           }
5526           
5527           // FALL THROUGH.
5528         case Instruction::Sub:
5529           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5530           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5531               match(Op0BO->getOperand(0),
5532                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5533             Instruction *YS = new ShiftInst(Instruction::Shl, 
5534                                             Op0BO->getOperand(1), Op1,
5535                                             Op0BO->getName());
5536             InsertNewInstBefore(YS, I); // (Y << C)
5537             Instruction *X =
5538               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5539                                      Op0BO->getOperand(0)->getName());
5540             InsertNewInstBefore(X, I);  // (X + (Y << C))
5541             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5542             C2 = ConstantExpr::getShl(C2, Op1);
5543             return BinaryOperator::createAnd(X, C2);
5544           }
5545           
5546           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5547           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5548               match(Op0BO->getOperand(0),
5549                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5550                           m_ConstantInt(CC))) && V2 == Op1 &&
5551               cast<BinaryOperator>(Op0BO->getOperand(0))
5552                   ->getOperand(0)->hasOneUse()) {
5553             Instruction *YS = new ShiftInst(Instruction::Shl, 
5554                                             Op0BO->getOperand(1), Op1,
5555                                             Op0BO->getName());
5556             InsertNewInstBefore(YS, I); // (Y << C)
5557             Instruction *XM =
5558               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5559                                         V1->getName()+".mask");
5560             InsertNewInstBefore(XM, I); // X & (CC << C)
5561             
5562             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5563           }
5564           
5565           break;
5566       }
5567       
5568       
5569       // If the operand is an bitwise operator with a constant RHS, and the
5570       // shift is the only use, we can pull it out of the shift.
5571       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5572         bool isValid = true;     // Valid only for And, Or, Xor
5573         bool highBitSet = false; // Transform if high bit of constant set?
5574         
5575         switch (Op0BO->getOpcode()) {
5576           default: isValid = false; break;   // Do not perform transform!
5577           case Instruction::Add:
5578             isValid = isLeftShift;
5579             break;
5580           case Instruction::Or:
5581           case Instruction::Xor:
5582             highBitSet = false;
5583             break;
5584           case Instruction::And:
5585             highBitSet = true;
5586             break;
5587         }
5588         
5589         // If this is a signed shift right, and the high bit is modified
5590         // by the logical operation, do not perform the transformation.
5591         // The highBitSet boolean indicates the value of the high bit of
5592         // the constant which would cause it to be modified for this
5593         // operation.
5594         //
5595         if (isValid && !isLeftShift && isSignedShift) {
5596           uint64_t Val = Op0C->getZExtValue();
5597           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5598         }
5599         
5600         if (isValid) {
5601           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5602           
5603           Instruction *NewShift =
5604             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5605                           Op0BO->getName());
5606           Op0BO->setName("");
5607           InsertNewInstBefore(NewShift, I);
5608           
5609           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5610                                         NewRHS);
5611         }
5612       }
5613     }
5614   }
5615   
5616   // Find out if this is a shift of a shift by a constant.
5617   ShiftInst *ShiftOp = 0;
5618   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5619     ShiftOp = Op0SI;
5620   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5621     // If this is a noop-integer cast of a shift instruction, use the shift.
5622     if (isa<ShiftInst>(CI->getOperand(0))) {
5623       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5624     }
5625   }
5626   
5627   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5628     // Find the operands and properties of the input shift.  Note that the
5629     // signedness of the input shift may differ from the current shift if there
5630     // is a noop cast between the two.
5631     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5632     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5633     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5634     
5635     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5636
5637     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5638     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5639     
5640     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5641     if (isLeftShift == isShiftOfLeftShift) {
5642       // Do not fold these shifts if the first one is signed and the second one
5643       // is unsigned and this is a right shift.  Further, don't do any folding
5644       // on them.
5645       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5646         return 0;
5647       
5648       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5649       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5650         Amt = Op0->getType()->getPrimitiveSizeInBits();
5651       
5652       Value *Op = ShiftOp->getOperand(0);
5653       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5654                                           ConstantInt::get(Type::UByteTy, Amt));
5655       if (I.getType() == ShiftResult->getType())
5656         return ShiftResult;
5657       InsertNewInstBefore(ShiftResult, I);
5658       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5659     }
5660     
5661     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5662     // signed types, we can only support the (A >> c1) << c2 configuration,
5663     // because it can not turn an arbitrary bit of A into a sign bit.
5664     if (isUnsignedShift || isLeftShift) {
5665       // Calculate bitmask for what gets shifted off the edge.
5666       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5667       if (isLeftShift)
5668         C = ConstantExpr::getShl(C, ShiftAmt1C);
5669       else
5670         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5671       
5672       Value *Op = ShiftOp->getOperand(0);
5673       if (Op->getType() != C->getType())
5674         Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
5675       
5676       Instruction *Mask =
5677         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5678       InsertNewInstBefore(Mask, I);
5679       
5680       // Figure out what flavor of shift we should use...
5681       if (ShiftAmt1 == ShiftAmt2) {
5682         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5683       } else if (ShiftAmt1 < ShiftAmt2) {
5684         return new ShiftInst(I.getOpcode(), Mask,
5685                          ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5686       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5687         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5688           return new ShiftInst(Instruction::LShr, Mask, 
5689             ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5690         } else {
5691           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5692                     ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5693         }
5694       } else {
5695         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5696         Instruction *Shift =
5697           new ShiftInst(ShiftOp->getOpcode(), Mask,
5698                         ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5699         InsertNewInstBefore(Shift, I);
5700         
5701         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5702         C = ConstantExpr::getShl(C, Op1);
5703         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5704       }
5705     } else {
5706       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5707       // this case, C1 == C2 and C1 is 8, 16, or 32.
5708       if (ShiftAmt1 == ShiftAmt2) {
5709         const Type *SExtType = 0;
5710         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5711         case 8 : SExtType = Type::SByteTy; break;
5712         case 16: SExtType = Type::ShortTy; break;
5713         case 32: SExtType = Type::IntTy; break;
5714         }
5715         
5716         if (SExtType) {
5717           Instruction *NewTrunc = 
5718             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5719           InsertNewInstBefore(NewTrunc, I);
5720           return new SExtInst(NewTrunc, I.getType());
5721         }
5722       }
5723     }
5724   }
5725   return 0;
5726 }
5727
5728
5729 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5730 /// expression.  If so, decompose it, returning some value X, such that Val is
5731 /// X*Scale+Offset.
5732 ///
5733 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5734                                         unsigned &Offset) {
5735   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5736   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5737     if (CI->getType()->isUnsigned()) {
5738       Offset = CI->getZExtValue();
5739       Scale  = 1;
5740       return ConstantInt::get(Type::UIntTy, 0);
5741     }
5742   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5743     if (I->getNumOperands() == 2) {
5744       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5745         if (CUI->getType()->isUnsigned()) {
5746           if (I->getOpcode() == Instruction::Shl) {
5747             // This is a value scaled by '1 << the shift amt'.
5748             Scale = 1U << CUI->getZExtValue();
5749             Offset = 0;
5750             return I->getOperand(0);
5751           } else if (I->getOpcode() == Instruction::Mul) {
5752             // This value is scaled by 'CUI'.
5753             Scale = CUI->getZExtValue();
5754             Offset = 0;
5755             return I->getOperand(0);
5756           } else if (I->getOpcode() == Instruction::Add) {
5757             // We have X+C.  Check to see if we really have (X*C2)+C1, 
5758             // where C1 is divisible by C2.
5759             unsigned SubScale;
5760             Value *SubVal = 
5761               DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5762             Offset += CUI->getZExtValue();
5763             if (SubScale > 1 && (Offset % SubScale == 0)) {
5764               Scale = SubScale;
5765               return SubVal;
5766             }
5767           }
5768         }
5769       }
5770     }
5771   }
5772
5773   // Otherwise, we can't look past this.
5774   Scale = 1;
5775   Offset = 0;
5776   return Val;
5777 }
5778
5779
5780 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5781 /// try to eliminate the cast by moving the type information into the alloc.
5782 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5783                                                    AllocationInst &AI) {
5784   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5785   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5786   
5787   // Remove any uses of AI that are dead.
5788   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5789   std::vector<Instruction*> DeadUsers;
5790   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5791     Instruction *User = cast<Instruction>(*UI++);
5792     if (isInstructionTriviallyDead(User)) {
5793       while (UI != E && *UI == User)
5794         ++UI; // If this instruction uses AI more than once, don't break UI.
5795       
5796       // Add operands to the worklist.
5797       AddUsesToWorkList(*User);
5798       ++NumDeadInst;
5799       DOUT << "IC: DCE: " << *User;
5800       
5801       User->eraseFromParent();
5802       removeFromWorkList(User);
5803     }
5804   }
5805   
5806   // Get the type really allocated and the type casted to.
5807   const Type *AllocElTy = AI.getAllocatedType();
5808   const Type *CastElTy = PTy->getElementType();
5809   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5810
5811   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5812   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5813   if (CastElTyAlign < AllocElTyAlign) return 0;
5814
5815   // If the allocation has multiple uses, only promote it if we are strictly
5816   // increasing the alignment of the resultant allocation.  If we keep it the
5817   // same, we open the door to infinite loops of various kinds.
5818   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5819
5820   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5821   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5822   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5823
5824   // See if we can satisfy the modulus by pulling a scale out of the array
5825   // size argument.
5826   unsigned ArraySizeScale, ArrayOffset;
5827   Value *NumElements = // See if the array size is a decomposable linear expr.
5828     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5829  
5830   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5831   // do the xform.
5832   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5833       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5834
5835   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5836   Value *Amt = 0;
5837   if (Scale == 1) {
5838     Amt = NumElements;
5839   } else {
5840     // If the allocation size is constant, form a constant mul expression
5841     Amt = ConstantInt::get(Type::UIntTy, Scale);
5842     if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5843       Amt = ConstantExpr::getMul(
5844               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5845     // otherwise multiply the amount and the number of elements
5846     else if (Scale != 1) {
5847       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5848       Amt = InsertNewInstBefore(Tmp, AI);
5849     }
5850   }
5851   
5852   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5853     Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5854     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5855     Amt = InsertNewInstBefore(Tmp, AI);
5856   }
5857   
5858   std::string Name = AI.getName(); AI.setName("");
5859   AllocationInst *New;
5860   if (isa<MallocInst>(AI))
5861     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5862   else
5863     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5864   InsertNewInstBefore(New, AI);
5865   
5866   // If the allocation has multiple uses, insert a cast and change all things
5867   // that used it to use the new cast.  This will also hack on CI, but it will
5868   // die soon.
5869   if (!AI.hasOneUse()) {
5870     AddUsesToWorkList(AI);
5871     // New is the allocation instruction, pointer typed. AI is the original
5872     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5873     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5874     InsertNewInstBefore(NewCast, AI);
5875     AI.replaceAllUsesWith(NewCast);
5876   }
5877   return ReplaceInstUsesWith(CI, New);
5878 }
5879
5880 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5881 /// and return it without inserting any new casts.  This is used by code that
5882 /// tries to decide whether promoting or shrinking integer operations to wider
5883 /// or smaller types will allow us to eliminate a truncate or extend.
5884 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5885                                        int &NumCastsRemoved) {
5886   if (isa<Constant>(V)) return true;
5887   
5888   Instruction *I = dyn_cast<Instruction>(V);
5889   if (!I || !I->hasOneUse()) return false;
5890   
5891   switch (I->getOpcode()) {
5892   case Instruction::And:
5893   case Instruction::Or:
5894   case Instruction::Xor:
5895     // These operators can all arbitrarily be extended or truncated.
5896     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5897            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5898   case Instruction::AShr:
5899   case Instruction::LShr:
5900   case Instruction::Shl:
5901     // If this is just a bitcast changing the sign of the operation, we can
5902     // convert if the operand can be converted.
5903     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5904       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5905     break;
5906   case Instruction::Trunc:
5907   case Instruction::ZExt:
5908   case Instruction::SExt:
5909   case Instruction::BitCast:
5910     // If this is a cast from the destination type, we can trivially eliminate
5911     // it, and this will remove a cast overall.
5912     if (I->getOperand(0)->getType() == Ty) {
5913       // If the first operand is itself a cast, and is eliminable, do not count
5914       // this as an eliminable cast.  We would prefer to eliminate those two
5915       // casts first.
5916       if (isa<CastInst>(I->getOperand(0)))
5917         return true;
5918       
5919       ++NumCastsRemoved;
5920       return true;
5921     }
5922     break;
5923   default:
5924     // TODO: Can handle more cases here.
5925     break;
5926   }
5927   
5928   return false;
5929 }
5930
5931 /// EvaluateInDifferentType - Given an expression that 
5932 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5933 /// evaluate the expression.
5934 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5935                                              bool isSigned ) {
5936   if (Constant *C = dyn_cast<Constant>(V))
5937     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5938
5939   // Otherwise, it must be an instruction.
5940   Instruction *I = cast<Instruction>(V);
5941   Instruction *Res = 0;
5942   switch (I->getOpcode()) {
5943   case Instruction::And:
5944   case Instruction::Or:
5945   case Instruction::Xor: {
5946     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5947     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5948     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5949                                  LHS, RHS, I->getName());
5950     break;
5951   }
5952   case Instruction::AShr:
5953   case Instruction::LShr:
5954   case Instruction::Shl: {
5955     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5956     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5957                         I->getOperand(1), I->getName());
5958     break;
5959   }    
5960   case Instruction::Trunc:
5961   case Instruction::ZExt:
5962   case Instruction::SExt:
5963   case Instruction::BitCast:
5964     // If the source type of the cast is the type we're trying for then we can
5965     // just return the source. There's no need to insert it because its not new.
5966     if (I->getOperand(0)->getType() == Ty)
5967       return I->getOperand(0);
5968     
5969     // Some other kind of cast, which shouldn't happen, so just ..
5970     // FALL THROUGH
5971   default: 
5972     // TODO: Can handle more cases here.
5973     assert(0 && "Unreachable!");
5974     break;
5975   }
5976   
5977   return InsertNewInstBefore(Res, *I);
5978 }
5979
5980 /// @brief Implement the transforms common to all CastInst visitors.
5981 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5982   Value *Src = CI.getOperand(0);
5983
5984   // Casting undef to anything results in undef so might as just replace it and
5985   // get rid of the cast.
5986   if (isa<UndefValue>(Src))   // cast undef -> undef
5987     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5988
5989   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5990   // eliminate it now.
5991   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5992     if (Instruction::CastOps opc = 
5993         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5994       // The first cast (CSrc) is eliminable so we need to fix up or replace
5995       // the second cast (CI). CSrc will then have a good chance of being dead.
5996       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5997     }
5998   }
5999
6000   // If casting the result of a getelementptr instruction with no offset, turn
6001   // this into a cast of the original pointer!
6002   //
6003   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6004     bool AllZeroOperands = true;
6005     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6006       if (!isa<Constant>(GEP->getOperand(i)) ||
6007           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6008         AllZeroOperands = false;
6009         break;
6010       }
6011     if (AllZeroOperands) {
6012       // Changing the cast operand is usually not a good idea but it is safe
6013       // here because the pointer operand is being replaced with another 
6014       // pointer operand so the opcode doesn't need to change.
6015       CI.setOperand(0, GEP->getOperand(0));
6016       return &CI;
6017     }
6018   }
6019     
6020   // If we are casting a malloc or alloca to a pointer to a type of the same
6021   // size, rewrite the allocation instruction to allocate the "right" type.
6022   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6023     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6024       return V;
6025
6026   // If we are casting a select then fold the cast into the select
6027   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6028     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6029       return NV;
6030
6031   // If we are casting a PHI then fold the cast into the PHI
6032   if (isa<PHINode>(Src))
6033     if (Instruction *NV = FoldOpIntoPhi(CI))
6034       return NV;
6035   
6036   return 0;
6037 }
6038
6039 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6040 /// integers. This function implements the common transforms for all those
6041 /// cases.
6042 /// @brief Implement the transforms common to CastInst with integer operands
6043 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6044   if (Instruction *Result = commonCastTransforms(CI))
6045     return Result;
6046
6047   Value *Src = CI.getOperand(0);
6048   const Type *SrcTy = Src->getType();
6049   const Type *DestTy = CI.getType();
6050   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6051   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6052
6053   // See if we can simplify any instructions used by the LHS whose sole 
6054   // purpose is to compute bits we don't care about.
6055   uint64_t KnownZero = 0, KnownOne = 0;
6056   if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6057                            KnownZero, KnownOne))
6058     return &CI;
6059
6060   // If the source isn't an instruction or has more than one use then we
6061   // can't do anything more. 
6062   Instruction *SrcI = dyn_cast<Instruction>(Src);
6063   if (!SrcI || !Src->hasOneUse())
6064     return 0;
6065
6066   // Attempt to propagate the cast into the instruction.
6067   int NumCastsRemoved = 0;
6068   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6069     // If this cast is a truncate, evaluting in a different type always
6070     // eliminates the cast, so it is always a win.  If this is a noop-cast
6071     // this just removes a noop cast which isn't pointful, but simplifies
6072     // the code.  If this is a zero-extension, we need to do an AND to
6073     // maintain the clear top-part of the computation, so we require that
6074     // the input have eliminated at least one cast.  If this is a sign
6075     // extension, we insert two new casts (to do the extension) so we
6076     // require that two casts have been eliminated.
6077     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6078     if (!DoXForm) {
6079       switch (CI.getOpcode()) {
6080         case Instruction::Trunc:
6081           DoXForm = true;
6082           break;
6083         case Instruction::ZExt:
6084           DoXForm = NumCastsRemoved >= 1;
6085           break;
6086         case Instruction::SExt:
6087           DoXForm = NumCastsRemoved >= 2;
6088           break;
6089         case Instruction::BitCast:
6090           DoXForm = false;
6091           break;
6092         default:
6093           // All the others use floating point so we shouldn't actually 
6094           // get here because of the check above.
6095           assert(!"Unknown cast type .. unreachable");
6096           break;
6097       }
6098     }
6099     
6100     if (DoXForm) {
6101       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6102                                            CI.getOpcode() == Instruction::SExt);
6103       assert(Res->getType() == DestTy);
6104       switch (CI.getOpcode()) {
6105       default: assert(0 && "Unknown cast type!");
6106       case Instruction::Trunc:
6107       case Instruction::BitCast:
6108         // Just replace this cast with the result.
6109         return ReplaceInstUsesWith(CI, Res);
6110       case Instruction::ZExt: {
6111         // We need to emit an AND to clear the high bits.
6112         assert(SrcBitSize < DestBitSize && "Not a zext?");
6113         Constant *C = 
6114           ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
6115         if (DestBitSize < 64)
6116           C = ConstantExpr::getTrunc(C, DestTy);
6117         else {
6118           assert(DestBitSize == 64);
6119           C = ConstantExpr::getBitCast(C, DestTy);
6120         }
6121         return BinaryOperator::createAnd(Res, C);
6122       }
6123       case Instruction::SExt:
6124         // We need to emit a cast to truncate, then a cast to sext.
6125         return CastInst::create(Instruction::SExt,
6126             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6127                              CI), DestTy);
6128       }
6129     }
6130   }
6131   
6132   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6133   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6134
6135   switch (SrcI->getOpcode()) {
6136   case Instruction::Add:
6137   case Instruction::Mul:
6138   case Instruction::And:
6139   case Instruction::Or:
6140   case Instruction::Xor:
6141     // If we are discarding information, or just changing the sign, 
6142     // rewrite.
6143     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
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 (DestBitSize == SrcBitSize || 
6148           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6149           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6150         Instruction::CastOps opcode = CI.getOpcode();
6151         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6152         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6153         return BinaryOperator::create(
6154             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6155       }
6156     }
6157
6158     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6159     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6160         SrcI->getOpcode() == Instruction::Xor &&
6161         Op1 == ConstantBool::getTrue() &&
6162         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6163       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6164       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6165     }
6166     break;
6167   case Instruction::SDiv:
6168   case Instruction::UDiv:
6169   case Instruction::SRem:
6170   case Instruction::URem:
6171     // If we are just changing the sign, rewrite.
6172     if (DestBitSize == SrcBitSize) {
6173       // Don't insert two casts if they cannot be eliminated.  We allow 
6174       // two casts to be inserted if the sizes are the same.  This could 
6175       // only be converting signedness, which is a noop.
6176       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6177           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6178         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6179                                               Op0, DestTy, SrcI);
6180         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6181                                               Op1, DestTy, SrcI);
6182         return BinaryOperator::create(
6183           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6184       }
6185     }
6186     break;
6187
6188   case Instruction::Shl:
6189     // Allow changing the sign of the source operand.  Do not allow 
6190     // changing the size of the shift, UNLESS the shift amount is a 
6191     // constant.  We must not change variable sized shifts to a smaller 
6192     // size, because it is undefined to shift more bits out than exist 
6193     // in the value.
6194     if (DestBitSize == SrcBitSize ||
6195         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6196       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6197           Instruction::BitCast : Instruction::Trunc);
6198       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6199       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6200     }
6201     break;
6202   case Instruction::AShr:
6203     // If this is a signed shr, and if all bits shifted in are about to be
6204     // truncated off, turn it into an unsigned shr to allow greater
6205     // simplifications.
6206     if (DestBitSize < SrcBitSize &&
6207         isa<ConstantInt>(Op1)) {
6208       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6209       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6210         // Insert the new logical shift right.
6211         return new ShiftInst(Instruction::LShr, Op0, Op1);
6212       }
6213     }
6214     break;
6215
6216   case Instruction::ICmp:
6217     // If we are just checking for a icmp eq of a single bit and casting it
6218     // to an integer, then shift the bit to the appropriate place and then
6219     // cast to integer to avoid the comparison.
6220     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6221       uint64_t Op1CV = Op1C->getZExtValue();
6222       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6223       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6224       // cast (X == 1) to int --> X        iff X has only the low bit set.
6225       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6226       // cast (X != 0) to int --> X        iff X has only the low bit set.
6227       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6228       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6229       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6230       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6231         // If Op1C some other power of two, convert:
6232         uint64_t KnownZero, KnownOne;
6233         uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6234         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6235
6236         // This only works for EQ and NE
6237         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6238         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6239           break;
6240         
6241         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6242           bool isNE = pred == ICmpInst::ICMP_NE;
6243           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6244             // (X&4) == 2 --> false
6245             // (X&4) != 2 --> true
6246             Constant *Res = ConstantBool::get(isNE);
6247             Res = ConstantExpr::getZExt(Res, CI.getType());
6248             return ReplaceInstUsesWith(CI, Res);
6249           }
6250           
6251           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6252           Value *In = Op0;
6253           if (ShiftAmt) {
6254             // Perform a logical shr by shiftamt.
6255             // Insert the shift to put the result in the low bit.
6256             In = InsertNewInstBefore(
6257               new ShiftInst(Instruction::LShr, In,
6258                             ConstantInt::get(Type::UByteTy, ShiftAmt),
6259                             In->getName()+".lobit"), CI);
6260           }
6261           
6262           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6263             Constant *One = ConstantInt::get(In->getType(), 1);
6264             In = BinaryOperator::createXor(In, One, "tmp");
6265             InsertNewInstBefore(cast<Instruction>(In), CI);
6266           }
6267           
6268           if (CI.getType() == In->getType())
6269             return ReplaceInstUsesWith(CI, In);
6270           else
6271             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6272         }
6273       }
6274     }
6275     break;
6276   }
6277   return 0;
6278 }
6279
6280 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6281   if (Instruction *Result = commonIntCastTransforms(CI))
6282     return Result;
6283   
6284   Value *Src = CI.getOperand(0);
6285   const Type *Ty = CI.getType();
6286   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6287   
6288   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6289     switch (SrcI->getOpcode()) {
6290     default: break;
6291     case Instruction::LShr:
6292       // We can shrink lshr to something smaller if we know the bits shifted in
6293       // are already zeros.
6294       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6295         unsigned ShAmt = ShAmtV->getZExtValue();
6296         
6297         // Get a mask for the bits shifting in.
6298         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6299         Value* SrcIOp0 = SrcI->getOperand(0);
6300         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6301           if (ShAmt >= DestBitWidth)        // All zeros.
6302             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6303
6304           // Okay, we can shrink this.  Truncate the input, then return a new
6305           // shift.
6306           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6307           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6308         }
6309       } else {     // This is a variable shr.
6310         
6311         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6312         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6313         // loop-invariant and CSE'd.
6314         if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6315           Value *One = ConstantInt::get(SrcI->getType(), 1);
6316
6317           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6318                                                        SrcI->getOperand(1),
6319                                                        "tmp"), CI);
6320           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6321                                                             SrcI->getOperand(0),
6322                                                             "tmp"), CI);
6323           Value *Zero = Constant::getNullValue(V->getType());
6324           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6325         }
6326       }
6327       break;
6328     }
6329   }
6330   
6331   return 0;
6332 }
6333
6334 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6335   // If one of the common conversion will work ..
6336   if (Instruction *Result = commonIntCastTransforms(CI))
6337     return Result;
6338
6339   Value *Src = CI.getOperand(0);
6340
6341   // If this is a cast of a cast
6342   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6343     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6344     // types and if the sizes are just right we can convert this into a logical
6345     // 'and' which will be much cheaper than the pair of casts.
6346     if (isa<TruncInst>(CSrc)) {
6347       // Get the sizes of the types involved
6348       Value *A = CSrc->getOperand(0);
6349       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6350       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6351       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6352       // If we're actually extending zero bits and the trunc is a no-op
6353       if (MidSize < DstSize && SrcSize == DstSize) {
6354         // Replace both of the casts with an And of the type mask.
6355         uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6356         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6357         Instruction *And = 
6358           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6359         // Unfortunately, if the type changed, we need to cast it back.
6360         if (And->getType() != CI.getType()) {
6361           And->setName(CSrc->getName()+".mask");
6362           InsertNewInstBefore(And, CI);
6363           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6364         }
6365         return And;
6366       }
6367     }
6368   }
6369
6370   return 0;
6371 }
6372
6373 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6374   return commonIntCastTransforms(CI);
6375 }
6376
6377 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6378   return commonCastTransforms(CI);
6379 }
6380
6381 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6382   return commonCastTransforms(CI);
6383 }
6384
6385 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6386   return commonCastTransforms(CI);
6387 }
6388
6389 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6390   return commonCastTransforms(CI);
6391 }
6392
6393 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6394   return commonCastTransforms(CI);
6395 }
6396
6397 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6398   return commonCastTransforms(CI);
6399 }
6400
6401 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6402   return commonCastTransforms(CI);
6403 }
6404
6405 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6406   return commonCastTransforms(CI);
6407 }
6408
6409 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6410
6411   // If the operands are integer typed then apply the integer transforms,
6412   // otherwise just apply the common ones.
6413   Value *Src = CI.getOperand(0);
6414   const Type *SrcTy = Src->getType();
6415   const Type *DestTy = CI.getType();
6416
6417   if (SrcTy->isInteger() && DestTy->isInteger()) {
6418     if (Instruction *Result = commonIntCastTransforms(CI))
6419       return Result;
6420   } else {
6421     if (Instruction *Result = commonCastTransforms(CI))
6422       return Result;
6423   }
6424
6425
6426   // Get rid of casts from one type to the same type. These are useless and can
6427   // be replaced by the operand.
6428   if (DestTy == Src->getType())
6429     return ReplaceInstUsesWith(CI, Src);
6430
6431   // If the source and destination are pointers, and this cast is equivalent to
6432   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6433   // This can enhance SROA and other transforms that want type-safe pointers.
6434   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6435     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6436       const Type *DstElTy = DstPTy->getElementType();
6437       const Type *SrcElTy = SrcPTy->getElementType();
6438       
6439       Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6440       unsigned NumZeros = 0;
6441       while (SrcElTy != DstElTy && 
6442              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6443              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6444         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6445         ++NumZeros;
6446       }
6447
6448       // If we found a path from the src to dest, create the getelementptr now.
6449       if (SrcElTy == DstElTy) {
6450         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6451         return new GetElementPtrInst(Src, Idxs);
6452       }
6453     }
6454   }
6455
6456   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6457     if (SVI->hasOneUse()) {
6458       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6459       // a bitconvert to a vector with the same # elts.
6460       if (isa<PackedType>(DestTy) && 
6461           cast<PackedType>(DestTy)->getNumElements() == 
6462                 SVI->getType()->getNumElements()) {
6463         CastInst *Tmp;
6464         // If either of the operands is a cast from CI.getType(), then
6465         // evaluating the shuffle in the casted destination's type will allow
6466         // us to eliminate at least one cast.
6467         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6468              Tmp->getOperand(0)->getType() == DestTy) ||
6469             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6470              Tmp->getOperand(0)->getType() == DestTy)) {
6471           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6472                                                SVI->getOperand(0), DestTy, &CI);
6473           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6474                                                SVI->getOperand(1), DestTy, &CI);
6475           // Return a new shuffle vector.  Use the same element ID's, as we
6476           // know the vector types match #elts.
6477           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6478         }
6479       }
6480     }
6481   }
6482   return 0;
6483 }
6484
6485 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6486 ///   %C = or %A, %B
6487 ///   %D = select %cond, %C, %A
6488 /// into:
6489 ///   %C = select %cond, %B, 0
6490 ///   %D = or %A, %C
6491 ///
6492 /// Assuming that the specified instruction is an operand to the select, return
6493 /// a bitmask indicating which operands of this instruction are foldable if they
6494 /// equal the other incoming value of the select.
6495 ///
6496 static unsigned GetSelectFoldableOperands(Instruction *I) {
6497   switch (I->getOpcode()) {
6498   case Instruction::Add:
6499   case Instruction::Mul:
6500   case Instruction::And:
6501   case Instruction::Or:
6502   case Instruction::Xor:
6503     return 3;              // Can fold through either operand.
6504   case Instruction::Sub:   // Can only fold on the amount subtracted.
6505   case Instruction::Shl:   // Can only fold on the shift amount.
6506   case Instruction::LShr:
6507   case Instruction::AShr:
6508     return 1;
6509   default:
6510     return 0;              // Cannot fold
6511   }
6512 }
6513
6514 /// GetSelectFoldableConstant - For the same transformation as the previous
6515 /// function, return the identity constant that goes into the select.
6516 static Constant *GetSelectFoldableConstant(Instruction *I) {
6517   switch (I->getOpcode()) {
6518   default: assert(0 && "This cannot happen!"); abort();
6519   case Instruction::Add:
6520   case Instruction::Sub:
6521   case Instruction::Or:
6522   case Instruction::Xor:
6523     return Constant::getNullValue(I->getType());
6524   case Instruction::Shl:
6525   case Instruction::LShr:
6526   case Instruction::AShr:
6527     return Constant::getNullValue(Type::UByteTy);
6528   case Instruction::And:
6529     return ConstantInt::getAllOnesValue(I->getType());
6530   case Instruction::Mul:
6531     return ConstantInt::get(I->getType(), 1);
6532   }
6533 }
6534
6535 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6536 /// have the same opcode and only one use each.  Try to simplify this.
6537 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6538                                           Instruction *FI) {
6539   if (TI->getNumOperands() == 1) {
6540     // If this is a non-volatile load or a cast from the same type,
6541     // merge.
6542     if (TI->isCast()) {
6543       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6544         return 0;
6545     } else {
6546       return 0;  // unknown unary op.
6547     }
6548
6549     // Fold this by inserting a select from the input values.
6550     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6551                                        FI->getOperand(0), SI.getName()+".v");
6552     InsertNewInstBefore(NewSI, SI);
6553     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6554                             TI->getType());
6555   }
6556
6557   // Only handle binary, compare and shift operators here.
6558   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI) && !isa<CmpInst>(TI))
6559     return 0;
6560
6561   // If the CmpInst predicates don't match, then the instructions aren't the 
6562   // same and we can't continue.
6563   if (isa<CmpInst>(TI) && isa<CmpInst>(FI) &&
6564       (cast<CmpInst>(TI)->getPredicate() != cast<CmpInst>(FI)->getPredicate()))
6565     return 0;
6566
6567   // Figure out if the operations have any operands in common.
6568   Value *MatchOp, *OtherOpT, *OtherOpF;
6569   bool MatchIsOpZero;
6570   if (TI->getOperand(0) == FI->getOperand(0)) {
6571     MatchOp  = TI->getOperand(0);
6572     OtherOpT = TI->getOperand(1);
6573     OtherOpF = FI->getOperand(1);
6574     MatchIsOpZero = true;
6575   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6576     MatchOp  = TI->getOperand(1);
6577     OtherOpT = TI->getOperand(0);
6578     OtherOpF = FI->getOperand(0);
6579     MatchIsOpZero = false;
6580   } else if (!TI->isCommutative()) {
6581     return 0;
6582   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6583     MatchOp  = TI->getOperand(0);
6584     OtherOpT = TI->getOperand(1);
6585     OtherOpF = FI->getOperand(0);
6586     MatchIsOpZero = true;
6587   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6588     MatchOp  = TI->getOperand(1);
6589     OtherOpT = TI->getOperand(0);
6590     OtherOpF = FI->getOperand(1);
6591     MatchIsOpZero = true;
6592   } else {
6593     return 0;
6594   }
6595
6596   // If we reach here, they do have operations in common.
6597   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6598                                      OtherOpF, SI.getName()+".v");
6599   InsertNewInstBefore(NewSI, SI);
6600
6601   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6602     if (MatchIsOpZero)
6603       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6604     else
6605       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6606   } else {
6607     if (MatchIsOpZero)
6608       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6609     else
6610       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6611   }
6612 }
6613
6614 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6615   Value *CondVal = SI.getCondition();
6616   Value *TrueVal = SI.getTrueValue();
6617   Value *FalseVal = SI.getFalseValue();
6618
6619   // select true, X, Y  -> X
6620   // select false, X, Y -> Y
6621   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6622     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6623
6624   // select C, X, X -> X
6625   if (TrueVal == FalseVal)
6626     return ReplaceInstUsesWith(SI, TrueVal);
6627
6628   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6629     return ReplaceInstUsesWith(SI, FalseVal);
6630   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6631     return ReplaceInstUsesWith(SI, TrueVal);
6632   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6633     if (isa<Constant>(TrueVal))
6634       return ReplaceInstUsesWith(SI, TrueVal);
6635     else
6636       return ReplaceInstUsesWith(SI, FalseVal);
6637   }
6638
6639   if (SI.getType() == Type::BoolTy)
6640     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6641       if (C->getValue()) {
6642         // Change: A = select B, true, C --> A = or B, C
6643         return BinaryOperator::createOr(CondVal, FalseVal);
6644       } else {
6645         // Change: A = select B, false, C --> A = and !B, C
6646         Value *NotCond =
6647           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6648                                              "not."+CondVal->getName()), SI);
6649         return BinaryOperator::createAnd(NotCond, FalseVal);
6650       }
6651     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6652       if (C->getValue() == false) {
6653         // Change: A = select B, C, false --> A = and B, C
6654         return BinaryOperator::createAnd(CondVal, TrueVal);
6655       } else {
6656         // Change: A = select B, C, true --> A = or !B, C
6657         Value *NotCond =
6658           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6659                                              "not."+CondVal->getName()), SI);
6660         return BinaryOperator::createOr(NotCond, TrueVal);
6661       }
6662     }
6663
6664   // Selecting between two integer constants?
6665   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6666     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6667       // select C, 1, 0 -> cast C to int
6668       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6669         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6670       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6671         // select C, 0, 1 -> cast !C to int
6672         Value *NotCond =
6673           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6674                                                "not."+CondVal->getName()), SI);
6675         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6676       }
6677
6678       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6679
6680         // (x <s 0) ? -1 : 0 -> ashr x, 31
6681         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6682         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6683           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6684             bool CanXForm = false;
6685             if (IC->isSignedPredicate())
6686               CanXForm = CmpCst->isNullValue() && 
6687                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6688             else {
6689               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6690               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6691                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6692             }
6693             
6694             if (CanXForm) {
6695               // The comparison constant and the result are not neccessarily the
6696               // same width. Make an all-ones value by inserting a AShr.
6697               Value *X = IC->getOperand(0);
6698               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6699               Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6700               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6701                                                ShAmt, "ones");
6702               InsertNewInstBefore(SRA, SI);
6703               
6704               // Finally, convert to the type of the select RHS.  We figure out
6705               // if this requires a SExt, Trunc or BitCast based on the sizes.
6706               Instruction::CastOps opc = Instruction::BitCast;
6707               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6708               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6709               if (SRASize < SISize)
6710                 opc = Instruction::SExt;
6711               else if (SRASize > SISize)
6712                 opc = Instruction::Trunc;
6713               return CastInst::create(opc, SRA, SI.getType());
6714             }
6715           }
6716
6717
6718         // If one of the constants is zero (we know they can't both be) and we
6719         // have a fcmp instruction with zero, and we have an 'and' with the
6720         // non-constant value, eliminate this whole mess.  This corresponds to
6721         // cases like this: ((X & 27) ? 27 : 0)
6722         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6723           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6724               cast<Constant>(IC->getOperand(1))->isNullValue())
6725             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6726               if (ICA->getOpcode() == Instruction::And &&
6727                   isa<ConstantInt>(ICA->getOperand(1)) &&
6728                   (ICA->getOperand(1) == TrueValC ||
6729                    ICA->getOperand(1) == FalseValC) &&
6730                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6731                 // Okay, now we know that everything is set up, we just don't
6732                 // know whether we have a icmp_ne or icmp_eq and whether the 
6733                 // true or false val is the zero.
6734                 bool ShouldNotVal = !TrueValC->isNullValue();
6735                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6736                 Value *V = ICA;
6737                 if (ShouldNotVal)
6738                   V = InsertNewInstBefore(BinaryOperator::create(
6739                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6740                 return ReplaceInstUsesWith(SI, V);
6741               }
6742       }
6743     }
6744
6745   // See if we are selecting two values based on a comparison of the two values.
6746   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6747     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6748       // Transform (X == Y) ? X : Y  -> Y
6749       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6750         return ReplaceInstUsesWith(SI, FalseVal);
6751       // Transform (X != Y) ? X : Y  -> X
6752       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6753         return ReplaceInstUsesWith(SI, TrueVal);
6754       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6755
6756     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6757       // Transform (X == Y) ? Y : X  -> X
6758       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6759         return ReplaceInstUsesWith(SI, FalseVal);
6760       // Transform (X != Y) ? Y : X  -> Y
6761       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6762         return ReplaceInstUsesWith(SI, TrueVal);
6763       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6764     }
6765   }
6766
6767   // See if we are selecting two values based on a comparison of the two values.
6768   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6769     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6770       // Transform (X == Y) ? X : Y  -> Y
6771       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6772         return ReplaceInstUsesWith(SI, FalseVal);
6773       // Transform (X != Y) ? X : Y  -> X
6774       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6775         return ReplaceInstUsesWith(SI, TrueVal);
6776       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6777
6778     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6779       // Transform (X == Y) ? Y : X  -> X
6780       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6781         return ReplaceInstUsesWith(SI, FalseVal);
6782       // Transform (X != Y) ? Y : X  -> Y
6783       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6784         return ReplaceInstUsesWith(SI, TrueVal);
6785       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6786     }
6787   }
6788
6789   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6790     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6791       if (TI->hasOneUse() && FI->hasOneUse()) {
6792         Instruction *AddOp = 0, *SubOp = 0;
6793
6794         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6795         if (TI->getOpcode() == FI->getOpcode())
6796           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6797             return IV;
6798
6799         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6800         // even legal for FP.
6801         if (TI->getOpcode() == Instruction::Sub &&
6802             FI->getOpcode() == Instruction::Add) {
6803           AddOp = FI; SubOp = TI;
6804         } else if (FI->getOpcode() == Instruction::Sub &&
6805                    TI->getOpcode() == Instruction::Add) {
6806           AddOp = TI; SubOp = FI;
6807         }
6808
6809         if (AddOp) {
6810           Value *OtherAddOp = 0;
6811           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6812             OtherAddOp = AddOp->getOperand(1);
6813           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6814             OtherAddOp = AddOp->getOperand(0);
6815           }
6816
6817           if (OtherAddOp) {
6818             // So at this point we know we have (Y -> OtherAddOp):
6819             //        select C, (add X, Y), (sub X, Z)
6820             Value *NegVal;  // Compute -Z
6821             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6822               NegVal = ConstantExpr::getNeg(C);
6823             } else {
6824               NegVal = InsertNewInstBefore(
6825                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6826             }
6827
6828             Value *NewTrueOp = OtherAddOp;
6829             Value *NewFalseOp = NegVal;
6830             if (AddOp != TI)
6831               std::swap(NewTrueOp, NewFalseOp);
6832             Instruction *NewSel =
6833               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6834
6835             NewSel = InsertNewInstBefore(NewSel, SI);
6836             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6837           }
6838         }
6839       }
6840
6841   // See if we can fold the select into one of our operands.
6842   if (SI.getType()->isInteger()) {
6843     // See the comment above GetSelectFoldableOperands for a description of the
6844     // transformation we are doing here.
6845     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6846       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6847           !isa<Constant>(FalseVal))
6848         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6849           unsigned OpToFold = 0;
6850           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6851             OpToFold = 1;
6852           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6853             OpToFold = 2;
6854           }
6855
6856           if (OpToFold) {
6857             Constant *C = GetSelectFoldableConstant(TVI);
6858             std::string Name = TVI->getName(); TVI->setName("");
6859             Instruction *NewSel =
6860               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6861                              Name);
6862             InsertNewInstBefore(NewSel, SI);
6863             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6864               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6865             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6866               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6867             else {
6868               assert(0 && "Unknown instruction!!");
6869             }
6870           }
6871         }
6872
6873     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6874       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6875           !isa<Constant>(TrueVal))
6876         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6877           unsigned OpToFold = 0;
6878           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6879             OpToFold = 1;
6880           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6881             OpToFold = 2;
6882           }
6883
6884           if (OpToFold) {
6885             Constant *C = GetSelectFoldableConstant(FVI);
6886             std::string Name = FVI->getName(); FVI->setName("");
6887             Instruction *NewSel =
6888               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6889                              Name);
6890             InsertNewInstBefore(NewSel, SI);
6891             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6892               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6893             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6894               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6895             else {
6896               assert(0 && "Unknown instruction!!");
6897             }
6898           }
6899         }
6900   }
6901
6902   if (BinaryOperator::isNot(CondVal)) {
6903     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6904     SI.setOperand(1, FalseVal);
6905     SI.setOperand(2, TrueVal);
6906     return &SI;
6907   }
6908
6909   return 0;
6910 }
6911
6912 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6913 /// determine, return it, otherwise return 0.
6914 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6915   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6916     unsigned Align = GV->getAlignment();
6917     if (Align == 0 && TD) 
6918       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6919     return Align;
6920   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6921     unsigned Align = AI->getAlignment();
6922     if (Align == 0 && TD) {
6923       if (isa<AllocaInst>(AI))
6924         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6925       else if (isa<MallocInst>(AI)) {
6926         // Malloc returns maximally aligned memory.
6927         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6928         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6929         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6930       }
6931     }
6932     return Align;
6933   } else if (isa<BitCastInst>(V) ||
6934              (isa<ConstantExpr>(V) && 
6935               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6936     User *CI = cast<User>(V);
6937     if (isa<PointerType>(CI->getOperand(0)->getType()))
6938       return GetKnownAlignment(CI->getOperand(0), TD);
6939     return 0;
6940   } else if (isa<GetElementPtrInst>(V) ||
6941              (isa<ConstantExpr>(V) && 
6942               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6943     User *GEPI = cast<User>(V);
6944     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6945     if (BaseAlignment == 0) return 0;
6946     
6947     // If all indexes are zero, it is just the alignment of the base pointer.
6948     bool AllZeroOperands = true;
6949     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6950       if (!isa<Constant>(GEPI->getOperand(i)) ||
6951           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6952         AllZeroOperands = false;
6953         break;
6954       }
6955     if (AllZeroOperands)
6956       return BaseAlignment;
6957     
6958     // Otherwise, if the base alignment is >= the alignment we expect for the
6959     // base pointer type, then we know that the resultant pointer is aligned at
6960     // least as much as its type requires.
6961     if (!TD) return 0;
6962
6963     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6964     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6965         <= BaseAlignment) {
6966       const Type *GEPTy = GEPI->getType();
6967       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6968     }
6969     return 0;
6970   }
6971   return 0;
6972 }
6973
6974
6975 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6976 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6977 /// the heavy lifting.
6978 ///
6979 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6980   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6981   if (!II) return visitCallSite(&CI);
6982   
6983   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6984   // visitCallSite.
6985   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6986     bool Changed = false;
6987
6988     // memmove/cpy/set of zero bytes is a noop.
6989     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6990       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6991
6992       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6993         if (CI->getZExtValue() == 1) {
6994           // Replace the instruction with just byte operations.  We would
6995           // transform other cases to loads/stores, but we don't know if
6996           // alignment is sufficient.
6997         }
6998     }
6999
7000     // If we have a memmove and the source operation is a constant global,
7001     // then the source and dest pointers can't alias, so we can change this
7002     // into a call to memcpy.
7003     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7004       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7005         if (GVSrc->isConstant()) {
7006           Module *M = CI.getParent()->getParent()->getParent();
7007           const char *Name;
7008           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7009               Type::UIntTy)
7010             Name = "llvm.memcpy.i32";
7011           else
7012             Name = "llvm.memcpy.i64";
7013           Function *MemCpy = M->getOrInsertFunction(Name,
7014                                      CI.getCalledFunction()->getFunctionType());
7015           CI.setOperand(0, MemCpy);
7016           Changed = true;
7017         }
7018     }
7019
7020     // If we can determine a pointer alignment that is bigger than currently
7021     // set, update the alignment.
7022     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7023       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7024       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7025       unsigned Align = std::min(Alignment1, Alignment2);
7026       if (MI->getAlignment()->getZExtValue() < Align) {
7027         MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
7028         Changed = true;
7029       }
7030     } else if (isa<MemSetInst>(MI)) {
7031       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7032       if (MI->getAlignment()->getZExtValue() < Alignment) {
7033         MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
7034         Changed = true;
7035       }
7036     }
7037           
7038     if (Changed) return II;
7039   } else {
7040     switch (II->getIntrinsicID()) {
7041     default: break;
7042     case Intrinsic::ppc_altivec_lvx:
7043     case Intrinsic::ppc_altivec_lvxl:
7044     case Intrinsic::x86_sse_loadu_ps:
7045     case Intrinsic::x86_sse2_loadu_pd:
7046     case Intrinsic::x86_sse2_loadu_dq:
7047       // Turn PPC lvx     -> load if the pointer is known aligned.
7048       // Turn X86 loadups -> load if the pointer is known aligned.
7049       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7050         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7051                                       PointerType::get(II->getType()), CI);
7052         return new LoadInst(Ptr);
7053       }
7054       break;
7055     case Intrinsic::ppc_altivec_stvx:
7056     case Intrinsic::ppc_altivec_stvxl:
7057       // Turn stvx -> store if the pointer is known aligned.
7058       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7059         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7060         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7061                                       OpPtrTy, CI);
7062         return new StoreInst(II->getOperand(1), Ptr);
7063       }
7064       break;
7065     case Intrinsic::x86_sse_storeu_ps:
7066     case Intrinsic::x86_sse2_storeu_pd:
7067     case Intrinsic::x86_sse2_storeu_dq:
7068     case Intrinsic::x86_sse2_storel_dq:
7069       // Turn X86 storeu -> store if the pointer is known aligned.
7070       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7071         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7072         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7073                                       OpPtrTy, CI);
7074         return new StoreInst(II->getOperand(2), Ptr);
7075       }
7076       break;
7077       
7078     case Intrinsic::x86_sse_cvttss2si: {
7079       // These intrinsics only demands the 0th element of its input vector.  If
7080       // we can simplify the input based on that, do so now.
7081       uint64_t UndefElts;
7082       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7083                                                 UndefElts)) {
7084         II->setOperand(1, V);
7085         return II;
7086       }
7087       break;
7088     }
7089       
7090     case Intrinsic::ppc_altivec_vperm:
7091       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7092       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7093         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7094         
7095         // Check that all of the elements are integer constants or undefs.
7096         bool AllEltsOk = true;
7097         for (unsigned i = 0; i != 16; ++i) {
7098           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7099               !isa<UndefValue>(Mask->getOperand(i))) {
7100             AllEltsOk = false;
7101             break;
7102           }
7103         }
7104         
7105         if (AllEltsOk) {
7106           // Cast the input vectors to byte vectors.
7107           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7108                                         II->getOperand(1), Mask->getType(), CI);
7109           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7110                                         II->getOperand(2), Mask->getType(), CI);
7111           Value *Result = UndefValue::get(Op0->getType());
7112           
7113           // Only extract each element once.
7114           Value *ExtractedElts[32];
7115           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7116           
7117           for (unsigned i = 0; i != 16; ++i) {
7118             if (isa<UndefValue>(Mask->getOperand(i)))
7119               continue;
7120             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7121             Idx &= 31;  // Match the hardware behavior.
7122             
7123             if (ExtractedElts[Idx] == 0) {
7124               Instruction *Elt = 
7125                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7126               InsertNewInstBefore(Elt, CI);
7127               ExtractedElts[Idx] = Elt;
7128             }
7129           
7130             // Insert this value into the result vector.
7131             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7132             InsertNewInstBefore(cast<Instruction>(Result), CI);
7133           }
7134           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7135         }
7136       }
7137       break;
7138
7139     case Intrinsic::stackrestore: {
7140       // If the save is right next to the restore, remove the restore.  This can
7141       // happen when variable allocas are DCE'd.
7142       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7143         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7144           BasicBlock::iterator BI = SS;
7145           if (&*++BI == II)
7146             return EraseInstFromFunction(CI);
7147         }
7148       }
7149       
7150       // If the stack restore is in a return/unwind block and if there are no
7151       // allocas or calls between the restore and the return, nuke the restore.
7152       TerminatorInst *TI = II->getParent()->getTerminator();
7153       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7154         BasicBlock::iterator BI = II;
7155         bool CannotRemove = false;
7156         for (++BI; &*BI != TI; ++BI) {
7157           if (isa<AllocaInst>(BI) ||
7158               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7159             CannotRemove = true;
7160             break;
7161           }
7162         }
7163         if (!CannotRemove)
7164           return EraseInstFromFunction(CI);
7165       }
7166       break;
7167     }
7168     }
7169   }
7170
7171   return visitCallSite(II);
7172 }
7173
7174 // InvokeInst simplification
7175 //
7176 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7177   return visitCallSite(&II);
7178 }
7179
7180 // visitCallSite - Improvements for call and invoke instructions.
7181 //
7182 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7183   bool Changed = false;
7184
7185   // If the callee is a constexpr cast of a function, attempt to move the cast
7186   // to the arguments of the call/invoke.
7187   if (transformConstExprCastCall(CS)) return 0;
7188
7189   Value *Callee = CS.getCalledValue();
7190
7191   if (Function *CalleeF = dyn_cast<Function>(Callee))
7192     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7193       Instruction *OldCall = CS.getInstruction();
7194       // If the call and callee calling conventions don't match, this call must
7195       // be unreachable, as the call is undefined.
7196       new StoreInst(ConstantBool::getTrue(),
7197                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7198       if (!OldCall->use_empty())
7199         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7200       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7201         return EraseInstFromFunction(*OldCall);
7202       return 0;
7203     }
7204
7205   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7206     // This instruction is not reachable, just remove it.  We insert a store to
7207     // undef so that we know that this code is not reachable, despite the fact
7208     // that we can't modify the CFG here.
7209     new StoreInst(ConstantBool::getTrue(),
7210                   UndefValue::get(PointerType::get(Type::BoolTy)),
7211                   CS.getInstruction());
7212
7213     if (!CS.getInstruction()->use_empty())
7214       CS.getInstruction()->
7215         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7216
7217     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7218       // Don't break the CFG, insert a dummy cond branch.
7219       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7220                      ConstantBool::getTrue(), II);
7221     }
7222     return EraseInstFromFunction(*CS.getInstruction());
7223   }
7224
7225   const PointerType *PTy = cast<PointerType>(Callee->getType());
7226   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7227   if (FTy->isVarArg()) {
7228     // See if we can optimize any arguments passed through the varargs area of
7229     // the call.
7230     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7231            E = CS.arg_end(); I != E; ++I)
7232       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7233         // If this cast does not effect the value passed through the varargs
7234         // area, we can eliminate the use of the cast.
7235         Value *Op = CI->getOperand(0);
7236         if (CI->isLosslessCast()) {
7237           *I = Op;
7238           Changed = true;
7239         }
7240       }
7241   }
7242
7243   return Changed ? CS.getInstruction() : 0;
7244 }
7245
7246 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7247 // attempt to move the cast to the arguments of the call/invoke.
7248 //
7249 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7250   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7251   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7252   if (CE->getOpcode() != Instruction::BitCast || 
7253       !isa<Function>(CE->getOperand(0)))
7254     return false;
7255   Function *Callee = cast<Function>(CE->getOperand(0));
7256   Instruction *Caller = CS.getInstruction();
7257
7258   // Okay, this is a cast from a function to a different type.  Unless doing so
7259   // would cause a type conversion of one of our arguments, change this call to
7260   // be a direct call with arguments casted to the appropriate types.
7261   //
7262   const FunctionType *FT = Callee->getFunctionType();
7263   const Type *OldRetTy = Caller->getType();
7264
7265   // Check to see if we are changing the return type...
7266   if (OldRetTy != FT->getReturnType()) {
7267     if (Callee->isExternal() &&
7268         !Caller->use_empty() && 
7269         !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
7270           (isa<PointerType>(FT->getReturnType()) && 
7271            TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7272         )
7273       return false;   // Cannot transform this return value...
7274
7275     // If the callsite is an invoke instruction, and the return value is used by
7276     // a PHI node in a successor, we cannot change the return type of the call
7277     // because there is no place to put the cast instruction (without breaking
7278     // the critical edge).  Bail out in this case.
7279     if (!Caller->use_empty())
7280       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7281         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7282              UI != E; ++UI)
7283           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7284             if (PN->getParent() == II->getNormalDest() ||
7285                 PN->getParent() == II->getUnwindDest())
7286               return false;
7287   }
7288
7289   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7290   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7291
7292   CallSite::arg_iterator AI = CS.arg_begin();
7293   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7294     const Type *ParamTy = FT->getParamType(i);
7295     const Type *ActTy = (*AI)->getType();
7296     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7297     //Either we can cast directly, or we can upconvert the argument
7298     bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
7299       (ParamTy->isIntegral() && ActTy->isIntegral() &&
7300        ParamTy->isSigned() == ActTy->isSigned() &&
7301        ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7302       (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
7303        c->getSExtValue() > 0);
7304     if (Callee->isExternal() && !isConvertible) return false;
7305   }
7306
7307   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7308       Callee->isExternal())
7309     return false;   // Do not delete arguments unless we have a function body...
7310
7311   // Okay, we decided that this is a safe thing to do: go ahead and start
7312   // inserting cast instructions as necessary...
7313   std::vector<Value*> Args;
7314   Args.reserve(NumActualArgs);
7315
7316   AI = CS.arg_begin();
7317   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7318     const Type *ParamTy = FT->getParamType(i);
7319     if ((*AI)->getType() == ParamTy) {
7320       Args.push_back(*AI);
7321     } else {
7322       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7323           (*AI)->getType()->isSigned(), ParamTy, ParamTy->isSigned());
7324       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7325       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7326     }
7327   }
7328
7329   // If the function takes more arguments than the call was taking, add them
7330   // now...
7331   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7332     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7333
7334   // If we are removing arguments to the function, emit an obnoxious warning...
7335   if (FT->getNumParams() < NumActualArgs)
7336     if (!FT->isVarArg()) {
7337       cerr << "WARNING: While resolving call to function '"
7338            << Callee->getName() << "' arguments were dropped!\n";
7339     } else {
7340       // Add all of the arguments in their promoted form to the arg list...
7341       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7342         const Type *PTy = getPromotedType((*AI)->getType());
7343         if (PTy != (*AI)->getType()) {
7344           // Must promote to pass through va_arg area!
7345           Instruction::CastOps opcode = CastInst::getCastOpcode(
7346               *AI, (*AI)->getType()->isSigned(), PTy, PTy->isSigned());
7347           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7348           InsertNewInstBefore(Cast, *Caller);
7349           Args.push_back(Cast);
7350         } else {
7351           Args.push_back(*AI);
7352         }
7353       }
7354     }
7355
7356   if (FT->getReturnType() == Type::VoidTy)
7357     Caller->setName("");   // Void type should not have a name...
7358
7359   Instruction *NC;
7360   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7361     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7362                         Args, Caller->getName(), Caller);
7363     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7364   } else {
7365     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7366     if (cast<CallInst>(Caller)->isTailCall())
7367       cast<CallInst>(NC)->setTailCall();
7368    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7369   }
7370
7371   // Insert a cast of the return type as necessary...
7372   Value *NV = NC;
7373   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7374     if (NV->getType() != Type::VoidTy) {
7375       const Type *CallerTy = Caller->getType();
7376       Instruction::CastOps opcode = CastInst::getCastOpcode(
7377           NC, NC->getType()->isSigned(), CallerTy, CallerTy->isSigned());
7378       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7379
7380       // If this is an invoke instruction, we should insert it after the first
7381       // non-phi, instruction in the normal successor block.
7382       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7383         BasicBlock::iterator I = II->getNormalDest()->begin();
7384         while (isa<PHINode>(I)) ++I;
7385         InsertNewInstBefore(NC, *I);
7386       } else {
7387         // Otherwise, it's a call, just insert cast right after the call instr
7388         InsertNewInstBefore(NC, *Caller);
7389       }
7390       AddUsersToWorkList(*Caller);
7391     } else {
7392       NV = UndefValue::get(Caller->getType());
7393     }
7394   }
7395
7396   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7397     Caller->replaceAllUsesWith(NV);
7398   Caller->getParent()->getInstList().erase(Caller);
7399   removeFromWorkList(Caller);
7400   return true;
7401 }
7402
7403 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7404 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7405 /// and a single binop.
7406 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7407   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7408   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7409          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7410   unsigned Opc = FirstInst->getOpcode();
7411   Value *LHSVal = FirstInst->getOperand(0);
7412   Value *RHSVal = FirstInst->getOperand(1);
7413     
7414   const Type *LHSType = LHSVal->getType();
7415   const Type *RHSType = RHSVal->getType();
7416   
7417   // Scan to see if all operands are the same opcode, all have one use, and all
7418   // kill their operands (i.e. the operands have one use).
7419   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7420     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7421     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7422         // Verify type of the LHS matches so we don't fold cmp's of different
7423         // types or GEP's with different index types.
7424         I->getOperand(0)->getType() != LHSType ||
7425         I->getOperand(1)->getType() != RHSType)
7426       return 0;
7427
7428     // If they are CmpInst instructions, check their predicates
7429     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7430       if (cast<CmpInst>(I)->getPredicate() !=
7431           cast<CmpInst>(FirstInst)->getPredicate())
7432         return 0;
7433     
7434     // Keep track of which operand needs a phi node.
7435     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7436     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7437   }
7438   
7439   // Otherwise, this is safe to transform, determine if it is profitable.
7440
7441   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7442   // Indexes are often folded into load/store instructions, so we don't want to
7443   // hide them behind a phi.
7444   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7445     return 0;
7446   
7447   Value *InLHS = FirstInst->getOperand(0);
7448   Value *InRHS = FirstInst->getOperand(1);
7449   PHINode *NewLHS = 0, *NewRHS = 0;
7450   if (LHSVal == 0) {
7451     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7452     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7453     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7454     InsertNewInstBefore(NewLHS, PN);
7455     LHSVal = NewLHS;
7456   }
7457   
7458   if (RHSVal == 0) {
7459     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7460     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7461     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7462     InsertNewInstBefore(NewRHS, PN);
7463     RHSVal = NewRHS;
7464   }
7465   
7466   // Add all operands to the new PHIs.
7467   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7468     if (NewLHS) {
7469       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7470       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7471     }
7472     if (NewRHS) {
7473       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7474       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7475     }
7476   }
7477     
7478   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7479     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7480   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7481     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7482                            RHSVal);
7483   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7484     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7485   else {
7486     assert(isa<GetElementPtrInst>(FirstInst));
7487     return new GetElementPtrInst(LHSVal, RHSVal);
7488   }
7489 }
7490
7491 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7492 /// of the block that defines it.  This means that it must be obvious the value
7493 /// of the load is not changed from the point of the load to the end of the
7494 /// block it is in.
7495 static bool isSafeToSinkLoad(LoadInst *L) {
7496   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7497   
7498   for (++BBI; BBI != E; ++BBI)
7499     if (BBI->mayWriteToMemory())
7500       return false;
7501   return true;
7502 }
7503
7504
7505 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7506 // operator and they all are only used by the PHI, PHI together their
7507 // inputs, and do the operation once, to the result of the PHI.
7508 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7509   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7510
7511   // Scan the instruction, looking for input operations that can be folded away.
7512   // If all input operands to the phi are the same instruction (e.g. a cast from
7513   // the same type or "+42") we can pull the operation through the PHI, reducing
7514   // code size and simplifying code.
7515   Constant *ConstantOp = 0;
7516   const Type *CastSrcTy = 0;
7517   bool isVolatile = false;
7518   if (isa<CastInst>(FirstInst)) {
7519     CastSrcTy = FirstInst->getOperand(0)->getType();
7520   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7521              isa<CmpInst>(FirstInst)) {
7522     // Can fold binop, compare or shift here if the RHS is a constant, 
7523     // otherwise call FoldPHIArgBinOpIntoPHI.
7524     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7525     if (ConstantOp == 0)
7526       return FoldPHIArgBinOpIntoPHI(PN);
7527   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7528     isVolatile = LI->isVolatile();
7529     // We can't sink the load if the loaded value could be modified between the
7530     // load and the PHI.
7531     if (LI->getParent() != PN.getIncomingBlock(0) ||
7532         !isSafeToSinkLoad(LI))
7533       return 0;
7534   } else if (isa<GetElementPtrInst>(FirstInst)) {
7535     if (FirstInst->getNumOperands() == 2)
7536       return FoldPHIArgBinOpIntoPHI(PN);
7537     // Can't handle general GEPs yet.
7538     return 0;
7539   } else {
7540     return 0;  // Cannot fold this operation.
7541   }
7542
7543   // Check to see if all arguments are the same operation.
7544   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7545     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7546     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7547     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7548       return 0;
7549     if (CastSrcTy) {
7550       if (I->getOperand(0)->getType() != CastSrcTy)
7551         return 0;  // Cast operation must match.
7552     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7553       // We can't sink the load if the loaded value could be modified between 
7554       // the load and the PHI.
7555       if (LI->isVolatile() != isVolatile ||
7556           LI->getParent() != PN.getIncomingBlock(i) ||
7557           !isSafeToSinkLoad(LI))
7558         return 0;
7559     } else if (I->getOperand(1) != ConstantOp) {
7560       return 0;
7561     }
7562   }
7563
7564   // Okay, they are all the same operation.  Create a new PHI node of the
7565   // correct type, and PHI together all of the LHS's of the instructions.
7566   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7567                                PN.getName()+".in");
7568   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7569
7570   Value *InVal = FirstInst->getOperand(0);
7571   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7572
7573   // Add all operands to the new PHI.
7574   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7575     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7576     if (NewInVal != InVal)
7577       InVal = 0;
7578     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7579   }
7580
7581   Value *PhiVal;
7582   if (InVal) {
7583     // The new PHI unions all of the same values together.  This is really
7584     // common, so we handle it intelligently here for compile-time speed.
7585     PhiVal = InVal;
7586     delete NewPN;
7587   } else {
7588     InsertNewInstBefore(NewPN, PN);
7589     PhiVal = NewPN;
7590   }
7591
7592   // Insert and return the new operation.
7593   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7594     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7595   else if (isa<LoadInst>(FirstInst))
7596     return new LoadInst(PhiVal, "", isVolatile);
7597   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7598     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7599   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7600     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7601                            PhiVal, ConstantOp);
7602   else
7603     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7604                          PhiVal, ConstantOp);
7605 }
7606
7607 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7608 /// that is dead.
7609 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7610   if (PN->use_empty()) return true;
7611   if (!PN->hasOneUse()) return false;
7612
7613   // Remember this node, and if we find the cycle, return.
7614   if (!PotentiallyDeadPHIs.insert(PN).second)
7615     return true;
7616
7617   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7618     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7619
7620   return false;
7621 }
7622
7623 // PHINode simplification
7624 //
7625 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7626   // If LCSSA is around, don't mess with Phi nodes
7627   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7628   
7629   if (Value *V = PN.hasConstantValue())
7630     return ReplaceInstUsesWith(PN, V);
7631
7632   // If all PHI operands are the same operation, pull them through the PHI,
7633   // reducing code size.
7634   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7635       PN.getIncomingValue(0)->hasOneUse())
7636     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7637       return Result;
7638
7639   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7640   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7641   // PHI)... break the cycle.
7642   if (PN.hasOneUse())
7643     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7644       std::set<PHINode*> PotentiallyDeadPHIs;
7645       PotentiallyDeadPHIs.insert(&PN);
7646       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7647         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7648     }
7649
7650   return 0;
7651 }
7652
7653 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7654                                    Instruction *InsertPoint,
7655                                    InstCombiner *IC) {
7656   unsigned PtrSize = DTy->getPrimitiveSize();
7657   unsigned VTySize = V->getType()->getPrimitiveSize();
7658   // We must cast correctly to the pointer type. Ensure that we
7659   // sign extend the integer value if it is smaller as this is
7660   // used for address computation.
7661   Instruction::CastOps opcode = 
7662      (VTySize < PtrSize ? Instruction::SExt :
7663       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7664   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7665 }
7666
7667
7668 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7669   Value *PtrOp = GEP.getOperand(0);
7670   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7671   // If so, eliminate the noop.
7672   if (GEP.getNumOperands() == 1)
7673     return ReplaceInstUsesWith(GEP, PtrOp);
7674
7675   if (isa<UndefValue>(GEP.getOperand(0)))
7676     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7677
7678   bool HasZeroPointerIndex = false;
7679   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7680     HasZeroPointerIndex = C->isNullValue();
7681
7682   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7683     return ReplaceInstUsesWith(GEP, PtrOp);
7684
7685   // Eliminate unneeded casts for indices.
7686   bool MadeChange = false;
7687   gep_type_iterator GTI = gep_type_begin(GEP);
7688   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7689     if (isa<SequentialType>(*GTI)) {
7690       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7691         Value *Src = CI->getOperand(0);
7692         const Type *SrcTy = Src->getType();
7693         const Type *DestTy = CI->getType();
7694         if (Src->getType()->isInteger()) {
7695           if (SrcTy->getPrimitiveSizeInBits() ==
7696                        DestTy->getPrimitiveSizeInBits()) {
7697             // We can always eliminate a cast from ulong or long to the other.
7698             // We can always eliminate a cast from uint to int or the other on
7699             // 32-bit pointer platforms.
7700             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7701               MadeChange = true;
7702               GEP.setOperand(i, Src);
7703             }
7704           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7705                      SrcTy->getPrimitiveSize() == 4) {
7706             // We can eliminate a cast from [u]int to [u]long iff the target 
7707             // is a 32-bit pointer target.
7708             if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7709               MadeChange = true;
7710               GEP.setOperand(i, Src);
7711             }
7712           }
7713         }
7714       }
7715       // If we are using a wider index than needed for this platform, shrink it
7716       // to what we need.  If the incoming value needs a cast instruction,
7717       // insert it.  This explicit cast can make subsequent optimizations more
7718       // obvious.
7719       Value *Op = GEP.getOperand(i);
7720       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7721         if (Constant *C = dyn_cast<Constant>(Op)) {
7722           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7723           MadeChange = true;
7724         } else {
7725           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7726                                 GEP);
7727           GEP.setOperand(i, Op);
7728           MadeChange = true;
7729         }
7730       // If this is a constant idx, make sure to canonicalize it to be a signed
7731       // operand, otherwise CSE and other optimizations are pessimized.
7732       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7733         if (CUI->getType()->isUnsigned()) {
7734           GEP.setOperand(i, 
7735             ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
7736           MadeChange = true;
7737         }
7738     }
7739   if (MadeChange) return &GEP;
7740
7741   // Combine Indices - If the source pointer to this getelementptr instruction
7742   // is a getelementptr instruction, combine the indices of the two
7743   // getelementptr instructions into a single instruction.
7744   //
7745   std::vector<Value*> SrcGEPOperands;
7746   if (User *Src = dyn_castGetElementPtr(PtrOp))
7747     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7748
7749   if (!SrcGEPOperands.empty()) {
7750     // Note that if our source is a gep chain itself that we wait for that
7751     // chain to be resolved before we perform this transformation.  This
7752     // avoids us creating a TON of code in some cases.
7753     //
7754     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7755         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7756       return 0;   // Wait until our source is folded to completion.
7757
7758     std::vector<Value *> Indices;
7759
7760     // Find out whether the last index in the source GEP is a sequential idx.
7761     bool EndsWithSequential = false;
7762     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7763            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7764       EndsWithSequential = !isa<StructType>(*I);
7765
7766     // Can we combine the two pointer arithmetics offsets?
7767     if (EndsWithSequential) {
7768       // Replace: gep (gep %P, long B), long A, ...
7769       // With:    T = long A+B; gep %P, T, ...
7770       //
7771       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7772       if (SO1 == Constant::getNullValue(SO1->getType())) {
7773         Sum = GO1;
7774       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7775         Sum = SO1;
7776       } else {
7777         // If they aren't the same type, convert both to an integer of the
7778         // target's pointer size.
7779         if (SO1->getType() != GO1->getType()) {
7780           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7781             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7782           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7783             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7784           } else {
7785             unsigned PS = TD->getPointerSize();
7786             if (SO1->getType()->getPrimitiveSize() == PS) {
7787               // Convert GO1 to SO1's type.
7788               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7789
7790             } else if (GO1->getType()->getPrimitiveSize() == PS) {
7791               // Convert SO1 to GO1's type.
7792               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7793             } else {
7794               const Type *PT = TD->getIntPtrType();
7795               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7796               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7797             }
7798           }
7799         }
7800         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7801           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7802         else {
7803           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7804           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7805         }
7806       }
7807
7808       // Recycle the GEP we already have if possible.
7809       if (SrcGEPOperands.size() == 2) {
7810         GEP.setOperand(0, SrcGEPOperands[0]);
7811         GEP.setOperand(1, Sum);
7812         return &GEP;
7813       } else {
7814         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7815                        SrcGEPOperands.end()-1);
7816         Indices.push_back(Sum);
7817         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7818       }
7819     } else if (isa<Constant>(*GEP.idx_begin()) &&
7820                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7821                SrcGEPOperands.size() != 1) {
7822       // Otherwise we can do the fold if the first index of the GEP is a zero
7823       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7824                      SrcGEPOperands.end());
7825       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7826     }
7827
7828     if (!Indices.empty())
7829       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7830
7831   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7832     // GEP of global variable.  If all of the indices for this GEP are
7833     // constants, we can promote this to a constexpr instead of an instruction.
7834
7835     // Scan for nonconstants...
7836     std::vector<Constant*> Indices;
7837     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7838     for (; I != E && isa<Constant>(*I); ++I)
7839       Indices.push_back(cast<Constant>(*I));
7840
7841     if (I == E) {  // If they are all constants...
7842       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7843
7844       // Replace all uses of the GEP with the new constexpr...
7845       return ReplaceInstUsesWith(GEP, CE);
7846     }
7847   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7848     if (!isa<PointerType>(X->getType())) {
7849       // Not interesting.  Source pointer must be a cast from pointer.
7850     } else if (HasZeroPointerIndex) {
7851       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7852       // into     : GEP [10 x ubyte]* X, long 0, ...
7853       //
7854       // This occurs when the program declares an array extern like "int X[];"
7855       //
7856       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7857       const PointerType *XTy = cast<PointerType>(X->getType());
7858       if (const ArrayType *XATy =
7859           dyn_cast<ArrayType>(XTy->getElementType()))
7860         if (const ArrayType *CATy =
7861             dyn_cast<ArrayType>(CPTy->getElementType()))
7862           if (CATy->getElementType() == XATy->getElementType()) {
7863             // At this point, we know that the cast source type is a pointer
7864             // to an array of the same type as the destination pointer
7865             // array.  Because the array type is never stepped over (there
7866             // is a leading zero) we can fold the cast into this GEP.
7867             GEP.setOperand(0, X);
7868             return &GEP;
7869           }
7870     } else if (GEP.getNumOperands() == 2) {
7871       // Transform things like:
7872       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7873       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7874       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7875       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7876       if (isa<ArrayType>(SrcElTy) &&
7877           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7878           TD->getTypeSize(ResElTy)) {
7879         Value *V = InsertNewInstBefore(
7880                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7881                                      GEP.getOperand(1), GEP.getName()), GEP);
7882         // V and GEP are both pointer types --> BitCast
7883         return new BitCastInst(V, GEP.getType());
7884       }
7885       
7886       // Transform things like:
7887       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7888       //   (where tmp = 8*tmp2) into:
7889       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7890       
7891       if (isa<ArrayType>(SrcElTy) &&
7892           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7893         uint64_t ArrayEltSize =
7894             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7895         
7896         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7897         // allow either a mul, shift, or constant here.
7898         Value *NewIdx = 0;
7899         ConstantInt *Scale = 0;
7900         if (ArrayEltSize == 1) {
7901           NewIdx = GEP.getOperand(1);
7902           Scale = ConstantInt::get(NewIdx->getType(), 1);
7903         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7904           NewIdx = ConstantInt::get(CI->getType(), 1);
7905           Scale = CI;
7906         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7907           if (Inst->getOpcode() == Instruction::Shl &&
7908               isa<ConstantInt>(Inst->getOperand(1))) {
7909             unsigned ShAmt =
7910               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7911             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7912             NewIdx = Inst->getOperand(0);
7913           } else if (Inst->getOpcode() == Instruction::Mul &&
7914                      isa<ConstantInt>(Inst->getOperand(1))) {
7915             Scale = cast<ConstantInt>(Inst->getOperand(1));
7916             NewIdx = Inst->getOperand(0);
7917           }
7918         }
7919
7920         // If the index will be to exactly the right offset with the scale taken
7921         // out, perform the transformation.
7922         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7923           if (isa<ConstantInt>(Scale))
7924             Scale = ConstantInt::get(Scale->getType(),
7925                                       Scale->getZExtValue() / ArrayEltSize);
7926           if (Scale->getZExtValue() != 1) {
7927             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7928                                                        true /*SExt*/);
7929             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7930             NewIdx = InsertNewInstBefore(Sc, GEP);
7931           }
7932
7933           // Insert the new GEP instruction.
7934           Instruction *NewGEP =
7935             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7936                                   NewIdx, GEP.getName());
7937           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7938           // The NewGEP must be pointer typed, so must the old one -> BitCast
7939           return new BitCastInst(NewGEP, GEP.getType());
7940         }
7941       }
7942     }
7943   }
7944
7945   return 0;
7946 }
7947
7948 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7949   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7950   if (AI.isArrayAllocation())    // Check C != 1
7951     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7952       const Type *NewTy = 
7953         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7954       AllocationInst *New = 0;
7955
7956       // Create and insert the replacement instruction...
7957       if (isa<MallocInst>(AI))
7958         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7959       else {
7960         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7961         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7962       }
7963
7964       InsertNewInstBefore(New, AI);
7965
7966       // Scan to the end of the allocation instructions, to skip over a block of
7967       // allocas if possible...
7968       //
7969       BasicBlock::iterator It = New;
7970       while (isa<AllocationInst>(*It)) ++It;
7971
7972       // Now that I is pointing to the first non-allocation-inst in the block,
7973       // insert our getelementptr instruction...
7974       //
7975       Value *NullIdx = Constant::getNullValue(Type::IntTy);
7976       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7977                                        New->getName()+".sub", It);
7978
7979       // Now make everything use the getelementptr instead of the original
7980       // allocation.
7981       return ReplaceInstUsesWith(AI, V);
7982     } else if (isa<UndefValue>(AI.getArraySize())) {
7983       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7984     }
7985
7986   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7987   // Note that we only do this for alloca's, because malloc should allocate and
7988   // return a unique pointer, even for a zero byte allocation.
7989   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7990       TD->getTypeSize(AI.getAllocatedType()) == 0)
7991     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7992
7993   return 0;
7994 }
7995
7996 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7997   Value *Op = FI.getOperand(0);
7998
7999   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8000   if (CastInst *CI = dyn_cast<CastInst>(Op))
8001     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8002       FI.setOperand(0, CI->getOperand(0));
8003       return &FI;
8004     }
8005
8006   // free undef -> unreachable.
8007   if (isa<UndefValue>(Op)) {
8008     // Insert a new store to null because we cannot modify the CFG here.
8009     new StoreInst(ConstantBool::getTrue(),
8010                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
8011     return EraseInstFromFunction(FI);
8012   }
8013
8014   // If we have 'free null' delete the instruction.  This can happen in stl code
8015   // when lots of inlining happens.
8016   if (isa<ConstantPointerNull>(Op))
8017     return EraseInstFromFunction(FI);
8018
8019   return 0;
8020 }
8021
8022
8023 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8024 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8025   User *CI = cast<User>(LI.getOperand(0));
8026   Value *CastOp = CI->getOperand(0);
8027
8028   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8029   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8030     const Type *SrcPTy = SrcTy->getElementType();
8031
8032     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8033         isa<PackedType>(DestPTy)) {
8034       // If the source is an array, the code below will not succeed.  Check to
8035       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8036       // constants.
8037       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8038         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8039           if (ASrcTy->getNumElements() != 0) {
8040             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
8041             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8042             SrcTy = cast<PointerType>(CastOp->getType());
8043             SrcPTy = SrcTy->getElementType();
8044           }
8045
8046       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8047            isa<PackedType>(SrcPTy)) &&
8048           // Do not allow turning this into a load of an integer, which is then
8049           // casted to a pointer, this pessimizes pointer analysis a lot.
8050           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8051           IC.getTargetData().getTypeSize(SrcPTy) ==
8052                IC.getTargetData().getTypeSize(DestPTy)) {
8053
8054         // Okay, we are casting from one integer or pointer type to another of
8055         // the same size.  Instead of casting the pointer before the load, cast
8056         // the result of the loaded value.
8057         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8058                                                              CI->getName(),
8059                                                          LI.isVolatile()),LI);
8060         // Now cast the result of the load.
8061         return new BitCastInst(NewLoad, LI.getType());
8062       }
8063     }
8064   }
8065   return 0;
8066 }
8067
8068 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8069 /// from this value cannot trap.  If it is not obviously safe to load from the
8070 /// specified pointer, we do a quick local scan of the basic block containing
8071 /// ScanFrom, to determine if the address is already accessed.
8072 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8073   // If it is an alloca or global variable, it is always safe to load from.
8074   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8075
8076   // Otherwise, be a little bit agressive by scanning the local block where we
8077   // want to check to see if the pointer is already being loaded or stored
8078   // from/to.  If so, the previous load or store would have already trapped,
8079   // so there is no harm doing an extra load (also, CSE will later eliminate
8080   // the load entirely).
8081   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8082
8083   while (BBI != E) {
8084     --BBI;
8085
8086     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8087       if (LI->getOperand(0) == V) return true;
8088     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8089       if (SI->getOperand(1) == V) return true;
8090
8091   }
8092   return false;
8093 }
8094
8095 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8096   Value *Op = LI.getOperand(0);
8097
8098   // load (cast X) --> cast (load X) iff safe
8099   if (isa<CastInst>(Op))
8100     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8101       return Res;
8102
8103   // None of the following transforms are legal for volatile loads.
8104   if (LI.isVolatile()) return 0;
8105   
8106   if (&LI.getParent()->front() != &LI) {
8107     BasicBlock::iterator BBI = &LI; --BBI;
8108     // If the instruction immediately before this is a store to the same
8109     // address, do a simple form of store->load forwarding.
8110     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8111       if (SI->getOperand(1) == LI.getOperand(0))
8112         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8113     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8114       if (LIB->getOperand(0) == LI.getOperand(0))
8115         return ReplaceInstUsesWith(LI, LIB);
8116   }
8117
8118   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8119     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8120         isa<UndefValue>(GEPI->getOperand(0))) {
8121       // Insert a new store to null instruction before the load to indicate
8122       // that this code is not reachable.  We do this instead of inserting
8123       // an unreachable instruction directly because we cannot modify the
8124       // CFG.
8125       new StoreInst(UndefValue::get(LI.getType()),
8126                     Constant::getNullValue(Op->getType()), &LI);
8127       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8128     }
8129
8130   if (Constant *C = dyn_cast<Constant>(Op)) {
8131     // load null/undef -> undef
8132     if ((C->isNullValue() || isa<UndefValue>(C))) {
8133       // Insert a new store to null instruction before the load to indicate that
8134       // this code is not reachable.  We do this instead of inserting an
8135       // unreachable instruction directly because we cannot modify the CFG.
8136       new StoreInst(UndefValue::get(LI.getType()),
8137                     Constant::getNullValue(Op->getType()), &LI);
8138       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8139     }
8140
8141     // Instcombine load (constant global) into the value loaded.
8142     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8143       if (GV->isConstant() && !GV->isExternal())
8144         return ReplaceInstUsesWith(LI, GV->getInitializer());
8145
8146     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8147     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8148       if (CE->getOpcode() == Instruction::GetElementPtr) {
8149         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8150           if (GV->isConstant() && !GV->isExternal())
8151             if (Constant *V = 
8152                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8153               return ReplaceInstUsesWith(LI, V);
8154         if (CE->getOperand(0)->isNullValue()) {
8155           // Insert a new store to null instruction before the load to indicate
8156           // that this code is not reachable.  We do this instead of inserting
8157           // an unreachable instruction directly because we cannot modify the
8158           // CFG.
8159           new StoreInst(UndefValue::get(LI.getType()),
8160                         Constant::getNullValue(Op->getType()), &LI);
8161           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8162         }
8163
8164       } else if (CE->isCast()) {
8165         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8166           return Res;
8167       }
8168   }
8169
8170   if (Op->hasOneUse()) {
8171     // Change select and PHI nodes to select values instead of addresses: this
8172     // helps alias analysis out a lot, allows many others simplifications, and
8173     // exposes redundancy in the code.
8174     //
8175     // Note that we cannot do the transformation unless we know that the
8176     // introduced loads cannot trap!  Something like this is valid as long as
8177     // the condition is always false: load (select bool %C, int* null, int* %G),
8178     // but it would not be valid if we transformed it to load from null
8179     // unconditionally.
8180     //
8181     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8182       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8183       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8184           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8185         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8186                                      SI->getOperand(1)->getName()+".val"), LI);
8187         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8188                                      SI->getOperand(2)->getName()+".val"), LI);
8189         return new SelectInst(SI->getCondition(), V1, V2);
8190       }
8191
8192       // load (select (cond, null, P)) -> load P
8193       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8194         if (C->isNullValue()) {
8195           LI.setOperand(0, SI->getOperand(2));
8196           return &LI;
8197         }
8198
8199       // load (select (cond, P, null)) -> load P
8200       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8201         if (C->isNullValue()) {
8202           LI.setOperand(0, SI->getOperand(1));
8203           return &LI;
8204         }
8205     }
8206   }
8207   return 0;
8208 }
8209
8210 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8211 /// when possible.
8212 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8213   User *CI = cast<User>(SI.getOperand(1));
8214   Value *CastOp = CI->getOperand(0);
8215
8216   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8217   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8218     const Type *SrcPTy = SrcTy->getElementType();
8219
8220     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8221       // If the source is an array, the code below will not succeed.  Check to
8222       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8223       // constants.
8224       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8225         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8226           if (ASrcTy->getNumElements() != 0) {
8227             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
8228             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8229             SrcTy = cast<PointerType>(CastOp->getType());
8230             SrcPTy = SrcTy->getElementType();
8231           }
8232
8233       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8234           IC.getTargetData().getTypeSize(SrcPTy) ==
8235                IC.getTargetData().getTypeSize(DestPTy)) {
8236
8237         // Okay, we are casting from one integer or pointer type to another of
8238         // the same size.  Instead of casting the pointer before the store, cast
8239         // the value to be stored.
8240         Value *NewCast;
8241         Instruction::CastOps opcode = Instruction::BitCast;
8242         Value *SIOp0 = SI.getOperand(0);
8243         if (isa<PointerType>(SrcPTy)) {
8244           if (SIOp0->getType()->isIntegral())
8245             opcode = Instruction::IntToPtr;
8246         } else if (SrcPTy->isIntegral()) {
8247           if (isa<PointerType>(SIOp0->getType()))
8248             opcode = Instruction::PtrToInt;
8249         }
8250         if (Constant *C = dyn_cast<Constant>(SIOp0))
8251           NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
8252         else
8253           NewCast = IC.InsertNewInstBefore(
8254             CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
8255         return new StoreInst(NewCast, CastOp);
8256       }
8257     }
8258   }
8259   return 0;
8260 }
8261
8262 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8263   Value *Val = SI.getOperand(0);
8264   Value *Ptr = SI.getOperand(1);
8265
8266   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8267     EraseInstFromFunction(SI);
8268     ++NumCombined;
8269     return 0;
8270   }
8271
8272   // Do really simple DSE, to catch cases where there are several consequtive
8273   // stores to the same location, separated by a few arithmetic operations. This
8274   // situation often occurs with bitfield accesses.
8275   BasicBlock::iterator BBI = &SI;
8276   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8277        --ScanInsts) {
8278     --BBI;
8279     
8280     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8281       // Prev store isn't volatile, and stores to the same location?
8282       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8283         ++NumDeadStore;
8284         ++BBI;
8285         EraseInstFromFunction(*PrevSI);
8286         continue;
8287       }
8288       break;
8289     }
8290     
8291     // If this is a load, we have to stop.  However, if the loaded value is from
8292     // the pointer we're loading and is producing the pointer we're storing,
8293     // then *this* store is dead (X = load P; store X -> P).
8294     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8295       if (LI == Val && LI->getOperand(0) == Ptr) {
8296         EraseInstFromFunction(SI);
8297         ++NumCombined;
8298         return 0;
8299       }
8300       // Otherwise, this is a load from some other location.  Stores before it
8301       // may not be dead.
8302       break;
8303     }
8304     
8305     // Don't skip over loads or things that can modify memory.
8306     if (BBI->mayWriteToMemory())
8307       break;
8308   }
8309   
8310   
8311   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8312
8313   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8314   if (isa<ConstantPointerNull>(Ptr)) {
8315     if (!isa<UndefValue>(Val)) {
8316       SI.setOperand(0, UndefValue::get(Val->getType()));
8317       if (Instruction *U = dyn_cast<Instruction>(Val))
8318         WorkList.push_back(U);  // Dropped a use.
8319       ++NumCombined;
8320     }
8321     return 0;  // Do not modify these!
8322   }
8323
8324   // store undef, Ptr -> noop
8325   if (isa<UndefValue>(Val)) {
8326     EraseInstFromFunction(SI);
8327     ++NumCombined;
8328     return 0;
8329   }
8330
8331   // If the pointer destination is a cast, see if we can fold the cast into the
8332   // source instead.
8333   if (isa<CastInst>(Ptr))
8334     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8335       return Res;
8336   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8337     if (CE->isCast())
8338       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8339         return Res;
8340
8341   
8342   // If this store is the last instruction in the basic block, and if the block
8343   // ends with an unconditional branch, try to move it to the successor block.
8344   BBI = &SI; ++BBI;
8345   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8346     if (BI->isUnconditional()) {
8347       // Check to see if the successor block has exactly two incoming edges.  If
8348       // so, see if the other predecessor contains a store to the same location.
8349       // if so, insert a PHI node (if needed) and move the stores down.
8350       BasicBlock *Dest = BI->getSuccessor(0);
8351
8352       pred_iterator PI = pred_begin(Dest);
8353       BasicBlock *Other = 0;
8354       if (*PI != BI->getParent())
8355         Other = *PI;
8356       ++PI;
8357       if (PI != pred_end(Dest)) {
8358         if (*PI != BI->getParent())
8359           if (Other)
8360             Other = 0;
8361           else
8362             Other = *PI;
8363         if (++PI != pred_end(Dest))
8364           Other = 0;
8365       }
8366       if (Other) {  // If only one other pred...
8367         BBI = Other->getTerminator();
8368         // Make sure this other block ends in an unconditional branch and that
8369         // there is an instruction before the branch.
8370         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8371             BBI != Other->begin()) {
8372           --BBI;
8373           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8374           
8375           // If this instruction is a store to the same location.
8376           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8377             // Okay, we know we can perform this transformation.  Insert a PHI
8378             // node now if we need it.
8379             Value *MergedVal = OtherStore->getOperand(0);
8380             if (MergedVal != SI.getOperand(0)) {
8381               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8382               PN->reserveOperandSpace(2);
8383               PN->addIncoming(SI.getOperand(0), SI.getParent());
8384               PN->addIncoming(OtherStore->getOperand(0), Other);
8385               MergedVal = InsertNewInstBefore(PN, Dest->front());
8386             }
8387             
8388             // Advance to a place where it is safe to insert the new store and
8389             // insert it.
8390             BBI = Dest->begin();
8391             while (isa<PHINode>(BBI)) ++BBI;
8392             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8393                                               OtherStore->isVolatile()), *BBI);
8394
8395             // Nuke the old stores.
8396             EraseInstFromFunction(SI);
8397             EraseInstFromFunction(*OtherStore);
8398             ++NumCombined;
8399             return 0;
8400           }
8401         }
8402       }
8403     }
8404   
8405   return 0;
8406 }
8407
8408
8409 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8410   // Change br (not X), label True, label False to: br X, label False, True
8411   Value *X = 0;
8412   BasicBlock *TrueDest;
8413   BasicBlock *FalseDest;
8414   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8415       !isa<Constant>(X)) {
8416     // Swap Destinations and condition...
8417     BI.setCondition(X);
8418     BI.setSuccessor(0, FalseDest);
8419     BI.setSuccessor(1, TrueDest);
8420     return &BI;
8421   }
8422
8423   // Cannonicalize fcmp_one -> fcmp_oeq
8424   FCmpInst::Predicate FPred; Value *Y;
8425   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8426                              TrueDest, FalseDest)))
8427     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8428          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8429       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8430       std::string Name = I->getName(); I->setName("");
8431       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8432       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8433       // Swap Destinations and condition...
8434       BI.setCondition(NewSCC);
8435       BI.setSuccessor(0, FalseDest);
8436       BI.setSuccessor(1, TrueDest);
8437       removeFromWorkList(I);
8438       I->getParent()->getInstList().erase(I);
8439       WorkList.push_back(cast<Instruction>(NewSCC));
8440       return &BI;
8441     }
8442
8443   // Cannonicalize icmp_ne -> icmp_eq
8444   ICmpInst::Predicate IPred;
8445   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8446                       TrueDest, FalseDest)))
8447     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8448          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8449          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8450       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8451       std::string Name = I->getName(); I->setName("");
8452       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8453       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8454       // Swap Destinations and condition...
8455       BI.setCondition(NewSCC);
8456       BI.setSuccessor(0, FalseDest);
8457       BI.setSuccessor(1, TrueDest);
8458       removeFromWorkList(I);
8459       I->getParent()->getInstList().erase(I);
8460       WorkList.push_back(cast<Instruction>(NewSCC));
8461       return &BI;
8462     }
8463
8464   return 0;
8465 }
8466
8467 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8468   Value *Cond = SI.getCondition();
8469   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8470     if (I->getOpcode() == Instruction::Add)
8471       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8472         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8473         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8474           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8475                                                 AddRHS));
8476         SI.setOperand(0, I->getOperand(0));
8477         WorkList.push_back(I);
8478         return &SI;
8479       }
8480   }
8481   return 0;
8482 }
8483
8484 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8485 /// is to leave as a vector operation.
8486 static bool CheapToScalarize(Value *V, bool isConstant) {
8487   if (isa<ConstantAggregateZero>(V)) 
8488     return true;
8489   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8490     if (isConstant) return true;
8491     // If all elts are the same, we can extract.
8492     Constant *Op0 = C->getOperand(0);
8493     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8494       if (C->getOperand(i) != Op0)
8495         return false;
8496     return true;
8497   }
8498   Instruction *I = dyn_cast<Instruction>(V);
8499   if (!I) return false;
8500   
8501   // Insert element gets simplified to the inserted element or is deleted if
8502   // this is constant idx extract element and its a constant idx insertelt.
8503   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8504       isa<ConstantInt>(I->getOperand(2)))
8505     return true;
8506   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8507     return true;
8508   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8509     if (BO->hasOneUse() &&
8510         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8511          CheapToScalarize(BO->getOperand(1), isConstant)))
8512       return true;
8513   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8514     if (CI->hasOneUse() &&
8515         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8516          CheapToScalarize(CI->getOperand(1), isConstant)))
8517       return true;
8518   
8519   return false;
8520 }
8521
8522 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8523 /// elements into values that are larger than the #elts in the input.
8524 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8525   unsigned NElts = SVI->getType()->getNumElements();
8526   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8527     return std::vector<unsigned>(NElts, 0);
8528   if (isa<UndefValue>(SVI->getOperand(2)))
8529     return std::vector<unsigned>(NElts, 2*NElts);
8530
8531   std::vector<unsigned> Result;
8532   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8533   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8534     if (isa<UndefValue>(CP->getOperand(i)))
8535       Result.push_back(NElts*2);  // undef -> 8
8536     else
8537       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8538   return Result;
8539 }
8540
8541 /// FindScalarElement - Given a vector and an element number, see if the scalar
8542 /// value is already around as a register, for example if it were inserted then
8543 /// extracted from the vector.
8544 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8545   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8546   const PackedType *PTy = cast<PackedType>(V->getType());
8547   unsigned Width = PTy->getNumElements();
8548   if (EltNo >= Width)  // Out of range access.
8549     return UndefValue::get(PTy->getElementType());
8550   
8551   if (isa<UndefValue>(V))
8552     return UndefValue::get(PTy->getElementType());
8553   else if (isa<ConstantAggregateZero>(V))
8554     return Constant::getNullValue(PTy->getElementType());
8555   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8556     return CP->getOperand(EltNo);
8557   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8558     // If this is an insert to a variable element, we don't know what it is.
8559     if (!isa<ConstantInt>(III->getOperand(2))) 
8560       return 0;
8561     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8562     
8563     // If this is an insert to the element we are looking for, return the
8564     // inserted value.
8565     if (EltNo == IIElt) 
8566       return III->getOperand(1);
8567     
8568     // Otherwise, the insertelement doesn't modify the value, recurse on its
8569     // vector input.
8570     return FindScalarElement(III->getOperand(0), EltNo);
8571   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8572     unsigned InEl = getShuffleMask(SVI)[EltNo];
8573     if (InEl < Width)
8574       return FindScalarElement(SVI->getOperand(0), InEl);
8575     else if (InEl < Width*2)
8576       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8577     else
8578       return UndefValue::get(PTy->getElementType());
8579   }
8580   
8581   // Otherwise, we don't know.
8582   return 0;
8583 }
8584
8585 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8586
8587   // If packed val is undef, replace extract with scalar undef.
8588   if (isa<UndefValue>(EI.getOperand(0)))
8589     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8590
8591   // If packed val is constant 0, replace extract with scalar 0.
8592   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8593     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8594   
8595   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8596     // If packed val is constant with uniform operands, replace EI
8597     // with that operand
8598     Constant *op0 = C->getOperand(0);
8599     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8600       if (C->getOperand(i) != op0) {
8601         op0 = 0; 
8602         break;
8603       }
8604     if (op0)
8605       return ReplaceInstUsesWith(EI, op0);
8606   }
8607   
8608   // If extracting a specified index from the vector, see if we can recursively
8609   // find a previously computed scalar that was inserted into the vector.
8610   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8611     // This instruction only demands the single element from the input vector.
8612     // If the input vector has a single use, simplify it based on this use
8613     // property.
8614     uint64_t IndexVal = IdxC->getZExtValue();
8615     if (EI.getOperand(0)->hasOneUse()) {
8616       uint64_t UndefElts;
8617       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8618                                                 1 << IndexVal,
8619                                                 UndefElts)) {
8620         EI.setOperand(0, V);
8621         return &EI;
8622       }
8623     }
8624     
8625     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8626       return ReplaceInstUsesWith(EI, Elt);
8627   }
8628   
8629   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8630     if (I->hasOneUse()) {
8631       // Push extractelement into predecessor operation if legal and
8632       // profitable to do so
8633       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8634         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8635         if (CheapToScalarize(BO, isConstantElt)) {
8636           ExtractElementInst *newEI0 = 
8637             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8638                                    EI.getName()+".lhs");
8639           ExtractElementInst *newEI1 =
8640             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8641                                    EI.getName()+".rhs");
8642           InsertNewInstBefore(newEI0, EI);
8643           InsertNewInstBefore(newEI1, EI);
8644           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8645         }
8646       } else if (isa<LoadInst>(I)) {
8647         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8648                                       PointerType::get(EI.getType()), EI);
8649         GetElementPtrInst *GEP = 
8650           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8651         InsertNewInstBefore(GEP, EI);
8652         return new LoadInst(GEP);
8653       }
8654     }
8655     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8656       // Extracting the inserted element?
8657       if (IE->getOperand(2) == EI.getOperand(1))
8658         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8659       // If the inserted and extracted elements are constants, they must not
8660       // be the same value, extract from the pre-inserted value instead.
8661       if (isa<Constant>(IE->getOperand(2)) &&
8662           isa<Constant>(EI.getOperand(1))) {
8663         AddUsesToWorkList(EI);
8664         EI.setOperand(0, IE->getOperand(0));
8665         return &EI;
8666       }
8667     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8668       // If this is extracting an element from a shufflevector, figure out where
8669       // it came from and extract from the appropriate input element instead.
8670       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8671         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8672         Value *Src;
8673         if (SrcIdx < SVI->getType()->getNumElements())
8674           Src = SVI->getOperand(0);
8675         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8676           SrcIdx -= SVI->getType()->getNumElements();
8677           Src = SVI->getOperand(1);
8678         } else {
8679           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8680         }
8681         return new ExtractElementInst(Src, SrcIdx);
8682       }
8683     }
8684   }
8685   return 0;
8686 }
8687
8688 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8689 /// elements from either LHS or RHS, return the shuffle mask and true. 
8690 /// Otherwise, return false.
8691 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8692                                          std::vector<Constant*> &Mask) {
8693   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8694          "Invalid CollectSingleShuffleElements");
8695   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8696
8697   if (isa<UndefValue>(V)) {
8698     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8699     return true;
8700   } else if (V == LHS) {
8701     for (unsigned i = 0; i != NumElts; ++i)
8702       Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8703     return true;
8704   } else if (V == RHS) {
8705     for (unsigned i = 0; i != NumElts; ++i)
8706       Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
8707     return true;
8708   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8709     // If this is an insert of an extract from some other vector, include it.
8710     Value *VecOp    = IEI->getOperand(0);
8711     Value *ScalarOp = IEI->getOperand(1);
8712     Value *IdxOp    = IEI->getOperand(2);
8713     
8714     if (!isa<ConstantInt>(IdxOp))
8715       return false;
8716     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8717     
8718     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8719       // Okay, we can handle this if the vector we are insertinting into is
8720       // transitively ok.
8721       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8722         // If so, update the mask to reflect the inserted undef.
8723         Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8724         return true;
8725       }      
8726     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8727       if (isa<ConstantInt>(EI->getOperand(1)) &&
8728           EI->getOperand(0)->getType() == V->getType()) {
8729         unsigned ExtractedIdx =
8730           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8731         
8732         // This must be extracting from either LHS or RHS.
8733         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8734           // Okay, we can handle this if the vector we are insertinting into is
8735           // transitively ok.
8736           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8737             // If so, update the mask to reflect the inserted value.
8738             if (EI->getOperand(0) == LHS) {
8739               Mask[InsertedIdx & (NumElts-1)] = 
8740                  ConstantInt::get(Type::UIntTy, ExtractedIdx);
8741             } else {
8742               assert(EI->getOperand(0) == RHS);
8743               Mask[InsertedIdx & (NumElts-1)] = 
8744                 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
8745               
8746             }
8747             return true;
8748           }
8749         }
8750       }
8751     }
8752   }
8753   // TODO: Handle shufflevector here!
8754   
8755   return false;
8756 }
8757
8758 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8759 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8760 /// that computes V and the LHS value of the shuffle.
8761 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8762                                      Value *&RHS) {
8763   assert(isa<PackedType>(V->getType()) && 
8764          (RHS == 0 || V->getType() == RHS->getType()) &&
8765          "Invalid shuffle!");
8766   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8767
8768   if (isa<UndefValue>(V)) {
8769     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8770     return V;
8771   } else if (isa<ConstantAggregateZero>(V)) {
8772     Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
8773     return V;
8774   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8775     // If this is an insert of an extract from some other vector, include it.
8776     Value *VecOp    = IEI->getOperand(0);
8777     Value *ScalarOp = IEI->getOperand(1);
8778     Value *IdxOp    = IEI->getOperand(2);
8779     
8780     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8781       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8782           EI->getOperand(0)->getType() == V->getType()) {
8783         unsigned ExtractedIdx =
8784           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8785         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8786         
8787         // Either the extracted from or inserted into vector must be RHSVec,
8788         // otherwise we'd end up with a shuffle of three inputs.
8789         if (EI->getOperand(0) == RHS || RHS == 0) {
8790           RHS = EI->getOperand(0);
8791           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8792           Mask[InsertedIdx & (NumElts-1)] = 
8793             ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
8794           return V;
8795         }
8796         
8797         if (VecOp == RHS) {
8798           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8799           // Everything but the extracted element is replaced with the RHS.
8800           for (unsigned i = 0; i != NumElts; ++i) {
8801             if (i != InsertedIdx)
8802               Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
8803           }
8804           return V;
8805         }
8806         
8807         // If this insertelement is a chain that comes from exactly these two
8808         // vectors, return the vector and the effective shuffle.
8809         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8810           return EI->getOperand(0);
8811         
8812       }
8813     }
8814   }
8815   // TODO: Handle shufflevector here!
8816   
8817   // Otherwise, can't do anything fancy.  Return an identity vector.
8818   for (unsigned i = 0; i != NumElts; ++i)
8819     Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8820   return V;
8821 }
8822
8823 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8824   Value *VecOp    = IE.getOperand(0);
8825   Value *ScalarOp = IE.getOperand(1);
8826   Value *IdxOp    = IE.getOperand(2);
8827   
8828   // If the inserted element was extracted from some other vector, and if the 
8829   // indexes are constant, try to turn this into a shufflevector operation.
8830   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8831     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8832         EI->getOperand(0)->getType() == IE.getType()) {
8833       unsigned NumVectorElts = IE.getType()->getNumElements();
8834       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8835       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8836       
8837       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8838         return ReplaceInstUsesWith(IE, VecOp);
8839       
8840       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8841         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8842       
8843       // If we are extracting a value from a vector, then inserting it right
8844       // back into the same place, just use the input vector.
8845       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8846         return ReplaceInstUsesWith(IE, VecOp);      
8847       
8848       // We could theoretically do this for ANY input.  However, doing so could
8849       // turn chains of insertelement instructions into a chain of shufflevector
8850       // instructions, and right now we do not merge shufflevectors.  As such,
8851       // only do this in a situation where it is clear that there is benefit.
8852       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8853         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8854         // the values of VecOp, except then one read from EIOp0.
8855         // Build a new shuffle mask.
8856         std::vector<Constant*> Mask;
8857         if (isa<UndefValue>(VecOp))
8858           Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8859         else {
8860           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8861           Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8862                                                        NumVectorElts));
8863         } 
8864         Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8865         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8866                                      ConstantPacked::get(Mask));
8867       }
8868       
8869       // If this insertelement isn't used by some other insertelement, turn it
8870       // (and any insertelements it points to), into one big shuffle.
8871       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8872         std::vector<Constant*> Mask;
8873         Value *RHS = 0;
8874         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8875         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8876         // We now have a shuffle of LHS, RHS, Mask.
8877         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8878       }
8879     }
8880   }
8881
8882   return 0;
8883 }
8884
8885
8886 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8887   Value *LHS = SVI.getOperand(0);
8888   Value *RHS = SVI.getOperand(1);
8889   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8890
8891   bool MadeChange = false;
8892   
8893   // Undefined shuffle mask -> undefined value.
8894   if (isa<UndefValue>(SVI.getOperand(2)))
8895     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8896   
8897   // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8898   // the undef, change them to undefs.
8899   
8900   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8901   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8902   if (LHS == RHS || isa<UndefValue>(LHS)) {
8903     if (isa<UndefValue>(LHS) && LHS == RHS) {
8904       // shuffle(undef,undef,mask) -> undef.
8905       return ReplaceInstUsesWith(SVI, LHS);
8906     }
8907     
8908     // Remap any references to RHS to use LHS.
8909     std::vector<Constant*> Elts;
8910     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8911       if (Mask[i] >= 2*e)
8912         Elts.push_back(UndefValue::get(Type::UIntTy));
8913       else {
8914         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8915             (Mask[i] <  e && isa<UndefValue>(LHS)))
8916           Mask[i] = 2*e;     // Turn into undef.
8917         else
8918           Mask[i] &= (e-1);  // Force to LHS.
8919         Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8920       }
8921     }
8922     SVI.setOperand(0, SVI.getOperand(1));
8923     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8924     SVI.setOperand(2, ConstantPacked::get(Elts));
8925     LHS = SVI.getOperand(0);
8926     RHS = SVI.getOperand(1);
8927     MadeChange = true;
8928   }
8929   
8930   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8931   bool isLHSID = true, isRHSID = true;
8932     
8933   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8934     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8935     // Is this an identity shuffle of the LHS value?
8936     isLHSID &= (Mask[i] == i);
8937       
8938     // Is this an identity shuffle of the RHS value?
8939     isRHSID &= (Mask[i]-e == i);
8940   }
8941
8942   // Eliminate identity shuffles.
8943   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8944   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8945   
8946   // If the LHS is a shufflevector itself, see if we can combine it with this
8947   // one without producing an unusual shuffle.  Here we are really conservative:
8948   // we are absolutely afraid of producing a shuffle mask not in the input
8949   // program, because the code gen may not be smart enough to turn a merged
8950   // shuffle into two specific shuffles: it may produce worse code.  As such,
8951   // we only merge two shuffles if the result is one of the two input shuffle
8952   // masks.  In this case, merging the shuffles just removes one instruction,
8953   // which we know is safe.  This is good for things like turning:
8954   // (splat(splat)) -> splat.
8955   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8956     if (isa<UndefValue>(RHS)) {
8957       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8958
8959       std::vector<unsigned> NewMask;
8960       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8961         if (Mask[i] >= 2*e)
8962           NewMask.push_back(2*e);
8963         else
8964           NewMask.push_back(LHSMask[Mask[i]]);
8965       
8966       // If the result mask is equal to the src shuffle or this shuffle mask, do
8967       // the replacement.
8968       if (NewMask == LHSMask || NewMask == Mask) {
8969         std::vector<Constant*> Elts;
8970         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8971           if (NewMask[i] >= e*2) {
8972             Elts.push_back(UndefValue::get(Type::UIntTy));
8973           } else {
8974             Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8975           }
8976         }
8977         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8978                                      LHSSVI->getOperand(1),
8979                                      ConstantPacked::get(Elts));
8980       }
8981     }
8982   }
8983   
8984   return MadeChange ? &SVI : 0;
8985 }
8986
8987
8988
8989 void InstCombiner::removeFromWorkList(Instruction *I) {
8990   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8991                  WorkList.end());
8992 }
8993
8994
8995 /// TryToSinkInstruction - Try to move the specified instruction from its
8996 /// current block into the beginning of DestBlock, which can only happen if it's
8997 /// safe to move the instruction past all of the instructions between it and the
8998 /// end of its block.
8999 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9000   assert(I->hasOneUse() && "Invariants didn't hold!");
9001
9002   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9003   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9004
9005   // Do not sink alloca instructions out of the entry block.
9006   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9007     return false;
9008
9009   // We can only sink load instructions if there is nothing between the load and
9010   // the end of block that could change the value.
9011   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9012     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9013          Scan != E; ++Scan)
9014       if (Scan->mayWriteToMemory())
9015         return false;
9016   }
9017
9018   BasicBlock::iterator InsertPos = DestBlock->begin();
9019   while (isa<PHINode>(InsertPos)) ++InsertPos;
9020
9021   I->moveBefore(InsertPos);
9022   ++NumSunkInst;
9023   return true;
9024 }
9025
9026 /// OptimizeConstantExpr - Given a constant expression and target data layout
9027 /// information, symbolically evaluate the constant expr to something simpler
9028 /// if possible.
9029 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9030   if (!TD) return CE;
9031   
9032   Constant *Ptr = CE->getOperand(0);
9033   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9034       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9035     // If this is a constant expr gep that is effectively computing an
9036     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9037     bool isFoldableGEP = true;
9038     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9039       if (!isa<ConstantInt>(CE->getOperand(i)))
9040         isFoldableGEP = false;
9041     if (isFoldableGEP) {
9042       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9043       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
9044       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
9045       return ConstantExpr::getIntToPtr(C, CE->getType());
9046     }
9047   }
9048   
9049   return CE;
9050 }
9051
9052
9053 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9054 /// all reachable code to the worklist.
9055 ///
9056 /// This has a couple of tricks to make the code faster and more powerful.  In
9057 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9058 /// them to the worklist (this significantly speeds up instcombine on code where
9059 /// many instructions are dead or constant).  Additionally, if we find a branch
9060 /// whose condition is a known constant, we only visit the reachable successors.
9061 ///
9062 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9063                                        std::set<BasicBlock*> &Visited,
9064                                        std::vector<Instruction*> &WorkList,
9065                                        const TargetData *TD) {
9066   // We have now visited this block!  If we've already been here, bail out.
9067   if (!Visited.insert(BB).second) return;
9068     
9069   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9070     Instruction *Inst = BBI++;
9071     
9072     // DCE instruction if trivially dead.
9073     if (isInstructionTriviallyDead(Inst)) {
9074       ++NumDeadInst;
9075       DOUT << "IC: DCE: " << *Inst;
9076       Inst->eraseFromParent();
9077       continue;
9078     }
9079     
9080     // ConstantProp instruction if trivially constant.
9081     if (Constant *C = ConstantFoldInstruction(Inst)) {
9082       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9083         C = OptimizeConstantExpr(CE, TD);
9084       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9085       Inst->replaceAllUsesWith(C);
9086       ++NumConstProp;
9087       Inst->eraseFromParent();
9088       continue;
9089     }
9090     
9091     WorkList.push_back(Inst);
9092   }
9093
9094   // Recursively visit successors.  If this is a branch or switch on a constant,
9095   // only visit the reachable successor.
9096   TerminatorInst *TI = BB->getTerminator();
9097   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9098     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9099       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
9100       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9101                                  TD);
9102       return;
9103     }
9104   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9105     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9106       // See if this is an explicit destination.
9107       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9108         if (SI->getCaseValue(i) == Cond) {
9109           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9110           return;
9111         }
9112       
9113       // Otherwise it is the default destination.
9114       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9115       return;
9116     }
9117   }
9118   
9119   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9120     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9121 }
9122
9123 bool InstCombiner::runOnFunction(Function &F) {
9124   bool Changed = false;
9125   TD = &getAnalysis<TargetData>();
9126
9127   {
9128     // Do a depth-first traversal of the function, populate the worklist with
9129     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9130     // track of which blocks we visit.
9131     std::set<BasicBlock*> Visited;
9132     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9133
9134     // Do a quick scan over the function.  If we find any blocks that are
9135     // unreachable, remove any instructions inside of them.  This prevents
9136     // the instcombine code from having to deal with some bad special cases.
9137     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9138       if (!Visited.count(BB)) {
9139         Instruction *Term = BB->getTerminator();
9140         while (Term != BB->begin()) {   // Remove instrs bottom-up
9141           BasicBlock::iterator I = Term; --I;
9142
9143           DOUT << "IC: DCE: " << *I;
9144           ++NumDeadInst;
9145
9146           if (!I->use_empty())
9147             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9148           I->eraseFromParent();
9149         }
9150       }
9151   }
9152
9153   while (!WorkList.empty()) {
9154     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9155     WorkList.pop_back();
9156
9157     // Check to see if we can DCE the instruction.
9158     if (isInstructionTriviallyDead(I)) {
9159       // Add operands to the worklist.
9160       if (I->getNumOperands() < 4)
9161         AddUsesToWorkList(*I);
9162       ++NumDeadInst;
9163
9164       DOUT << "IC: DCE: " << *I;
9165
9166       I->eraseFromParent();
9167       removeFromWorkList(I);
9168       continue;
9169     }
9170
9171     // Instruction isn't dead, see if we can constant propagate it.
9172     if (Constant *C = ConstantFoldInstruction(I)) {
9173       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9174         C = OptimizeConstantExpr(CE, TD);
9175       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9176
9177       // Add operands to the worklist.
9178       AddUsesToWorkList(*I);
9179       ReplaceInstUsesWith(*I, C);
9180
9181       ++NumConstProp;
9182       I->eraseFromParent();
9183       removeFromWorkList(I);
9184       continue;
9185     }
9186
9187     // See if we can trivially sink this instruction to a successor basic block.
9188     if (I->hasOneUse()) {
9189       BasicBlock *BB = I->getParent();
9190       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9191       if (UserParent != BB) {
9192         bool UserIsSuccessor = false;
9193         // See if the user is one of our successors.
9194         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9195           if (*SI == UserParent) {
9196             UserIsSuccessor = true;
9197             break;
9198           }
9199
9200         // If the user is one of our immediate successors, and if that successor
9201         // only has us as a predecessors (we'd have to split the critical edge
9202         // otherwise), we can keep going.
9203         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9204             next(pred_begin(UserParent)) == pred_end(UserParent))
9205           // Okay, the CFG is simple enough, try to sink this instruction.
9206           Changed |= TryToSinkInstruction(I, UserParent);
9207       }
9208     }
9209
9210     // Now that we have an instruction, try combining it to simplify it...
9211     if (Instruction *Result = visit(*I)) {
9212       ++NumCombined;
9213       // Should we replace the old instruction with a new one?
9214       if (Result != I) {
9215         DOUT << "IC: Old = " << *I
9216              << "    New = " << *Result;
9217
9218         // Everything uses the new instruction now.
9219         I->replaceAllUsesWith(Result);
9220
9221         // Push the new instruction and any users onto the worklist.
9222         WorkList.push_back(Result);
9223         AddUsersToWorkList(*Result);
9224
9225         // Move the name to the new instruction first...
9226         std::string OldName = I->getName(); I->setName("");
9227         Result->setName(OldName);
9228
9229         // Insert the new instruction into the basic block...
9230         BasicBlock *InstParent = I->getParent();
9231         BasicBlock::iterator InsertPos = I;
9232
9233         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9234           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9235             ++InsertPos;
9236
9237         InstParent->getInstList().insert(InsertPos, Result);
9238
9239         // Make sure that we reprocess all operands now that we reduced their
9240         // use counts.
9241         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9242           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9243             WorkList.push_back(OpI);
9244
9245         // Instructions can end up on the worklist more than once.  Make sure
9246         // we do not process an instruction that has been deleted.
9247         removeFromWorkList(I);
9248
9249         // Erase the old instruction.
9250         InstParent->getInstList().erase(I);
9251       } else {
9252         DOUT << "IC: MOD = " << *I;
9253
9254         // If the instruction was modified, it's possible that it is now dead.
9255         // if so, remove it.
9256         if (isInstructionTriviallyDead(I)) {
9257           // Make sure we process all operands now that we are reducing their
9258           // use counts.
9259           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9260             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9261               WorkList.push_back(OpI);
9262
9263           // Instructions may end up in the worklist more than once.  Erase all
9264           // occurrences of this instruction.
9265           removeFromWorkList(I);
9266           I->eraseFromParent();
9267         } else {
9268           WorkList.push_back(Result);
9269           AddUsersToWorkList(*Result);
9270         }
9271       }
9272       Changed = true;
9273     }
9274   }
9275
9276   return Changed;
9277 }
9278
9279 FunctionPass *llvm::createInstructionCombiningPass() {
9280   return new InstCombiner();
9281 }
9282