For PR950:
[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::Int8TyID:
344   case Type::Int16TyID:  return Type::Int32Ty;
345   case Type::FloatTyID:  return Type::DoubleTy;
346   default:               return Ty;
347   }
348 }
349
350 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
351 /// expression bitcast,  return the operand value, otherwise return null.
352 static Value *getBitCastOperand(Value *V) {
353   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
354     return I->getOperand(0);
355   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
356     if (CE->getOpcode() == Instruction::BitCast)
357       return CE->getOperand(0);
358   return 0;
359 }
360
361 /// This function is a wrapper around CastInst::isEliminableCastPair. It
362 /// simply extracts arguments and returns what that function returns.
363 /// @Determine if it is valid to eliminate a Convert pair
364 static Instruction::CastOps 
365 isEliminableCastPair(
366   const CastInst *CI, ///< The first cast instruction
367   unsigned opcode,       ///< The opcode of the second cast instruction
368   const Type *DstTy,     ///< The target type for the second cast instruction
369   TargetData *TD         ///< The target data for pointer size
370 ) {
371   
372   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
373   const Type *MidTy = CI->getType();                  // B from above
374
375   // Get the opcodes of the two Cast instructions
376   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
378
379   return Instruction::CastOps(
380       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381                                      DstTy, TD->getIntPtrType()));
382 }
383
384 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385 /// in any code being generated.  It does not require codegen if V is simple
386 /// enough or if the cast can be folded into other casts.
387 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
388                               const Type *Ty, TargetData *TD) {
389   if (V->getType() == Ty || isa<Constant>(V)) return false;
390   
391   // If this is a noop cast, it isn't real codegen.
392   if (V->getType()->canLosslesslyBitCastTo(Ty))
393     return false;
394
395   // If this is another cast that can be eliminated, it isn't codegen either.
396   if (const CastInst *CI = dyn_cast<CastInst>(V))
397     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
398       return false;
399   return true;
400 }
401
402 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
403 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
404 /// casts that are known to not do anything...
405 ///
406 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
407                                              Value *V, const Type *DestTy,
408                                              Instruction *InsertBefore) {
409   if (V->getType() == DestTy) return V;
410   if (Constant *C = dyn_cast<Constant>(V))
411     return ConstantExpr::getCast(opcode, C, DestTy);
412   
413   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
414 }
415
416 // SimplifyCommutative - This performs a few simplifications for commutative
417 // operators:
418 //
419 //  1. Order operands such that they are listed from right (least complex) to
420 //     left (most complex).  This puts constants before unary operators before
421 //     binary operators.
422 //
423 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
424 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
425 //
426 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
427   bool Changed = false;
428   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
429     Changed = !I.swapOperands();
430
431   if (!I.isAssociative()) return Changed;
432   Instruction::BinaryOps Opcode = I.getOpcode();
433   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
434     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
435       if (isa<Constant>(I.getOperand(1))) {
436         Constant *Folded = ConstantExpr::get(I.getOpcode(),
437                                              cast<Constant>(I.getOperand(1)),
438                                              cast<Constant>(Op->getOperand(1)));
439         I.setOperand(0, Op->getOperand(0));
440         I.setOperand(1, Folded);
441         return true;
442       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
443         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
444             isOnlyUse(Op) && isOnlyUse(Op1)) {
445           Constant *C1 = cast<Constant>(Op->getOperand(1));
446           Constant *C2 = cast<Constant>(Op1->getOperand(1));
447
448           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
449           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
450           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
451                                                     Op1->getOperand(0),
452                                                     Op1->getName(), &I);
453           WorkList.push_back(New);
454           I.setOperand(0, New);
455           I.setOperand(1, Folded);
456           return true;
457         }
458     }
459   return Changed;
460 }
461
462 /// SimplifyCompare - For a CmpInst this function just orders the operands
463 /// so that theyare listed from right (least complex) to left (most complex).
464 /// This puts constants before unary operators before binary operators.
465 bool InstCombiner::SimplifyCompare(CmpInst &I) {
466   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
467     return false;
468   I.swapOperands();
469   // Compare instructions are not associative so there's nothing else we can do.
470   return true;
471 }
472
473 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
474 // if the LHS is a constant zero (which is the 'negate' form).
475 //
476 static inline Value *dyn_castNegVal(Value *V) {
477   if (BinaryOperator::isNeg(V))
478     return BinaryOperator::getNegArgument(V);
479
480   // Constants can be considered to be negated values if they can be folded.
481   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
482     return ConstantExpr::getNeg(C);
483   return 0;
484 }
485
486 static inline Value *dyn_castNotVal(Value *V) {
487   if (BinaryOperator::isNot(V))
488     return BinaryOperator::getNotArgument(V);
489
490   // Constants can be considered to be not'ed values...
491   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
492     return ConstantExpr::getNot(C);
493   return 0;
494 }
495
496 // dyn_castFoldableMul - If this value is a multiply that can be folded into
497 // other computations (because it has a constant operand), return the
498 // non-constant operand of the multiply, and set CST to point to the multiplier.
499 // Otherwise, return null.
500 //
501 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
502   if (V->hasOneUse() && V->getType()->isInteger())
503     if (Instruction *I = dyn_cast<Instruction>(V)) {
504       if (I->getOpcode() == Instruction::Mul)
505         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
506           return I->getOperand(0);
507       if (I->getOpcode() == Instruction::Shl)
508         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
509           // The multiplier is really 1 << CST.
510           Constant *One = ConstantInt::get(V->getType(), 1);
511           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
512           return I->getOperand(0);
513         }
514     }
515   return 0;
516 }
517
518 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
519 /// expression, return it.
520 static User *dyn_castGetElementPtr(Value *V) {
521   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
522   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
523     if (CE->getOpcode() == Instruction::GetElementPtr)
524       return cast<User>(V);
525   return false;
526 }
527
528 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
529 static ConstantInt *AddOne(ConstantInt *C) {
530   return cast<ConstantInt>(ConstantExpr::getAdd(C,
531                                          ConstantInt::get(C->getType(), 1)));
532 }
533 static ConstantInt *SubOne(ConstantInt *C) {
534   return cast<ConstantInt>(ConstantExpr::getSub(C,
535                                          ConstantInt::get(C->getType(), 1)));
536 }
537
538 /// GetConstantInType - Return a ConstantInt with the specified type and value.
539 ///
540 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
541   if (Ty->getTypeID() == Type::BoolTyID)
542     return ConstantBool::get(Val);
543   return ConstantInt::get(Ty, Val);
544 }
545
546
547 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
548 /// known to be either zero or one and return them in the KnownZero/KnownOne
549 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
550 /// processing.
551 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
552                               uint64_t &KnownOne, unsigned Depth = 0) {
553   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
554   // we cannot optimize based on the assumption that it is zero without changing
555   // it to be an explicit zero.  If we don't change it to zero, other code could
556   // optimized based on the contradictory assumption that it is non-zero.
557   // Because instcombine aggressively folds operations with undef args anyway,
558   // this won't lose us code quality.
559   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
560     // We know all of the bits for a constant!
561     KnownOne = CI->getZExtValue() & Mask;
562     KnownZero = ~KnownOne & Mask;
563     return;
564   }
565
566   KnownZero = KnownOne = 0;   // Don't know anything.
567   if (Depth == 6 || Mask == 0)
568     return;  // Limit search depth.
569
570   uint64_t KnownZero2, KnownOne2;
571   Instruction *I = dyn_cast<Instruction>(V);
572   if (!I) return;
573
574   Mask &= V->getType()->getIntegralTypeMask();
575   
576   switch (I->getOpcode()) {
577   case Instruction::And:
578     // If either the LHS or the RHS are Zero, the result is zero.
579     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
580     Mask &= ~KnownZero;
581     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
582     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
583     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
584     
585     // Output known-1 bits are only known if set in both the LHS & RHS.
586     KnownOne &= KnownOne2;
587     // Output known-0 are known to be clear if zero in either the LHS | RHS.
588     KnownZero |= KnownZero2;
589     return;
590   case Instruction::Or:
591     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
592     Mask &= ~KnownOne;
593     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
594     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
595     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
596     
597     // Output known-0 bits are only known if clear in both the LHS & RHS.
598     KnownZero &= KnownZero2;
599     // Output known-1 are known to be set if set in either the LHS | RHS.
600     KnownOne |= KnownOne2;
601     return;
602   case Instruction::Xor: {
603     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
604     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
605     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
606     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
607     
608     // Output known-0 bits are known if clear or set in both the LHS & RHS.
609     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
610     // Output known-1 are known to be set if set in only one of the LHS, RHS.
611     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
612     KnownZero = KnownZeroOut;
613     return;
614   }
615   case Instruction::Select:
616     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
617     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
618     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
619     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
620
621     // Only known if known in both the LHS and RHS.
622     KnownOne &= KnownOne2;
623     KnownZero &= KnownZero2;
624     return;
625   case Instruction::FPTrunc:
626   case Instruction::FPExt:
627   case Instruction::FPToUI:
628   case Instruction::FPToSI:
629   case Instruction::SIToFP:
630   case Instruction::PtrToInt:
631   case Instruction::UIToFP:
632   case Instruction::IntToPtr:
633     return; // Can't work with floating point or pointers
634   case Instruction::Trunc: 
635     // All these have integer operands
636     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
637     return;
638   case Instruction::BitCast: {
639     const Type *SrcTy = I->getOperand(0)->getType();
640     if (SrcTy->isIntegral()) {
641       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
642       return;
643     }
644     break;
645   }
646   case Instruction::ZExt:  {
647     // Compute the bits in the result that are not present in the input.
648     const Type *SrcTy = I->getOperand(0)->getType();
649     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
650     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
651       
652     Mask &= SrcTy->getIntegralTypeMask();
653     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
655     // The top bits are known to be zero.
656     KnownZero |= NewBits;
657     return;
658   }
659   case Instruction::SExt: {
660     // Compute the bits in the result that are not present in the input.
661     const Type *SrcTy = I->getOperand(0)->getType();
662     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
663     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
664       
665     Mask &= SrcTy->getIntegralTypeMask();
666     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
667     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
668
669     // If the sign bit of the input is known set or clear, then we know the
670     // top bits of the result.
671     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
672     if (KnownZero & InSignBit) {          // Input sign bit known zero
673       KnownZero |= NewBits;
674       KnownOne &= ~NewBits;
675     } else if (KnownOne & InSignBit) {    // Input sign bit known set
676       KnownOne |= NewBits;
677       KnownZero &= ~NewBits;
678     } else {                              // Input sign bit unknown
679       KnownZero &= ~NewBits;
680       KnownOne &= ~NewBits;
681     }
682     return;
683   }
684   case Instruction::Shl:
685     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
686     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687       uint64_t ShiftAmt = SA->getZExtValue();
688       Mask >>= ShiftAmt;
689       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
690       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
691       KnownZero <<= ShiftAmt;
692       KnownOne  <<= ShiftAmt;
693       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
694       return;
695     }
696     break;
697   case Instruction::LShr:
698     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
699     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
700       // Compute the new bits that are at the top now.
701       uint64_t ShiftAmt = SA->getZExtValue();
702       uint64_t HighBits = (1ULL << ShiftAmt)-1;
703       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
704       
705       // Unsigned shift right.
706       Mask <<= ShiftAmt;
707       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
708       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
709       KnownZero >>= ShiftAmt;
710       KnownOne  >>= ShiftAmt;
711       KnownZero |= HighBits;  // high bits known zero.
712       return;
713     }
714     break;
715   case Instruction::AShr:
716     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
717     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
718       // Compute the new bits that are at the top now.
719       uint64_t ShiftAmt = SA->getZExtValue();
720       uint64_t HighBits = (1ULL << ShiftAmt)-1;
721       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
722       
723       // Signed shift right.
724       Mask <<= ShiftAmt;
725       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
726       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
727       KnownZero >>= ShiftAmt;
728       KnownOne  >>= ShiftAmt;
729         
730       // Handle the sign bits.
731       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
732       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
733         
734       if (KnownZero & SignBit) {       // New bits are known zero.
735         KnownZero |= HighBits;
736       } else if (KnownOne & SignBit) { // New bits are known one.
737         KnownOne |= HighBits;
738       }
739       return;
740     }
741     break;
742   }
743 }
744
745 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
746 /// this predicate to simplify operations downstream.  Mask is known to be zero
747 /// for bits that V cannot have.
748 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
749   uint64_t KnownZero, KnownOne;
750   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
751   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
752   return (KnownZero & Mask) == Mask;
753 }
754
755 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
756 /// specified instruction is a constant integer.  If so, check to see if there
757 /// are any bits set in the constant that are not demanded.  If so, shrink the
758 /// constant and return true.
759 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
760                                    uint64_t Demanded) {
761   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
762   if (!OpC) return false;
763
764   // If there are no bits set that aren't demanded, nothing to do.
765   if ((~Demanded & OpC->getZExtValue()) == 0)
766     return false;
767
768   // This is producing any bits that are not needed, shrink the RHS.
769   uint64_t Val = Demanded & OpC->getZExtValue();
770   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
771   return true;
772 }
773
774 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
775 // set of known zero and one bits, compute the maximum and minimum values that
776 // could have the specified known zero and known one bits, returning them in
777 // min/max.
778 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
779                                                    uint64_t KnownZero,
780                                                    uint64_t KnownOne,
781                                                    int64_t &Min, int64_t &Max) {
782   uint64_t TypeBits = Ty->getIntegralTypeMask();
783   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
784
785   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
786   
787   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
788   // bit if it is unknown.
789   Min = KnownOne;
790   Max = KnownOne|UnknownBits;
791   
792   if (SignBit & UnknownBits) { // Sign bit is unknown
793     Min |= SignBit;
794     Max &= ~SignBit;
795   }
796   
797   // Sign extend the min/max values.
798   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
799   Min = (Min << ShAmt) >> ShAmt;
800   Max = (Max << ShAmt) >> ShAmt;
801 }
802
803 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
804 // a set of known zero and one bits, compute the maximum and minimum values that
805 // could have the specified known zero and known one bits, returning them in
806 // min/max.
807 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
808                                                      uint64_t KnownZero,
809                                                      uint64_t KnownOne,
810                                                      uint64_t &Min,
811                                                      uint64_t &Max) {
812   uint64_t TypeBits = Ty->getIntegralTypeMask();
813   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
814   
815   // The minimum value is when the unknown bits are all zeros.
816   Min = KnownOne;
817   // The maximum value is when the unknown bits are all ones.
818   Max = KnownOne|UnknownBits;
819 }
820
821
822 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
823 /// DemandedMask bits of the result of V are ever used downstream.  If we can
824 /// use this information to simplify V, do so and return true.  Otherwise,
825 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
826 /// the expression (used to simplify the caller).  The KnownZero/One bits may
827 /// only be accurate for those bits in the DemandedMask.
828 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
829                                         uint64_t &KnownZero, uint64_t &KnownOne,
830                                         unsigned Depth) {
831   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
832     // We know all of the bits for a constant!
833     KnownOne = CI->getZExtValue() & DemandedMask;
834     KnownZero = ~KnownOne & DemandedMask;
835     return false;
836   }
837   
838   KnownZero = KnownOne = 0;
839   if (!V->hasOneUse()) {    // Other users may use these bits.
840     if (Depth != 0) {       // Not at the root.
841       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
842       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
843       return false;
844     }
845     // If this is the root being simplified, allow it to have multiple uses,
846     // just set the DemandedMask to all bits.
847     DemandedMask = V->getType()->getIntegralTypeMask();
848   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
849     if (V != UndefValue::get(V->getType()))
850       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
851     return false;
852   } else if (Depth == 6) {        // Limit search depth.
853     return false;
854   }
855   
856   Instruction *I = dyn_cast<Instruction>(V);
857   if (!I) return false;        // Only analyze instructions.
858
859   DemandedMask &= V->getType()->getIntegralTypeMask();
860   
861   uint64_t KnownZero2 = 0, KnownOne2 = 0;
862   switch (I->getOpcode()) {
863   default: break;
864   case Instruction::And:
865     // If either the LHS or the RHS are Zero, the result is zero.
866     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
867                              KnownZero, KnownOne, Depth+1))
868       return true;
869     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
870
871     // If something is known zero on the RHS, the bits aren't demanded on the
872     // LHS.
873     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
874                              KnownZero2, KnownOne2, Depth+1))
875       return true;
876     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
877
878     // If all of the demanded bits are known 1 on one side, return the other.
879     // These bits cannot contribute to the result of the 'and'.
880     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
881       return UpdateValueUsesWith(I, I->getOperand(0));
882     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
883       return UpdateValueUsesWith(I, I->getOperand(1));
884     
885     // If all of the demanded bits in the inputs are known zeros, return zero.
886     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
887       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
888       
889     // If the RHS is a constant, see if we can simplify it.
890     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
891       return UpdateValueUsesWith(I, I);
892       
893     // Output known-1 bits are only known if set in both the LHS & RHS.
894     KnownOne &= KnownOne2;
895     // Output known-0 are known to be clear if zero in either the LHS | RHS.
896     KnownZero |= KnownZero2;
897     break;
898   case Instruction::Or:
899     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
900                              KnownZero, KnownOne, Depth+1))
901       return true;
902     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
903     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
904                              KnownZero2, KnownOne2, Depth+1))
905       return true;
906     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
907     
908     // If all of the demanded bits are known zero on one side, return the other.
909     // These bits cannot contribute to the result of the 'or'.
910     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
911       return UpdateValueUsesWith(I, I->getOperand(0));
912     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
913       return UpdateValueUsesWith(I, I->getOperand(1));
914
915     // If all of the potentially set bits on one side are known to be set on
916     // the other side, just use the 'other' side.
917     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
918         (DemandedMask & (~KnownZero)))
919       return UpdateValueUsesWith(I, I->getOperand(0));
920     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
921         (DemandedMask & (~KnownZero2)))
922       return UpdateValueUsesWith(I, I->getOperand(1));
923         
924     // If the RHS is a constant, see if we can simplify it.
925     if (ShrinkDemandedConstant(I, 1, DemandedMask))
926       return UpdateValueUsesWith(I, I);
927           
928     // Output known-0 bits are only known if clear in both the LHS & RHS.
929     KnownZero &= KnownZero2;
930     // Output known-1 are known to be set if set in either the LHS | RHS.
931     KnownOne |= KnownOne2;
932     break;
933   case Instruction::Xor: {
934     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
935                              KnownZero, KnownOne, Depth+1))
936       return true;
937     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
938     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
939                              KnownZero2, KnownOne2, Depth+1))
940       return true;
941     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
942     
943     // If all of the demanded bits are known zero on one side, return the other.
944     // These bits cannot contribute to the result of the 'xor'.
945     if ((DemandedMask & KnownZero) == DemandedMask)
946       return UpdateValueUsesWith(I, I->getOperand(0));
947     if ((DemandedMask & KnownZero2) == DemandedMask)
948       return UpdateValueUsesWith(I, I->getOperand(1));
949     
950     // Output known-0 bits are known if clear or set in both the LHS & RHS.
951     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
952     // Output known-1 are known to be set if set in only one of the LHS, RHS.
953     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
954     
955     // If all of the demanded bits are known to be zero on one side or the
956     // other, turn this into an *inclusive* or.
957     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
958     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
959       Instruction *Or =
960         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
961                                  I->getName());
962       InsertNewInstBefore(Or, *I);
963       return UpdateValueUsesWith(I, Or);
964     }
965     
966     // If all of the demanded bits on one side are known, and all of the set
967     // bits on that side are also known to be set on the other side, turn this
968     // into an AND, as we know the bits will be cleared.
969     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
970     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
971       if ((KnownOne & KnownOne2) == KnownOne) {
972         Constant *AndC = GetConstantInType(I->getType(), 
973                                            ~KnownOne & DemandedMask);
974         Instruction *And = 
975           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
976         InsertNewInstBefore(And, *I);
977         return UpdateValueUsesWith(I, And);
978       }
979     }
980     
981     // If the RHS is a constant, see if we can simplify it.
982     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
983     if (ShrinkDemandedConstant(I, 1, DemandedMask))
984       return UpdateValueUsesWith(I, I);
985     
986     KnownZero = KnownZeroOut;
987     KnownOne  = KnownOneOut;
988     break;
989   }
990   case Instruction::Select:
991     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
992                              KnownZero, KnownOne, Depth+1))
993       return true;
994     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
995                              KnownZero2, KnownOne2, Depth+1))
996       return true;
997     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
998     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
999     
1000     // If the operands are constants, see if we can simplify them.
1001     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1002       return UpdateValueUsesWith(I, I);
1003     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1004       return UpdateValueUsesWith(I, I);
1005     
1006     // Only known if known in both the LHS and RHS.
1007     KnownOne &= KnownOne2;
1008     KnownZero &= KnownZero2;
1009     break;
1010   case Instruction::Trunc:
1011     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012                              KnownZero, KnownOne, Depth+1))
1013       return true;
1014     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1015     break;
1016   case Instruction::BitCast:
1017     if (!I->getOperand(0)->getType()->isIntegral())
1018       return false;
1019       
1020     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1021                              KnownZero, KnownOne, Depth+1))
1022       return true;
1023     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1024     break;
1025   case Instruction::ZExt: {
1026     // Compute the bits in the result that are not present in the input.
1027     const Type *SrcTy = I->getOperand(0)->getType();
1028     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1030     
1031     DemandedMask &= SrcTy->getIntegralTypeMask();
1032     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1033                              KnownZero, KnownOne, Depth+1))
1034       return true;
1035     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1036     // The top bits are known to be zero.
1037     KnownZero |= NewBits;
1038     break;
1039   }
1040   case Instruction::SExt: {
1041     // Compute the bits in the result that are not present in the input.
1042     const Type *SrcTy = I->getOperand(0)->getType();
1043     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1044     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1045     
1046     // Get the sign bit for the source type
1047     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1048     int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1049
1050     // If any of the sign extended bits are demanded, we know that the sign
1051     // bit is demanded.
1052     if (NewBits & DemandedMask)
1053       InputDemandedBits |= InSignBit;
1054       
1055     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1056                              KnownZero, KnownOne, Depth+1))
1057       return true;
1058     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1059       
1060     // If the sign bit of the input is known set or clear, then we know the
1061     // top bits of the result.
1062
1063     // If the input sign bit is known zero, or if the NewBits are not demanded
1064     // convert this into a zero extension.
1065     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1066       // Convert to ZExt cast
1067       CastInst *NewCast = CastInst::create(
1068         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1069       return UpdateValueUsesWith(I, NewCast);
1070     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1071       KnownOne |= NewBits;
1072       KnownZero &= ~NewBits;
1073     } else {                              // Input sign bit unknown
1074       KnownZero &= ~NewBits;
1075       KnownOne &= ~NewBits;
1076     }
1077     break;
1078   }
1079   case Instruction::Add:
1080     // If there is a constant on the RHS, there are a variety of xformations
1081     // we can do.
1082     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1083       // If null, this should be simplified elsewhere.  Some of the xforms here
1084       // won't work if the RHS is zero.
1085       if (RHS->isNullValue())
1086         break;
1087       
1088       // Figure out what the input bits are.  If the top bits of the and result
1089       // are not demanded, then the add doesn't demand them from its input
1090       // either.
1091       
1092       // Shift the demanded mask up so that it's at the top of the uint64_t.
1093       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1094       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1095       
1096       // If the top bit of the output is demanded, demand everything from the
1097       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1098       uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1099
1100       // Find information about known zero/one bits in the input.
1101       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1102                                KnownZero2, KnownOne2, Depth+1))
1103         return true;
1104
1105       // If the RHS of the add has bits set that can't affect the input, reduce
1106       // the constant.
1107       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1108         return UpdateValueUsesWith(I, I);
1109       
1110       // Avoid excess work.
1111       if (KnownZero2 == 0 && KnownOne2 == 0)
1112         break;
1113       
1114       // Turn it into OR if input bits are zero.
1115       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1116         Instruction *Or =
1117           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1118                                    I->getName());
1119         InsertNewInstBefore(Or, *I);
1120         return UpdateValueUsesWith(I, Or);
1121       }
1122       
1123       // We can say something about the output known-zero and known-one bits,
1124       // depending on potential carries from the input constant and the
1125       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1126       // bits set and the RHS constant is 0x01001, then we know we have a known
1127       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1128       
1129       // To compute this, we first compute the potential carry bits.  These are
1130       // the bits which may be modified.  I'm not aware of a better way to do
1131       // this scan.
1132       uint64_t RHSVal = RHS->getZExtValue();
1133       
1134       bool CarryIn = false;
1135       uint64_t CarryBits = 0;
1136       uint64_t CurBit = 1;
1137       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1138         // Record the current carry in.
1139         if (CarryIn) CarryBits |= CurBit;
1140         
1141         bool CarryOut;
1142         
1143         // This bit has a carry out unless it is "zero + zero" or
1144         // "zero + anything" with no carry in.
1145         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1146           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1147         } else if (!CarryIn &&
1148                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1149           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1150         } else {
1151           // Otherwise, we have to assume we have a carry out.
1152           CarryOut = true;
1153         }
1154         
1155         // This stage's carry out becomes the next stage's carry-in.
1156         CarryIn = CarryOut;
1157       }
1158       
1159       // Now that we know which bits have carries, compute the known-1/0 sets.
1160       
1161       // Bits are known one if they are known zero in one operand and one in the
1162       // other, and there is no input carry.
1163       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1164       
1165       // Bits are known zero if they are known zero in both operands and there
1166       // is no input carry.
1167       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1168     }
1169     break;
1170   case Instruction::Shl:
1171     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172       uint64_t ShiftAmt = SA->getZExtValue();
1173       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1174                                KnownZero, KnownOne, Depth+1))
1175         return true;
1176       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1177       KnownZero <<= ShiftAmt;
1178       KnownOne  <<= ShiftAmt;
1179       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1180     }
1181     break;
1182   case Instruction::LShr:
1183     // For a logical shift right
1184     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185       unsigned ShiftAmt = SA->getZExtValue();
1186       
1187       // Compute the new bits that are at the top now.
1188       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1189       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1190       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1191       // Unsigned shift right.
1192       if (SimplifyDemandedBits(I->getOperand(0),
1193                               (DemandedMask << ShiftAmt) & TypeMask,
1194                                KnownZero, KnownOne, Depth+1))
1195         return true;
1196       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1197       KnownZero &= TypeMask;
1198       KnownOne  &= TypeMask;
1199       KnownZero >>= ShiftAmt;
1200       KnownOne  >>= ShiftAmt;
1201       KnownZero |= HighBits;  // high bits known zero.
1202     }
1203     break;
1204   case Instruction::AShr:
1205     // If this is an arithmetic shift right and only the low-bit is set, we can
1206     // always convert this into a logical shr, even if the shift amount is
1207     // variable.  The low bit of the shift cannot be an input sign bit unless
1208     // the shift amount is >= the size of the datatype, which is undefined.
1209     if (DemandedMask == 1) {
1210       // Perform the logical shift right.
1211       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1212                                     I->getOperand(1), I->getName());
1213       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1214       return UpdateValueUsesWith(I, NewVal);
1215     }    
1216     
1217     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218       unsigned ShiftAmt = SA->getZExtValue();
1219       
1220       // Compute the new bits that are at the top now.
1221       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1222       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1223       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1224       // Signed shift right.
1225       if (SimplifyDemandedBits(I->getOperand(0),
1226                                (DemandedMask << ShiftAmt) & TypeMask,
1227                                KnownZero, KnownOne, Depth+1))
1228         return true;
1229       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1230       KnownZero &= TypeMask;
1231       KnownOne  &= TypeMask;
1232       KnownZero >>= ShiftAmt;
1233       KnownOne  >>= ShiftAmt;
1234         
1235       // Handle the sign bits.
1236       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1237       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1238         
1239       // If the input sign bit is known to be zero, or if none of the top bits
1240       // are demanded, turn this into an unsigned shift right.
1241       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1242         // Perform the logical shift right.
1243         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1244                                       SA, I->getName());
1245         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1246         return UpdateValueUsesWith(I, NewVal);
1247       } else if (KnownOne & SignBit) { // New bits are known one.
1248         KnownOne |= HighBits;
1249       }
1250     }
1251     break;
1252   }
1253   
1254   // If the client is only demanding bits that we know, return the known
1255   // constant.
1256   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1257     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1258   return false;
1259 }  
1260
1261
1262 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1263 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1264 /// actually used by the caller.  This method analyzes which elements of the
1265 /// operand are undef and returns that information in UndefElts.
1266 ///
1267 /// If the information about demanded elements can be used to simplify the
1268 /// operation, the operation is simplified, then the resultant value is
1269 /// returned.  This returns null if no change was made.
1270 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1271                                                 uint64_t &UndefElts,
1272                                                 unsigned Depth) {
1273   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1274   assert(VWidth <= 64 && "Vector too wide to analyze!");
1275   uint64_t EltMask = ~0ULL >> (64-VWidth);
1276   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1277          "Invalid DemandedElts!");
1278
1279   if (isa<UndefValue>(V)) {
1280     // If the entire vector is undefined, just return this info.
1281     UndefElts = EltMask;
1282     return 0;
1283   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1284     UndefElts = EltMask;
1285     return UndefValue::get(V->getType());
1286   }
1287   
1288   UndefElts = 0;
1289   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1290     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1291     Constant *Undef = UndefValue::get(EltTy);
1292
1293     std::vector<Constant*> Elts;
1294     for (unsigned i = 0; i != VWidth; ++i)
1295       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1296         Elts.push_back(Undef);
1297         UndefElts |= (1ULL << i);
1298       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1299         Elts.push_back(Undef);
1300         UndefElts |= (1ULL << i);
1301       } else {                               // Otherwise, defined.
1302         Elts.push_back(CP->getOperand(i));
1303       }
1304         
1305     // If we changed the constant, return it.
1306     Constant *NewCP = ConstantPacked::get(Elts);
1307     return NewCP != CP ? NewCP : 0;
1308   } else if (isa<ConstantAggregateZero>(V)) {
1309     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1310     // set to undef.
1311     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1312     Constant *Zero = Constant::getNullValue(EltTy);
1313     Constant *Undef = UndefValue::get(EltTy);
1314     std::vector<Constant*> Elts;
1315     for (unsigned i = 0; i != VWidth; ++i)
1316       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1317     UndefElts = DemandedElts ^ EltMask;
1318     return ConstantPacked::get(Elts);
1319   }
1320   
1321   if (!V->hasOneUse()) {    // Other users may use these bits.
1322     if (Depth != 0) {       // Not at the root.
1323       // TODO: Just compute the UndefElts information recursively.
1324       return false;
1325     }
1326     return false;
1327   } else if (Depth == 10) {        // Limit search depth.
1328     return false;
1329   }
1330   
1331   Instruction *I = dyn_cast<Instruction>(V);
1332   if (!I) return false;        // Only analyze instructions.
1333   
1334   bool MadeChange = false;
1335   uint64_t UndefElts2;
1336   Value *TmpV;
1337   switch (I->getOpcode()) {
1338   default: break;
1339     
1340   case Instruction::InsertElement: {
1341     // If this is a variable index, we don't know which element it overwrites.
1342     // demand exactly the same input as we produce.
1343     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1344     if (Idx == 0) {
1345       // Note that we can't propagate undef elt info, because we don't know
1346       // which elt is getting updated.
1347       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1348                                         UndefElts2, Depth+1);
1349       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1350       break;
1351     }
1352     
1353     // If this is inserting an element that isn't demanded, remove this
1354     // insertelement.
1355     unsigned IdxNo = Idx->getZExtValue();
1356     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1357       return AddSoonDeadInstToWorklist(*I, 0);
1358     
1359     // Otherwise, the element inserted overwrites whatever was there, so the
1360     // input demanded set is simpler than the output set.
1361     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1362                                       DemandedElts & ~(1ULL << IdxNo),
1363                                       UndefElts, Depth+1);
1364     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1365
1366     // The inserted element is defined.
1367     UndefElts |= 1ULL << IdxNo;
1368     break;
1369   }
1370     
1371   case Instruction::And:
1372   case Instruction::Or:
1373   case Instruction::Xor:
1374   case Instruction::Add:
1375   case Instruction::Sub:
1376   case Instruction::Mul:
1377     // div/rem demand all inputs, because they don't want divide by zero.
1378     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1379                                       UndefElts, Depth+1);
1380     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1381     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1382                                       UndefElts2, Depth+1);
1383     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1384       
1385     // Output elements are undefined if both are undefined.  Consider things
1386     // like undef&0.  The result is known zero, not undef.
1387     UndefElts &= UndefElts2;
1388     break;
1389     
1390   case Instruction::Call: {
1391     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1392     if (!II) break;
1393     switch (II->getIntrinsicID()) {
1394     default: break;
1395       
1396     // Binary vector operations that work column-wise.  A dest element is a
1397     // function of the corresponding input elements from the two inputs.
1398     case Intrinsic::x86_sse_sub_ss:
1399     case Intrinsic::x86_sse_mul_ss:
1400     case Intrinsic::x86_sse_min_ss:
1401     case Intrinsic::x86_sse_max_ss:
1402     case Intrinsic::x86_sse2_sub_sd:
1403     case Intrinsic::x86_sse2_mul_sd:
1404     case Intrinsic::x86_sse2_min_sd:
1405     case Intrinsic::x86_sse2_max_sd:
1406       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1407                                         UndefElts, Depth+1);
1408       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1409       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1410                                         UndefElts2, Depth+1);
1411       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1412
1413       // If only the low elt is demanded and this is a scalarizable intrinsic,
1414       // scalarize it now.
1415       if (DemandedElts == 1) {
1416         switch (II->getIntrinsicID()) {
1417         default: break;
1418         case Intrinsic::x86_sse_sub_ss:
1419         case Intrinsic::x86_sse_mul_ss:
1420         case Intrinsic::x86_sse2_sub_sd:
1421         case Intrinsic::x86_sse2_mul_sd:
1422           // TODO: Lower MIN/MAX/ABS/etc
1423           Value *LHS = II->getOperand(1);
1424           Value *RHS = II->getOperand(2);
1425           // Extract the element as scalars.
1426           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1427           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1428           
1429           switch (II->getIntrinsicID()) {
1430           default: assert(0 && "Case stmts out of sync!");
1431           case Intrinsic::x86_sse_sub_ss:
1432           case Intrinsic::x86_sse2_sub_sd:
1433             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1434                                                         II->getName()), *II);
1435             break;
1436           case Intrinsic::x86_sse_mul_ss:
1437           case Intrinsic::x86_sse2_mul_sd:
1438             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1439                                                          II->getName()), *II);
1440             break;
1441           }
1442           
1443           Instruction *New =
1444             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1445                                   II->getName());
1446           InsertNewInstBefore(New, *II);
1447           AddSoonDeadInstToWorklist(*II, 0);
1448           return New;
1449         }            
1450       }
1451         
1452       // Output elements are undefined if both are undefined.  Consider things
1453       // like undef&0.  The result is known zero, not undef.
1454       UndefElts &= UndefElts2;
1455       break;
1456     }
1457     break;
1458   }
1459   }
1460   return MadeChange ? I : 0;
1461 }
1462
1463 /// @returns true if the specified compare instruction is
1464 /// true when both operands are equal...
1465 /// @brief Determine if the ICmpInst returns true if both operands are equal
1466 static bool isTrueWhenEqual(ICmpInst &ICI) {
1467   ICmpInst::Predicate pred = ICI.getPredicate();
1468   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1469          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1470          pred == ICmpInst::ICMP_SLE;
1471 }
1472
1473 /// @returns true if the specified compare instruction is
1474 /// true when both operands are equal...
1475 /// @brief Determine if the FCmpInst returns true if both operands are equal
1476 static bool isTrueWhenEqual(FCmpInst &FCI) {
1477   FCmpInst::Predicate pred = FCI.getPredicate();
1478   return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1479          pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1480          pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
1481 }
1482
1483 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1484 /// function is designed to check a chain of associative operators for a
1485 /// potential to apply a certain optimization.  Since the optimization may be
1486 /// applicable if the expression was reassociated, this checks the chain, then
1487 /// reassociates the expression as necessary to expose the optimization
1488 /// opportunity.  This makes use of a special Functor, which must define
1489 /// 'shouldApply' and 'apply' methods.
1490 ///
1491 template<typename Functor>
1492 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1493   unsigned Opcode = Root.getOpcode();
1494   Value *LHS = Root.getOperand(0);
1495
1496   // Quick check, see if the immediate LHS matches...
1497   if (F.shouldApply(LHS))
1498     return F.apply(Root);
1499
1500   // Otherwise, if the LHS is not of the same opcode as the root, return.
1501   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1502   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1503     // Should we apply this transform to the RHS?
1504     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1505
1506     // If not to the RHS, check to see if we should apply to the LHS...
1507     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1508       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1509       ShouldApply = true;
1510     }
1511
1512     // If the functor wants to apply the optimization to the RHS of LHSI,
1513     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1514     if (ShouldApply) {
1515       BasicBlock *BB = Root.getParent();
1516
1517       // Now all of the instructions are in the current basic block, go ahead
1518       // and perform the reassociation.
1519       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1520
1521       // First move the selected RHS to the LHS of the root...
1522       Root.setOperand(0, LHSI->getOperand(1));
1523
1524       // Make what used to be the LHS of the root be the user of the root...
1525       Value *ExtraOperand = TmpLHSI->getOperand(1);
1526       if (&Root == TmpLHSI) {
1527         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1528         return 0;
1529       }
1530       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1531       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1532       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1533       BasicBlock::iterator ARI = &Root; ++ARI;
1534       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1535       ARI = Root;
1536
1537       // Now propagate the ExtraOperand down the chain of instructions until we
1538       // get to LHSI.
1539       while (TmpLHSI != LHSI) {
1540         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1541         // Move the instruction to immediately before the chain we are
1542         // constructing to avoid breaking dominance properties.
1543         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1544         BB->getInstList().insert(ARI, NextLHSI);
1545         ARI = NextLHSI;
1546
1547         Value *NextOp = NextLHSI->getOperand(1);
1548         NextLHSI->setOperand(1, ExtraOperand);
1549         TmpLHSI = NextLHSI;
1550         ExtraOperand = NextOp;
1551       }
1552
1553       // Now that the instructions are reassociated, have the functor perform
1554       // the transformation...
1555       return F.apply(Root);
1556     }
1557
1558     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1559   }
1560   return 0;
1561 }
1562
1563
1564 // AddRHS - Implements: X + X --> X << 1
1565 struct AddRHS {
1566   Value *RHS;
1567   AddRHS(Value *rhs) : RHS(rhs) {}
1568   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1569   Instruction *apply(BinaryOperator &Add) const {
1570     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1571                          ConstantInt::get(Type::Int8Ty, 1));
1572   }
1573 };
1574
1575 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1576 //                 iff C1&C2 == 0
1577 struct AddMaskingAnd {
1578   Constant *C2;
1579   AddMaskingAnd(Constant *c) : C2(c) {}
1580   bool shouldApply(Value *LHS) const {
1581     ConstantInt *C1;
1582     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1583            ConstantExpr::getAnd(C1, C2)->isNullValue();
1584   }
1585   Instruction *apply(BinaryOperator &Add) const {
1586     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1587   }
1588 };
1589
1590 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1591                                              InstCombiner *IC) {
1592   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1593     if (Constant *SOC = dyn_cast<Constant>(SO))
1594       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1595
1596     return IC->InsertNewInstBefore(CastInst::create(
1597           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1598   }
1599
1600   // Figure out if the constant is the left or the right argument.
1601   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1602   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1603
1604   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1605     if (ConstIsRHS)
1606       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1607     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1608   }
1609
1610   Value *Op0 = SO, *Op1 = ConstOperand;
1611   if (!ConstIsRHS)
1612     std::swap(Op0, Op1);
1613   Instruction *New;
1614   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1615     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1616   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1617     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1618                           SO->getName()+".cmp");
1619   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1620     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1621   else {
1622     assert(0 && "Unknown binary instruction type!");
1623     abort();
1624   }
1625   return IC->InsertNewInstBefore(New, I);
1626 }
1627
1628 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1629 // constant as the other operand, try to fold the binary operator into the
1630 // select arguments.  This also works for Cast instructions, which obviously do
1631 // not have a second operand.
1632 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1633                                      InstCombiner *IC) {
1634   // Don't modify shared select instructions
1635   if (!SI->hasOneUse()) return 0;
1636   Value *TV = SI->getOperand(1);
1637   Value *FV = SI->getOperand(2);
1638
1639   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1640     // Bool selects with constant operands can be folded to logical ops.
1641     if (SI->getType() == Type::BoolTy) return 0;
1642
1643     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1644     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1645
1646     return new SelectInst(SI->getCondition(), SelectTrueVal,
1647                           SelectFalseVal);
1648   }
1649   return 0;
1650 }
1651
1652
1653 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1654 /// node as operand #0, see if we can fold the instruction into the PHI (which
1655 /// is only possible if all operands to the PHI are constants).
1656 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1657   PHINode *PN = cast<PHINode>(I.getOperand(0));
1658   unsigned NumPHIValues = PN->getNumIncomingValues();
1659   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1660
1661   // Check to see if all of the operands of the PHI are constants.  If there is
1662   // one non-constant value, remember the BB it is.  If there is more than one
1663   // bail out.
1664   BasicBlock *NonConstBB = 0;
1665   for (unsigned i = 0; i != NumPHIValues; ++i)
1666     if (!isa<Constant>(PN->getIncomingValue(i))) {
1667       if (NonConstBB) return 0;  // More than one non-const value.
1668       NonConstBB = PN->getIncomingBlock(i);
1669       
1670       // If the incoming non-constant value is in I's block, we have an infinite
1671       // loop.
1672       if (NonConstBB == I.getParent())
1673         return 0;
1674     }
1675   
1676   // If there is exactly one non-constant value, we can insert a copy of the
1677   // operation in that block.  However, if this is a critical edge, we would be
1678   // inserting the computation one some other paths (e.g. inside a loop).  Only
1679   // do this if the pred block is unconditionally branching into the phi block.
1680   if (NonConstBB) {
1681     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1682     if (!BI || !BI->isUnconditional()) return 0;
1683   }
1684
1685   // Okay, we can do the transformation: create the new PHI node.
1686   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1687   I.setName("");
1688   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1689   InsertNewInstBefore(NewPN, *PN);
1690
1691   // Next, add all of the operands to the PHI.
1692   if (I.getNumOperands() == 2) {
1693     Constant *C = cast<Constant>(I.getOperand(1));
1694     for (unsigned i = 0; i != NumPHIValues; ++i) {
1695       Value *InV;
1696       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1697         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1698           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1699         else
1700           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1701       } else {
1702         assert(PN->getIncomingBlock(i) == NonConstBB);
1703         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1704           InV = BinaryOperator::create(BO->getOpcode(),
1705                                        PN->getIncomingValue(i), C, "phitmp",
1706                                        NonConstBB->getTerminator());
1707         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1708           InV = CmpInst::create(CI->getOpcode(), 
1709                                 CI->getPredicate(),
1710                                 PN->getIncomingValue(i), C, "phitmp",
1711                                 NonConstBB->getTerminator());
1712         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1713           InV = new ShiftInst(SI->getOpcode(),
1714                               PN->getIncomingValue(i), C, "phitmp",
1715                               NonConstBB->getTerminator());
1716         else
1717           assert(0 && "Unknown binop!");
1718         
1719         WorkList.push_back(cast<Instruction>(InV));
1720       }
1721       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1722     }
1723   } else { 
1724     CastInst *CI = cast<CastInst>(&I);
1725     const Type *RetTy = CI->getType();
1726     for (unsigned i = 0; i != NumPHIValues; ++i) {
1727       Value *InV;
1728       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1729         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1730       } else {
1731         assert(PN->getIncomingBlock(i) == NonConstBB);
1732         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1733                                I.getType(), "phitmp", 
1734                                NonConstBB->getTerminator());
1735         WorkList.push_back(cast<Instruction>(InV));
1736       }
1737       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1738     }
1739   }
1740   return ReplaceInstUsesWith(I, NewPN);
1741 }
1742
1743 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1744   bool Changed = SimplifyCommutative(I);
1745   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1746
1747   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1748     // X + undef -> undef
1749     if (isa<UndefValue>(RHS))
1750       return ReplaceInstUsesWith(I, RHS);
1751
1752     // X + 0 --> X
1753     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1754       if (RHSC->isNullValue())
1755         return ReplaceInstUsesWith(I, LHS);
1756     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1757       if (CFP->isExactlyValue(-0.0))
1758         return ReplaceInstUsesWith(I, LHS);
1759     }
1760
1761     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1762       // X + (signbit) --> X ^ signbit
1763       uint64_t Val = CI->getZExtValue();
1764       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1765         return BinaryOperator::createXor(LHS, RHS);
1766       
1767       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1768       // (X & 254)+1 -> (X&254)|1
1769       uint64_t KnownZero, KnownOne;
1770       if (!isa<PackedType>(I.getType()) &&
1771           SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1772                                KnownZero, KnownOne))
1773         return &I;
1774     }
1775
1776     if (isa<PHINode>(LHS))
1777       if (Instruction *NV = FoldOpIntoPhi(I))
1778         return NV;
1779     
1780     ConstantInt *XorRHS = 0;
1781     Value *XorLHS = 0;
1782     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1783       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1784       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1785       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1786       
1787       uint64_t C0080Val = 1ULL << 31;
1788       int64_t CFF80Val = -C0080Val;
1789       unsigned Size = 32;
1790       do {
1791         if (TySizeBits > Size) {
1792           bool Found = false;
1793           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1794           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1795           if (RHSSExt == CFF80Val) {
1796             if (XorRHS->getZExtValue() == C0080Val)
1797               Found = true;
1798           } else if (RHSZExt == C0080Val) {
1799             if (XorRHS->getSExtValue() == CFF80Val)
1800               Found = true;
1801           }
1802           if (Found) {
1803             // This is a sign extend if the top bits are known zero.
1804             uint64_t Mask = ~0ULL;
1805             Mask <<= 64-(TySizeBits-Size);
1806             Mask &= XorLHS->getType()->getIntegralTypeMask();
1807             if (!MaskedValueIsZero(XorLHS, Mask))
1808               Size = 0;  // Not a sign ext, but can't be any others either.
1809             goto FoundSExt;
1810           }
1811         }
1812         Size >>= 1;
1813         C0080Val >>= Size;
1814         CFF80Val >>= Size;
1815       } while (Size >= 8);
1816       
1817 FoundSExt:
1818       const Type *MiddleType = 0;
1819       switch (Size) {
1820       default: break;
1821       case 32: MiddleType = Type::Int32Ty; break;
1822       case 16: MiddleType = Type::Int16Ty; break;
1823       case 8:  MiddleType = Type::Int8Ty; break;
1824       }
1825       if (MiddleType) {
1826         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1827         InsertNewInstBefore(NewTrunc, I);
1828         return new SExtInst(NewTrunc, I.getType());
1829       }
1830     }
1831   }
1832
1833   // X + X --> X << 1
1834   if (I.getType()->isInteger()) {
1835     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1836
1837     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1838       if (RHSI->getOpcode() == Instruction::Sub)
1839         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1840           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1841     }
1842     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1843       if (LHSI->getOpcode() == Instruction::Sub)
1844         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1845           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1846     }
1847   }
1848
1849   // -A + B  -->  B - A
1850   if (Value *V = dyn_castNegVal(LHS))
1851     return BinaryOperator::createSub(RHS, V);
1852
1853   // A + -B  -->  A - B
1854   if (!isa<Constant>(RHS))
1855     if (Value *V = dyn_castNegVal(RHS))
1856       return BinaryOperator::createSub(LHS, V);
1857
1858
1859   ConstantInt *C2;
1860   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1861     if (X == RHS)   // X*C + X --> X * (C+1)
1862       return BinaryOperator::createMul(RHS, AddOne(C2));
1863
1864     // X*C1 + X*C2 --> X * (C1+C2)
1865     ConstantInt *C1;
1866     if (X == dyn_castFoldableMul(RHS, C1))
1867       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1868   }
1869
1870   // X + X*C --> X * (C+1)
1871   if (dyn_castFoldableMul(RHS, C2) == LHS)
1872     return BinaryOperator::createMul(LHS, AddOne(C2));
1873
1874
1875   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1876   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1877     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1878
1879   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1880     Value *X = 0;
1881     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1882       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1883       return BinaryOperator::createSub(C, X);
1884     }
1885
1886     // (X & FF00) + xx00  -> (X+xx00) & FF00
1887     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1888       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1889       if (Anded == CRHS) {
1890         // See if all bits from the first bit set in the Add RHS up are included
1891         // in the mask.  First, get the rightmost bit.
1892         uint64_t AddRHSV = CRHS->getZExtValue();
1893
1894         // Form a mask of all bits from the lowest bit added through the top.
1895         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1896         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1897
1898         // See if the and mask includes all of these bits.
1899         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1900
1901         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1902           // Okay, the xform is safe.  Insert the new add pronto.
1903           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1904                                                             LHS->getName()), I);
1905           return BinaryOperator::createAnd(NewAdd, C2);
1906         }
1907       }
1908     }
1909
1910     // Try to fold constant add into select arguments.
1911     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1912       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1913         return R;
1914   }
1915
1916   // add (cast *A to intptrtype) B -> 
1917   //   cast (GEP (cast *A to sbyte*) B) -> 
1918   //     intptrtype
1919   {
1920     CastInst *CI = dyn_cast<CastInst>(LHS);
1921     Value *Other = RHS;
1922     if (!CI) {
1923       CI = dyn_cast<CastInst>(RHS);
1924       Other = LHS;
1925     }
1926     if (CI && CI->getType()->isSized() && 
1927         (CI->getType()->getPrimitiveSize() == 
1928          TD->getIntPtrType()->getPrimitiveSize()) 
1929         && isa<PointerType>(CI->getOperand(0)->getType())) {
1930       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1931                                    PointerType::get(Type::Int8Ty), I);
1932       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1933       return new PtrToIntInst(I2, CI->getType());
1934     }
1935   }
1936
1937   return Changed ? &I : 0;
1938 }
1939
1940 // isSignBit - Return true if the value represented by the constant only has the
1941 // highest order bit set.
1942 static bool isSignBit(ConstantInt *CI) {
1943   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1944   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1945 }
1946
1947 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1948 ///
1949 static Value *RemoveNoopCast(Value *V) {
1950   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1951     const Type *CTy = CI->getType();
1952     const Type *OpTy = CI->getOperand(0)->getType();
1953     if (CTy->isInteger() && OpTy->isInteger()) {
1954       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1955         return RemoveNoopCast(CI->getOperand(0));
1956     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1957       return RemoveNoopCast(CI->getOperand(0));
1958   }
1959   return V;
1960 }
1961
1962 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1963   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1964
1965   if (Op0 == Op1)         // sub X, X  -> 0
1966     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1967
1968   // If this is a 'B = x-(-A)', change to B = x+A...
1969   if (Value *V = dyn_castNegVal(Op1))
1970     return BinaryOperator::createAdd(Op0, V);
1971
1972   if (isa<UndefValue>(Op0))
1973     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1974   if (isa<UndefValue>(Op1))
1975     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1976
1977   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1978     // Replace (-1 - A) with (~A)...
1979     if (C->isAllOnesValue())
1980       return BinaryOperator::createNot(Op1);
1981
1982     // C - ~X == X + (1+C)
1983     Value *X = 0;
1984     if (match(Op1, m_Not(m_Value(X))))
1985       return BinaryOperator::createAdd(X,
1986                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1987     // -((uint)X >> 31) -> ((int)X >> 31)
1988     // -((int)X >> 31) -> ((uint)X >> 31)
1989     if (C->isNullValue()) {
1990       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1991       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1992         if (SI->getOpcode() == Instruction::LShr) {
1993           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1994             // Check to see if we are shifting out everything but the sign bit.
1995             if (CU->getZExtValue() == 
1996                 SI->getType()->getPrimitiveSizeInBits()-1) {
1997               // Ok, the transformation is safe.  Insert AShr.
1998               // FIXME: Once integer types are signless, this cast should be 
1999               // removed.  
2000               Value *ShiftOp = SI->getOperand(0); 
2001               if (ShiftOp->getType() != I.getType()) 
2002                 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp, 
2003                                            I.getType(), I); 
2004               return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2005                                    SI->getName());
2006             }
2007           }
2008         }
2009         else if (SI->getOpcode() == Instruction::AShr) {
2010           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2011             // Check to see if we are shifting out everything but the sign bit.
2012             if (CU->getZExtValue() == 
2013                 SI->getType()->getPrimitiveSizeInBits()-1) {
2014               
2015               // Ok, the transformation is safe.  Insert LShr. 
2016               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
2017                                    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::Int8Ty, 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::Int8Ty,
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::Int8Ty, 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::Int8Ty, 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::Int8Ty, 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::Int8Ty, 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                 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3326               }
3327               break;                        // (X != 13 & X != 15) -> no change
3328             }
3329             break;
3330           case ICmpInst::ICMP_ULT:
3331             switch (RHSCC) {
3332             default: assert(0 && "Unknown integer condition code!");
3333             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3334             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3335               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3336             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3337               break;
3338             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3339             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3340               return ReplaceInstUsesWith(I, LHS);
3341             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3342               break;
3343             }
3344             break;
3345           case ICmpInst::ICMP_SLT:
3346             switch (RHSCC) {
3347             default: assert(0 && "Unknown integer condition code!");
3348             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3349             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3350               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3351             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3352               break;
3353             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3354             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3355               return ReplaceInstUsesWith(I, LHS);
3356             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3357               break;
3358             }
3359             break;
3360           case ICmpInst::ICMP_UGT:
3361             switch (RHSCC) {
3362             default: assert(0 && "Unknown integer condition code!");
3363             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3364               return ReplaceInstUsesWith(I, LHS);
3365             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3366               return ReplaceInstUsesWith(I, RHS);
3367             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3368               break;
3369             case ICmpInst::ICMP_NE:
3370               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3371                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3372               break;                        // (X u> 13 & X != 15) -> no change
3373             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3374               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3375                                      true, I);
3376             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3377               break;
3378             }
3379             break;
3380           case ICmpInst::ICMP_SGT:
3381             switch (RHSCC) {
3382             default: assert(0 && "Unknown integer condition code!");
3383             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3384               return ReplaceInstUsesWith(I, LHS);
3385             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3386               return ReplaceInstUsesWith(I, RHS);
3387             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3388               break;
3389             case ICmpInst::ICMP_NE:
3390               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3391                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3392               break;                        // (X s> 13 & X != 15) -> no change
3393             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3394               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3395                                      true, I);
3396             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3397               break;
3398             }
3399             break;
3400           }
3401         }
3402   }
3403
3404   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3405   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3406     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3407       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3408         const Type *SrcTy = Op0C->getOperand(0)->getType();
3409         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3410             // Only do this if the casts both really cause code to be generated.
3411             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3412                               I.getType(), TD) &&
3413             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3414                               I.getType(), TD)) {
3415           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3416                                                          Op1C->getOperand(0),
3417                                                          I.getName());
3418           InsertNewInstBefore(NewOp, I);
3419           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3420         }
3421       }
3422     
3423   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3424   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3425     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3426       if (SI0->getOpcode() == SI1->getOpcode() && 
3427           SI0->getOperand(1) == SI1->getOperand(1) &&
3428           (SI0->hasOneUse() || SI1->hasOneUse())) {
3429         Instruction *NewOp =
3430           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3431                                                         SI1->getOperand(0),
3432                                                         SI0->getName()), I);
3433         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3434       }
3435   }
3436
3437   return Changed ? &I : 0;
3438 }
3439
3440 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3441 /// in the result.  If it does, and if the specified byte hasn't been filled in
3442 /// yet, fill it in and return false.
3443 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3444   Instruction *I = dyn_cast<Instruction>(V);
3445   if (I == 0) return true;
3446
3447   // If this is an or instruction, it is an inner node of the bswap.
3448   if (I->getOpcode() == Instruction::Or)
3449     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3450            CollectBSwapParts(I->getOperand(1), ByteValues);
3451   
3452   // If this is a shift by a constant int, and it is "24", then its operand
3453   // defines a byte.  We only handle unsigned types here.
3454   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3455     // Not shifting the entire input by N-1 bytes?
3456     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3457         8*(ByteValues.size()-1))
3458       return true;
3459     
3460     unsigned DestNo;
3461     if (I->getOpcode() == Instruction::Shl) {
3462       // X << 24 defines the top byte with the lowest of the input bytes.
3463       DestNo = ByteValues.size()-1;
3464     } else {
3465       // X >>u 24 defines the low byte with the highest of the input bytes.
3466       DestNo = 0;
3467     }
3468     
3469     // If the destination byte value is already defined, the values are or'd
3470     // together, which isn't a bswap (unless it's an or of the same bits).
3471     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3472       return true;
3473     ByteValues[DestNo] = I->getOperand(0);
3474     return false;
3475   }
3476   
3477   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3478   // don't have this.
3479   Value *Shift = 0, *ShiftLHS = 0;
3480   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3481   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3482       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3483     return true;
3484   Instruction *SI = cast<Instruction>(Shift);
3485
3486   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3487   if (ShiftAmt->getZExtValue() & 7 ||
3488       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3489     return true;
3490   
3491   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3492   unsigned DestByte;
3493   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3494     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3495       break;
3496   // Unknown mask for bswap.
3497   if (DestByte == ByteValues.size()) return true;
3498   
3499   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3500   unsigned SrcByte;
3501   if (SI->getOpcode() == Instruction::Shl)
3502     SrcByte = DestByte - ShiftBytes;
3503   else
3504     SrcByte = DestByte + ShiftBytes;
3505   
3506   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3507   if (SrcByte != ByteValues.size()-DestByte-1)
3508     return true;
3509   
3510   // If the destination byte value is already defined, the values are or'd
3511   // together, which isn't a bswap (unless it's an or of the same bits).
3512   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3513     return true;
3514   ByteValues[DestByte] = SI->getOperand(0);
3515   return false;
3516 }
3517
3518 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3519 /// If so, insert the new bswap intrinsic and return it.
3520 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3521   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3522   if (I.getType() == Type::Int8Ty)
3523     return 0;
3524   
3525   /// ByteValues - For each byte of the result, we keep track of which value
3526   /// defines each byte.
3527   std::vector<Value*> ByteValues;
3528   ByteValues.resize(I.getType()->getPrimitiveSize());
3529     
3530   // Try to find all the pieces corresponding to the bswap.
3531   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3532       CollectBSwapParts(I.getOperand(1), ByteValues))
3533     return 0;
3534   
3535   // Check to see if all of the bytes come from the same value.
3536   Value *V = ByteValues[0];
3537   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3538   
3539   // Check to make sure that all of the bytes come from the same value.
3540   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3541     if (ByteValues[i] != V)
3542       return 0;
3543     
3544   // If they do then *success* we can turn this into a bswap.  Figure out what
3545   // bswap to make it into.
3546   Module *M = I.getParent()->getParent()->getParent();
3547   const char *FnName = 0;
3548   if (I.getType() == Type::Int16Ty)
3549     FnName = "llvm.bswap.i16";
3550   else if (I.getType() == Type::Int32Ty)
3551     FnName = "llvm.bswap.i32";
3552   else if (I.getType() == Type::Int64Ty)
3553     FnName = "llvm.bswap.i64";
3554   else
3555     assert(0 && "Unknown integer type!");
3556   Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3557   
3558   return new CallInst(F, V);
3559 }
3560
3561
3562 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3563   bool Changed = SimplifyCommutative(I);
3564   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3565
3566   if (isa<UndefValue>(Op1))
3567     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3568                                ConstantIntegral::getAllOnesValue(I.getType()));
3569
3570   // or X, X = X
3571   if (Op0 == Op1)
3572     return ReplaceInstUsesWith(I, Op0);
3573
3574   // See if we can simplify any instructions used by the instruction whose sole 
3575   // purpose is to compute bits we don't care about.
3576   uint64_t KnownZero, KnownOne;
3577   if (!isa<PackedType>(I.getType()) &&
3578       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3579                            KnownZero, KnownOne))
3580     return &I;
3581   
3582   // or X, -1 == -1
3583   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3584     ConstantInt *C1 = 0; Value *X = 0;
3585     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3586     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3587       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3588       Op0->setName("");
3589       InsertNewInstBefore(Or, I);
3590       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3591     }
3592
3593     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3594     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3595       std::string Op0Name = Op0->getName(); Op0->setName("");
3596       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3597       InsertNewInstBefore(Or, I);
3598       return BinaryOperator::createXor(Or,
3599                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3600     }
3601
3602     // Try to fold constant and into select arguments.
3603     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3604       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3605         return R;
3606     if (isa<PHINode>(Op0))
3607       if (Instruction *NV = FoldOpIntoPhi(I))
3608         return NV;
3609   }
3610
3611   Value *A = 0, *B = 0;
3612   ConstantInt *C1 = 0, *C2 = 0;
3613
3614   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3615     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3616       return ReplaceInstUsesWith(I, Op1);
3617   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3618     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3619       return ReplaceInstUsesWith(I, Op0);
3620
3621   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3622   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3623   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3624       match(Op1, m_Or(m_Value(), m_Value())) ||
3625       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3626        match(Op1, m_Shift(m_Value(), m_Value())))) {
3627     if (Instruction *BSwap = MatchBSwap(I))
3628       return BSwap;
3629   }
3630   
3631   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3632   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3633       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3634     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3635     Op0->setName("");
3636     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3637   }
3638
3639   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3640   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3641       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3642     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3643     Op0->setName("");
3644     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3645   }
3646
3647   // (A & C1)|(B & C2)
3648   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3649       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3650
3651     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3652       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3653
3654
3655     // If we have: ((V + N) & C1) | (V & C2)
3656     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3657     // replace with V+N.
3658     if (C1 == ConstantExpr::getNot(C2)) {
3659       Value *V1 = 0, *V2 = 0;
3660       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3661           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3662         // Add commutes, try both ways.
3663         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3664           return ReplaceInstUsesWith(I, A);
3665         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3666           return ReplaceInstUsesWith(I, A);
3667       }
3668       // Or commutes, try both ways.
3669       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3670           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3671         // Add commutes, try both ways.
3672         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3673           return ReplaceInstUsesWith(I, B);
3674         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3675           return ReplaceInstUsesWith(I, B);
3676       }
3677     }
3678   }
3679   
3680   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3681   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3682     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3683       if (SI0->getOpcode() == SI1->getOpcode() && 
3684           SI0->getOperand(1) == SI1->getOperand(1) &&
3685           (SI0->hasOneUse() || SI1->hasOneUse())) {
3686         Instruction *NewOp =
3687         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3688                                                      SI1->getOperand(0),
3689                                                      SI0->getName()), I);
3690         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3691       }
3692   }
3693
3694   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3695     if (A == Op1)   // ~A | A == -1
3696       return ReplaceInstUsesWith(I,
3697                                 ConstantIntegral::getAllOnesValue(I.getType()));
3698   } else {
3699     A = 0;
3700   }
3701   // Note, A is still live here!
3702   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3703     if (Op0 == B)
3704       return ReplaceInstUsesWith(I,
3705                                 ConstantIntegral::getAllOnesValue(I.getType()));
3706
3707     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3708     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3709       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3710                                               I.getName()+".demorgan"), I);
3711       return BinaryOperator::createNot(And);
3712     }
3713   }
3714
3715   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3716   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3717     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3718       return R;
3719
3720     Value *LHSVal, *RHSVal;
3721     ConstantInt *LHSCst, *RHSCst;
3722     ICmpInst::Predicate LHSCC, RHSCC;
3723     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3724       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3725         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3726             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3727             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3728             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3729             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3730             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3731           // Ensure that the larger constant is on the RHS.
3732           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3733             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3734           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3735           ICmpInst *LHS = cast<ICmpInst>(Op0);
3736           if (cast<ConstantBool>(Cmp)->getValue()) {
3737             std::swap(LHS, RHS);
3738             std::swap(LHSCst, RHSCst);
3739             std::swap(LHSCC, RHSCC);
3740           }
3741
3742           // At this point, we know we have have two icmp instructions
3743           // comparing a value against two constants and or'ing the result
3744           // together.  Because of the above check, we know that we only have
3745           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3746           // FoldICmpLogical check above), that the two constants are not
3747           // equal.
3748           assert(LHSCst != RHSCst && "Compares not folded above?");
3749
3750           switch (LHSCC) {
3751           default: assert(0 && "Unknown integer condition code!");
3752           case ICmpInst::ICMP_EQ:
3753             switch (RHSCC) {
3754             default: assert(0 && "Unknown integer condition code!");
3755             case ICmpInst::ICMP_EQ:
3756               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3757                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3758                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3759                                                       LHSVal->getName()+".off");
3760                 InsertNewInstBefore(Add, I);
3761                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3762                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3763               }
3764               break;                         // (X == 13 | X == 15) -> no change
3765             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3766             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3767               break;
3768             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3769             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3770             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3771               return ReplaceInstUsesWith(I, RHS);
3772             }
3773             break;
3774           case ICmpInst::ICMP_NE:
3775             switch (RHSCC) {
3776             default: assert(0 && "Unknown integer condition code!");
3777             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3778             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3779             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3780               return ReplaceInstUsesWith(I, LHS);
3781             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3782             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3783             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3784               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3785             }
3786             break;
3787           case ICmpInst::ICMP_ULT:
3788             switch (RHSCC) {
3789             default: assert(0 && "Unknown integer condition code!");
3790             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3791               break;
3792             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3793               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3794                                      false, I);
3795             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3796               break;
3797             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3798             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3799               return ReplaceInstUsesWith(I, RHS);
3800             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3801               break;
3802             }
3803             break;
3804           case ICmpInst::ICMP_SLT:
3805             switch (RHSCC) {
3806             default: assert(0 && "Unknown integer condition code!");
3807             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3808               break;
3809             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3810               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3811                                      false, I);
3812             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3813               break;
3814             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3815             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3816               return ReplaceInstUsesWith(I, RHS);
3817             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3818               break;
3819             }
3820             break;
3821           case ICmpInst::ICMP_UGT:
3822             switch (RHSCC) {
3823             default: assert(0 && "Unknown integer condition code!");
3824             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3825             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3826               return ReplaceInstUsesWith(I, LHS);
3827             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3828               break;
3829             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3830             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3831               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3832             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3833               break;
3834             }
3835             break;
3836           case ICmpInst::ICMP_SGT:
3837             switch (RHSCC) {
3838             default: assert(0 && "Unknown integer condition code!");
3839             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3840             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3841               return ReplaceInstUsesWith(I, LHS);
3842             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3843               break;
3844             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3845             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3846               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3847             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3848               break;
3849             }
3850             break;
3851           }
3852         }
3853   }
3854     
3855   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3856   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3857     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3858       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3859         const Type *SrcTy = Op0C->getOperand(0)->getType();
3860         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3861             // Only do this if the casts both really cause code to be generated.
3862             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3863                               I.getType(), TD) &&
3864             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3865                               I.getType(), TD)) {
3866           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3867                                                         Op1C->getOperand(0),
3868                                                         I.getName());
3869           InsertNewInstBefore(NewOp, I);
3870           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3871         }
3872       }
3873       
3874
3875   return Changed ? &I : 0;
3876 }
3877
3878 // XorSelf - Implements: X ^ X --> 0
3879 struct XorSelf {
3880   Value *RHS;
3881   XorSelf(Value *rhs) : RHS(rhs) {}
3882   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3883   Instruction *apply(BinaryOperator &Xor) const {
3884     return &Xor;
3885   }
3886 };
3887
3888
3889 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3890   bool Changed = SimplifyCommutative(I);
3891   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3892
3893   if (isa<UndefValue>(Op1))
3894     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3895
3896   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3897   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3898     assert(Result == &I && "AssociativeOpt didn't work?");
3899     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3900   }
3901   
3902   // See if we can simplify any instructions used by the instruction whose sole 
3903   // purpose is to compute bits we don't care about.
3904   uint64_t KnownZero, KnownOne;
3905   if (!isa<PackedType>(I.getType()) &&
3906       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3907                            KnownZero, KnownOne))
3908     return &I;
3909
3910   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3911     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3912     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3913       if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3914         return new ICmpInst(ICI->getInversePredicate(),
3915                             ICI->getOperand(0), ICI->getOperand(1));
3916
3917     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3918       // ~(c-X) == X-c-1 == X+(-c-1)
3919       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3920         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3921           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3922           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3923                                               ConstantInt::get(I.getType(), 1));
3924           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3925         }
3926
3927       // ~(~X & Y) --> (X | ~Y)
3928       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3929         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3930         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3931           Instruction *NotY =
3932             BinaryOperator::createNot(Op0I->getOperand(1),
3933                                       Op0I->getOperand(1)->getName()+".not");
3934           InsertNewInstBefore(NotY, I);
3935           return BinaryOperator::createOr(Op0NotVal, NotY);
3936         }
3937       }
3938
3939       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3940         if (Op0I->getOpcode() == Instruction::Add) {
3941           // ~(X-c) --> (-c-1)-X
3942           if (RHS->isAllOnesValue()) {
3943             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3944             return BinaryOperator::createSub(
3945                            ConstantExpr::getSub(NegOp0CI,
3946                                              ConstantInt::get(I.getType(), 1)),
3947                                           Op0I->getOperand(0));
3948           }
3949         } else if (Op0I->getOpcode() == Instruction::Or) {
3950           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3951           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3952             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3953             // Anything in both C1 and C2 is known to be zero, remove it from
3954             // NewRHS.
3955             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3956             NewRHS = ConstantExpr::getAnd(NewRHS, 
3957                                           ConstantExpr::getNot(CommonBits));
3958             WorkList.push_back(Op0I);
3959             I.setOperand(0, Op0I->getOperand(0));
3960             I.setOperand(1, NewRHS);
3961             return &I;
3962           }
3963         }
3964     }
3965
3966     // Try to fold constant and into select arguments.
3967     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3968       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3969         return R;
3970     if (isa<PHINode>(Op0))
3971       if (Instruction *NV = FoldOpIntoPhi(I))
3972         return NV;
3973   }
3974
3975   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3976     if (X == Op1)
3977       return ReplaceInstUsesWith(I,
3978                                 ConstantIntegral::getAllOnesValue(I.getType()));
3979
3980   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3981     if (X == Op0)
3982       return ReplaceInstUsesWith(I,
3983                                 ConstantIntegral::getAllOnesValue(I.getType()));
3984
3985   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3986     if (Op1I->getOpcode() == Instruction::Or) {
3987       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3988         Op1I->swapOperands();
3989         I.swapOperands();
3990         std::swap(Op0, Op1);
3991       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3992         I.swapOperands();     // Simplified below.
3993         std::swap(Op0, Op1);
3994       }
3995     } else if (Op1I->getOpcode() == Instruction::Xor) {
3996       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3997         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3998       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3999         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
4000     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4001       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
4002         Op1I->swapOperands();
4003       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
4004         I.swapOperands();     // Simplified below.
4005         std::swap(Op0, Op1);
4006       }
4007     }
4008
4009   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4010     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4011       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4012         Op0I->swapOperands();
4013       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4014         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4015         InsertNewInstBefore(NotB, I);
4016         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4017       }
4018     } else if (Op0I->getOpcode() == Instruction::Xor) {
4019       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4020         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4021       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4022         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4023     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4024       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4025         Op0I->swapOperands();
4026       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4027           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4028         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4029         InsertNewInstBefore(N, I);
4030         return BinaryOperator::createAnd(N, Op1);
4031       }
4032     }
4033
4034   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4035   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4036     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4037       return R;
4038
4039   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4040   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4041     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4042       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4043         const Type *SrcTy = Op0C->getOperand(0)->getType();
4044         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4045             // Only do this if the casts both really cause code to be generated.
4046             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4047                               I.getType(), TD) &&
4048             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4049                               I.getType(), TD)) {
4050           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4051                                                          Op1C->getOperand(0),
4052                                                          I.getName());
4053           InsertNewInstBefore(NewOp, I);
4054           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4055         }
4056       }
4057
4058   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4059   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4060     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4061       if (SI0->getOpcode() == SI1->getOpcode() && 
4062           SI0->getOperand(1) == SI1->getOperand(1) &&
4063           (SI0->hasOneUse() || SI1->hasOneUse())) {
4064         Instruction *NewOp =
4065         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4066                                                       SI1->getOperand(0),
4067                                                       SI0->getName()), I);
4068         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4069       }
4070   }
4071     
4072   return Changed ? &I : 0;
4073 }
4074
4075 static bool isPositive(ConstantInt *C) {
4076   return C->getSExtValue() >= 0;
4077 }
4078
4079 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4080 /// overflowed for this type.
4081 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4082                             ConstantInt *In2) {
4083   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4084
4085   return cast<ConstantInt>(Result)->getZExtValue() <
4086          cast<ConstantInt>(In1)->getZExtValue();
4087 }
4088
4089 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4090 /// code necessary to compute the offset from the base pointer (without adding
4091 /// in the base pointer).  Return the result as a signed integer of intptr size.
4092 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4093   TargetData &TD = IC.getTargetData();
4094   gep_type_iterator GTI = gep_type_begin(GEP);
4095   const Type *IntPtrTy = TD.getIntPtrType();
4096   Value *Result = Constant::getNullValue(IntPtrTy);
4097
4098   // Build a mask for high order bits.
4099   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4100
4101   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4102     Value *Op = GEP->getOperand(i);
4103     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4104     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4105     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4106       if (!OpC->isNullValue()) {
4107         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4108         Scale = ConstantExpr::getMul(OpC, Scale);
4109         if (Constant *RC = dyn_cast<Constant>(Result))
4110           Result = ConstantExpr::getAdd(RC, Scale);
4111         else {
4112           // Emit an add instruction.
4113           Result = IC.InsertNewInstBefore(
4114              BinaryOperator::createAdd(Result, Scale,
4115                                        GEP->getName()+".offs"), I);
4116         }
4117       }
4118     } else {
4119       // Convert to correct type.
4120       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4121                                                Op->getName()+".c"), I);
4122       if (Size != 1)
4123         // We'll let instcombine(mul) convert this to a shl if possible.
4124         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4125                                                     GEP->getName()+".idx"), I);
4126
4127       // Emit an add instruction.
4128       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4129                                                     GEP->getName()+".offs"), I);
4130     }
4131   }
4132   return Result;
4133 }
4134
4135 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4136 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4137 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4138                                        ICmpInst::Predicate Cond,
4139                                        Instruction &I) {
4140   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4141
4142   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4143     if (isa<PointerType>(CI->getOperand(0)->getType()))
4144       RHS = CI->getOperand(0);
4145
4146   Value *PtrBase = GEPLHS->getOperand(0);
4147   if (PtrBase == RHS) {
4148     // As an optimization, we don't actually have to compute the actual value of
4149     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4150     // each index is zero or not.
4151     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4152       Instruction *InVal = 0;
4153       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4154       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4155         bool EmitIt = true;
4156         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4157           if (isa<UndefValue>(C))  // undef index -> undef.
4158             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4159           if (C->isNullValue())
4160             EmitIt = false;
4161           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4162             EmitIt = false;  // This is indexing into a zero sized array?
4163           } else if (isa<ConstantInt>(C))
4164             return ReplaceInstUsesWith(I, // No comparison is needed here.
4165                                  ConstantBool::get(Cond == ICmpInst::ICMP_NE));
4166         }
4167
4168         if (EmitIt) {
4169           Instruction *Comp =
4170             new ICmpInst(Cond, GEPLHS->getOperand(i),
4171                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4172           if (InVal == 0)
4173             InVal = Comp;
4174           else {
4175             InVal = InsertNewInstBefore(InVal, I);
4176             InsertNewInstBefore(Comp, I);
4177             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4178               InVal = BinaryOperator::createOr(InVal, Comp);
4179             else                              // True if all are equal
4180               InVal = BinaryOperator::createAnd(InVal, Comp);
4181           }
4182         }
4183       }
4184
4185       if (InVal)
4186         return InVal;
4187       else
4188         // No comparison is needed here, all indexes = 0
4189         ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4190     }
4191
4192     // Only lower this if the icmp is the only user of the GEP or if we expect
4193     // the result to fold to a constant!
4194     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4195       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4196       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4197       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4198                           Constant::getNullValue(Offset->getType()));
4199     }
4200   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4201     // If the base pointers are different, but the indices are the same, just
4202     // compare the base pointer.
4203     if (PtrBase != GEPRHS->getOperand(0)) {
4204       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4205       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4206                         GEPRHS->getOperand(0)->getType();
4207       if (IndicesTheSame)
4208         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4209           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4210             IndicesTheSame = false;
4211             break;
4212           }
4213
4214       // If all indices are the same, just compare the base pointers.
4215       if (IndicesTheSame)
4216         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4217                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4218
4219       // Otherwise, the base pointers are different and the indices are
4220       // different, bail out.
4221       return 0;
4222     }
4223
4224     // If one of the GEPs has all zero indices, recurse.
4225     bool AllZeros = true;
4226     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4227       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4228           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4229         AllZeros = false;
4230         break;
4231       }
4232     if (AllZeros)
4233       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4234                           ICmpInst::getSwappedPredicate(Cond), I);
4235
4236     // If the other GEP has all zero indices, recurse.
4237     AllZeros = true;
4238     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4239       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4240           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4241         AllZeros = false;
4242         break;
4243       }
4244     if (AllZeros)
4245       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4246
4247     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4248       // If the GEPs only differ by one index, compare it.
4249       unsigned NumDifferences = 0;  // Keep track of # differences.
4250       unsigned DiffOperand = 0;     // The operand that differs.
4251       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4252         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4253           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4254                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4255             // Irreconcilable differences.
4256             NumDifferences = 2;
4257             break;
4258           } else {
4259             if (NumDifferences++) break;
4260             DiffOperand = i;
4261           }
4262         }
4263
4264       if (NumDifferences == 0)   // SAME GEP?
4265         return ReplaceInstUsesWith(I, // No comparison is needed here.
4266                                  ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4267       else if (NumDifferences == 1) {
4268         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4269         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4270         if (LHSV->getType() != RHSV->getType())
4271           // Doesn't matter which one we bitconvert here.
4272           LHSV = InsertCastBefore(Instruction::BitCast, LHSV, RHSV->getType(),
4273                                   I);
4274         // Make sure we do a signed comparison here.
4275         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4276       }
4277     }
4278
4279     // Only lower this if the icmp is the only user of the GEP or if we expect
4280     // the result to fold to a constant!
4281     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4282         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4283       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4284       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4285       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4286       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4287     }
4288   }
4289   return 0;
4290 }
4291
4292 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4293   bool Changed = SimplifyCompare(I);
4294   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4295
4296   // fcmp pred X, X
4297   if (Op0 == Op1)
4298     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4299
4300   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4301     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4302
4303   // Handle fcmp with constant RHS
4304   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4305     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4306       switch (LHSI->getOpcode()) {
4307       case Instruction::PHI:
4308         if (Instruction *NV = FoldOpIntoPhi(I))
4309           return NV;
4310         break;
4311       case Instruction::Select:
4312         // If either operand of the select is a constant, we can fold the
4313         // comparison into the select arms, which will cause one to be
4314         // constant folded and the select turned into a bitwise or.
4315         Value *Op1 = 0, *Op2 = 0;
4316         if (LHSI->hasOneUse()) {
4317           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4318             // Fold the known value into the constant operand.
4319             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4320             // Insert a new FCmp of the other select operand.
4321             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4322                                                       LHSI->getOperand(2), RHSC,
4323                                                       I.getName()), I);
4324           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4325             // Fold the known value into the constant operand.
4326             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4327             // Insert a new FCmp of the other select operand.
4328             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4329                                                       LHSI->getOperand(1), RHSC,
4330                                                       I.getName()), I);
4331           }
4332         }
4333
4334         if (Op1)
4335           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4336         break;
4337       }
4338   }
4339
4340   return Changed ? &I : 0;
4341 }
4342
4343 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4344   bool Changed = SimplifyCompare(I);
4345   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4346   const Type *Ty = Op0->getType();
4347
4348   // icmp X, X
4349   if (Op0 == Op1)
4350     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4351
4352   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4353     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4354
4355   // icmp of GlobalValues can never equal each other as long as they aren't
4356   // external weak linkage type.
4357   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4358     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4359       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4360         return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4361
4362   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4363   // addresses never equal each other!  We already know that Op0 != Op1.
4364   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4365        isa<ConstantPointerNull>(Op0)) &&
4366       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4367        isa<ConstantPointerNull>(Op1)))
4368     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4369
4370   // icmp's with boolean values can always be turned into bitwise operations
4371   if (Ty == Type::BoolTy) {
4372     switch (I.getPredicate()) {
4373     default: assert(0 && "Invalid icmp instruction!");
4374     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4375       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4376       InsertNewInstBefore(Xor, I);
4377       return BinaryOperator::createNot(Xor);
4378     }
4379     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4380       return BinaryOperator::createXor(Op0, Op1);
4381
4382     case ICmpInst::ICMP_UGT:
4383     case ICmpInst::ICMP_SGT:
4384       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4385       // FALL THROUGH
4386     case ICmpInst::ICMP_ULT:
4387     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4388       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4389       InsertNewInstBefore(Not, I);
4390       return BinaryOperator::createAnd(Not, Op1);
4391     }
4392     case ICmpInst::ICMP_UGE:
4393     case ICmpInst::ICMP_SGE:
4394       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4395       // FALL THROUGH
4396     case ICmpInst::ICMP_ULE:
4397     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4398       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4399       InsertNewInstBefore(Not, I);
4400       return BinaryOperator::createOr(Not, Op1);
4401     }
4402     }
4403   }
4404
4405   // See if we are doing a comparison between a constant and an instruction that
4406   // can be folded into the comparison.
4407   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4408     switch (I.getPredicate()) {
4409     default: break;
4410     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4411       if (CI->isMinValue(false))
4412         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4413       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4414         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4415       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4416         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4417       break;
4418
4419     case ICmpInst::ICMP_SLT:
4420       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4421         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4422       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4423         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4424       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4425         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4426       break;
4427
4428     case ICmpInst::ICMP_UGT:
4429       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4430         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4431       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4432         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4433       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4434         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4435       break;
4436
4437     case ICmpInst::ICMP_SGT:
4438       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4439         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4440       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4441         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4442       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4443         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4444       break;
4445
4446     case ICmpInst::ICMP_ULE:
4447       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4448         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4449       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4450         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4451       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4452         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4453       break;
4454
4455     case ICmpInst::ICMP_SLE:
4456       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4457         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4458       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4459         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4460       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4461         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4462       break;
4463
4464     case ICmpInst::ICMP_UGE:
4465       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4466         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4467       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4468         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4469       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4470         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4471       break;
4472
4473     case ICmpInst::ICMP_SGE:
4474       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4475         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4476       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4477         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4478       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4479         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4480       break;
4481     }
4482
4483     // If we still have a icmp le or icmp ge instruction, turn it into the
4484     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4485     // already been handled above, this requires little checking.
4486     //
4487     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4488       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4489     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4490       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4491     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4492       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4493     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4494       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4495     
4496     // See if we can fold the comparison based on bits known to be zero or one
4497     // in the input.
4498     uint64_t KnownZero, KnownOne;
4499     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4500                              KnownZero, KnownOne, 0))
4501       return &I;
4502         
4503     // Given the known and unknown bits, compute a range that the LHS could be
4504     // in.
4505     if (KnownOne | KnownZero) {
4506       // Compute the Min, Max and RHS values based on the known bits. For the
4507       // EQ and NE we use unsigned values.
4508       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4509       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4510       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4511         SRHSVal = CI->getSExtValue();
4512         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4513                                                SMax);
4514       } else {
4515         URHSVal = CI->getZExtValue();
4516         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4517                                                  UMax);
4518       }
4519       switch (I.getPredicate()) {  // LE/GE have been folded already.
4520       default: assert(0 && "Unknown icmp opcode!");
4521       case ICmpInst::ICMP_EQ:
4522         if (UMax < URHSVal || UMin > URHSVal)
4523           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4524         break;
4525       case ICmpInst::ICMP_NE:
4526         if (UMax < URHSVal || UMin > URHSVal)
4527           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4528         break;
4529       case ICmpInst::ICMP_ULT:
4530         if (UMax < URHSVal)
4531           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4532         if (UMin > URHSVal)
4533           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4534         break;
4535       case ICmpInst::ICMP_UGT:
4536         if (UMin > URHSVal)
4537           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4538         if (UMax < URHSVal)
4539           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4540         break;
4541       case ICmpInst::ICMP_SLT:
4542         if (SMax < SRHSVal)
4543           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4544         if (SMin > SRHSVal)
4545           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4546         break;
4547       case ICmpInst::ICMP_SGT: 
4548         if (SMin > SRHSVal)
4549           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4550         if (SMax < SRHSVal)
4551           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4552         break;
4553       }
4554     }
4555           
4556     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4557     // instruction, see if that instruction also has constants so that the 
4558     // instruction can be folded into the icmp 
4559     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4560       switch (LHSI->getOpcode()) {
4561       case Instruction::And:
4562         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4563             LHSI->getOperand(0)->hasOneUse()) {
4564           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4565
4566           // If the LHS is an AND of a truncating cast, we can widen the
4567           // and/compare to be the input width without changing the value
4568           // produced, eliminating a cast.
4569           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4570             // We can do this transformation if either the AND constant does not
4571             // have its sign bit set or if it is an equality comparison. 
4572             // Extending a relational comparison when we're checking the sign
4573             // bit would not work.
4574             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4575                 (I.isEquality() ||
4576                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4577                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4578               ConstantInt *NewCST;
4579               ConstantInt *NewCI;
4580               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4581                                          AndCST->getZExtValue());
4582               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4583                                         CI->getZExtValue());
4584               Instruction *NewAnd = 
4585                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4586                                           LHSI->getName());
4587               InsertNewInstBefore(NewAnd, I);
4588               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4589             }
4590           }
4591           
4592           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4593           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4594           // happens a LOT in code produced by the C front-end, for bitfield
4595           // access.
4596           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4597
4598           // Check to see if there is a noop-cast between the shift and the and.
4599           if (!Shift) {
4600             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4601               if (CI->getOpcode() == Instruction::BitCast)
4602                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4603           }
4604
4605           ConstantInt *ShAmt;
4606           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4607           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4608           const Type *AndTy = AndCST->getType();          // Type of the and.
4609
4610           // We can fold this as long as we can't shift unknown bits
4611           // into the mask.  This can only happen with signed shift
4612           // rights, as they sign-extend.
4613           if (ShAmt) {
4614             bool CanFold = Shift->isLogicalShift();
4615             if (!CanFold) {
4616               // To test for the bad case of the signed shr, see if any
4617               // of the bits shifted in could be tested after the mask.
4618               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4619               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4620
4621               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4622               Constant *ShVal =
4623                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4624                                      OShAmt);
4625               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4626                 CanFold = true;
4627             }
4628
4629             if (CanFold) {
4630               Constant *NewCst;
4631               if (Shift->getOpcode() == Instruction::Shl)
4632                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4633               else
4634                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4635
4636               // Check to see if we are shifting out any of the bits being
4637               // compared.
4638               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4639                 // If we shifted bits out, the fold is not going to work out.
4640                 // As a special case, check to see if this means that the
4641                 // result is always true or false now.
4642                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4643                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4644                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4645                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4646               } else {
4647                 I.setOperand(1, NewCst);
4648                 Constant *NewAndCST;
4649                 if (Shift->getOpcode() == Instruction::Shl)
4650                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4651                 else
4652                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4653                 LHSI->setOperand(1, NewAndCST);
4654                 if (AndTy == Ty) 
4655                   LHSI->setOperand(0, Shift->getOperand(0));
4656                 else {
4657                   Value *NewCast = InsertCastBefore(Instruction::BitCast,
4658                                                     Shift->getOperand(0), AndTy,
4659                                                     *Shift);
4660                   LHSI->setOperand(0, NewCast);
4661                 }
4662                 WorkList.push_back(Shift); // Shift is dead.
4663                 AddUsesToWorkList(I);
4664                 return &I;
4665               }
4666             }
4667           }
4668           
4669           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4670           // preferable because it allows the C<<Y expression to be hoisted out
4671           // of a loop if Y is invariant and X is not.
4672           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4673               I.isEquality() && !Shift->isArithmeticShift() &&
4674               isa<Instruction>(Shift->getOperand(0))) {
4675             // Compute C << Y.
4676             Value *NS;
4677             if (Shift->getOpcode() == Instruction::LShr) {
4678               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4679                                  "tmp");
4680             } else {
4681               // Insert a logical shift.
4682               NS = new ShiftInst(Instruction::LShr, AndCST,
4683                                  Shift->getOperand(1), "tmp");
4684             }
4685             InsertNewInstBefore(cast<Instruction>(NS), I);
4686
4687             // If C's sign doesn't agree with the and, insert a cast now.
4688             if (NS->getType() != LHSI->getType())
4689               NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4690                                     I);
4691
4692             Value *ShiftOp = Shift->getOperand(0);
4693             if (ShiftOp->getType() != LHSI->getType())
4694               ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp, 
4695                                          LHSI->getType(), I);
4696               
4697             // Compute X & (C << Y).
4698             Instruction *NewAnd =
4699               BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4700             InsertNewInstBefore(NewAnd, I);
4701             
4702             I.setOperand(0, NewAnd);
4703             return &I;
4704           }
4705         }
4706         break;
4707
4708       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4709         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4710           if (I.isEquality()) {
4711             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4712
4713             // Check that the shift amount is in range.  If not, don't perform
4714             // undefined shifts.  When the shift is visited it will be
4715             // simplified.
4716             if (ShAmt->getZExtValue() >= TypeBits)
4717               break;
4718
4719             // If we are comparing against bits always shifted out, the
4720             // comparison cannot succeed.
4721             Constant *Comp =
4722               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4723             if (Comp != CI) {// Comparing against a bit that we know is zero.
4724               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4725               Constant *Cst = ConstantBool::get(IsICMP_NE);
4726               return ReplaceInstUsesWith(I, Cst);
4727             }
4728
4729             if (LHSI->hasOneUse()) {
4730               // Otherwise strength reduce the shift into an and.
4731               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4732               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4733               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4734
4735               Instruction *AndI =
4736                 BinaryOperator::createAnd(LHSI->getOperand(0),
4737                                           Mask, LHSI->getName()+".mask");
4738               Value *And = InsertNewInstBefore(AndI, I);
4739               return new ICmpInst(I.getPredicate(), And,
4740                                      ConstantExpr::getLShr(CI, ShAmt));
4741             }
4742           }
4743         }
4744         break;
4745
4746       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4747       case Instruction::AShr:
4748         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4749           if (I.isEquality()) {
4750             // Check that the shift amount is in range.  If not, don't perform
4751             // undefined shifts.  When the shift is visited it will be
4752             // simplified.
4753             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4754             if (ShAmt->getZExtValue() >= TypeBits)
4755               break;
4756
4757             // If we are comparing against bits always shifted out, the
4758             // comparison cannot succeed.
4759             Constant *Comp;
4760             if (LHSI->getOpcode() == Instruction::LShr) 
4761               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4762                                            ShAmt);
4763             else
4764               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4765                                            ShAmt);
4766
4767             if (Comp != CI) {// Comparing against a bit that we know is zero.
4768               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4769               Constant *Cst = ConstantBool::get(IsICMP_NE);
4770               return ReplaceInstUsesWith(I, Cst);
4771             }
4772
4773             if (LHSI->hasOneUse() || CI->isNullValue()) {
4774               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4775
4776               // Otherwise strength reduce the shift into an and.
4777               uint64_t Val = ~0ULL;          // All ones.
4778               Val <<= ShAmtVal;              // Shift over to the right spot.
4779               Val &= ~0ULL >> (64-TypeBits);
4780               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4781
4782               Instruction *AndI =
4783                 BinaryOperator::createAnd(LHSI->getOperand(0),
4784                                           Mask, LHSI->getName()+".mask");
4785               Value *And = InsertNewInstBefore(AndI, I);
4786               return new ICmpInst(I.getPredicate(), And,
4787                                      ConstantExpr::getShl(CI, ShAmt));
4788             }
4789           }
4790         }
4791         break;
4792
4793       case Instruction::SDiv:
4794       case Instruction::UDiv:
4795         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4796         // Fold this div into the comparison, producing a range check. 
4797         // Determine, based on the divide type, what the range is being 
4798         // checked.  If there is an overflow on the low or high side, remember 
4799         // it, otherwise compute the range [low, hi) bounding the new value.
4800         // See: InsertRangeTest above for the kinds of replacements possible.
4801         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4802           // FIXME: If the operand types don't match the type of the divide 
4803           // then don't attempt this transform. The code below doesn't have the
4804           // logic to deal with a signed divide and an unsigned compare (and
4805           // vice versa). This is because (x /s C1) <s C2  produces different 
4806           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4807           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4808           // work. :(  The if statement below tests that condition and bails 
4809           // if it finds it. 
4810           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4811           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4812             break;
4813
4814           // Initialize the variables that will indicate the nature of the
4815           // range check.
4816           bool LoOverflow = false, HiOverflow = false;
4817           ConstantInt *LoBound = 0, *HiBound = 0;
4818
4819           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4820           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4821           // C2 (CI). By solving for X we can turn this into a range check 
4822           // instead of computing a divide. 
4823           ConstantInt *Prod = 
4824             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4825
4826           // Determine if the product overflows by seeing if the product is
4827           // not equal to the divide. Make sure we do the same kind of divide
4828           // as in the LHS instruction that we're folding. 
4829           bool ProdOV = !DivRHS->isNullValue() && 
4830             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4831               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4832
4833           // Get the ICmp opcode
4834           ICmpInst::Predicate predicate = I.getPredicate();
4835
4836           if (DivRHS->isNullValue()) {  
4837             // Don't hack on divide by zeros!
4838           } else if (!DivIsSigned) {  // udiv
4839             LoBound = Prod;
4840             LoOverflow = ProdOV;
4841             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4842           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4843             if (CI->isNullValue()) {       // (X / pos) op 0
4844               // Can't overflow.
4845               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4846               HiBound = DivRHS;
4847             } else if (isPositive(CI)) {   // (X / pos) op pos
4848               LoBound = Prod;
4849               LoOverflow = ProdOV;
4850               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4851             } else {                       // (X / pos) op neg
4852               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4853               LoOverflow = AddWithOverflow(LoBound, Prod,
4854                                            cast<ConstantInt>(DivRHSH));
4855               HiBound = Prod;
4856               HiOverflow = ProdOV;
4857             }
4858           } else {                         // Divisor is < 0.
4859             if (CI->isNullValue()) {       // (X / neg) op 0
4860               LoBound = AddOne(DivRHS);
4861               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4862               if (HiBound == DivRHS)
4863                 LoBound = 0;               // - INTMIN = INTMIN
4864             } else if (isPositive(CI)) {   // (X / neg) op pos
4865               HiOverflow = LoOverflow = ProdOV;
4866               if (!LoOverflow)
4867                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4868               HiBound = AddOne(Prod);
4869             } else {                       // (X / neg) op neg
4870               LoBound = Prod;
4871               LoOverflow = HiOverflow = ProdOV;
4872               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4873             }
4874
4875             // Dividing by a negate swaps the condition.
4876             predicate = ICmpInst::getSwappedPredicate(predicate);
4877           }
4878
4879           if (LoBound) {
4880             Value *X = LHSI->getOperand(0);
4881             switch (predicate) {
4882             default: assert(0 && "Unhandled icmp opcode!");
4883             case ICmpInst::ICMP_EQ:
4884               if (LoOverflow && HiOverflow)
4885                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4886               else if (HiOverflow)
4887                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4888                                     ICmpInst::ICMP_UGE, X, LoBound);
4889               else if (LoOverflow)
4890                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4891                                     ICmpInst::ICMP_ULT, X, HiBound);
4892               else
4893                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4894                                        true, I);
4895             case ICmpInst::ICMP_NE:
4896               if (LoOverflow && HiOverflow)
4897                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4898               else if (HiOverflow)
4899                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4900                                     ICmpInst::ICMP_ULT, X, LoBound);
4901               else if (LoOverflow)
4902                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4903                                     ICmpInst::ICMP_UGE, X, HiBound);
4904               else
4905                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4906                                        false, I);
4907             case ICmpInst::ICMP_ULT:
4908             case ICmpInst::ICMP_SLT:
4909               if (LoOverflow)
4910                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4911               return new ICmpInst(predicate, X, LoBound);
4912             case ICmpInst::ICMP_UGT:
4913             case ICmpInst::ICMP_SGT:
4914               if (HiOverflow)
4915                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4916               if (predicate == ICmpInst::ICMP_UGT)
4917                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4918               else
4919                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4920             }
4921           }
4922         }
4923         break;
4924       }
4925
4926     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4927     if (I.isEquality()) {
4928       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4929
4930       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4931       // the second operand is a constant, simplify a bit.
4932       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4933         switch (BO->getOpcode()) {
4934         case Instruction::SRem:
4935           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4936           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4937               BO->hasOneUse()) {
4938             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4939             if (V > 1 && isPowerOf2_64(V)) {
4940               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4941                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4942               return new ICmpInst(I.getPredicate(), NewRem, 
4943                                   Constant::getNullValue(BO->getType()));
4944             }
4945           }
4946           break;
4947         case Instruction::Add:
4948           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4949           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4950             if (BO->hasOneUse())
4951               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4952                                   ConstantExpr::getSub(CI, BOp1C));
4953           } else if (CI->isNullValue()) {
4954             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4955             // efficiently invertible, or if the add has just this one use.
4956             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4957
4958             if (Value *NegVal = dyn_castNegVal(BOp1))
4959               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4960             else if (Value *NegVal = dyn_castNegVal(BOp0))
4961               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4962             else if (BO->hasOneUse()) {
4963               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4964               BO->setName("");
4965               InsertNewInstBefore(Neg, I);
4966               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4967             }
4968           }
4969           break;
4970         case Instruction::Xor:
4971           // For the xor case, we can xor two constants together, eliminating
4972           // the explicit xor.
4973           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4974             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4975                                 ConstantExpr::getXor(CI, BOC));
4976
4977           // FALLTHROUGH
4978         case Instruction::Sub:
4979           // Replace (([sub|xor] A, B) != 0) with (A != B)
4980           if (CI->isNullValue())
4981             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4982                                 BO->getOperand(1));
4983           break;
4984
4985         case Instruction::Or:
4986           // If bits are being or'd in that are not present in the constant we
4987           // are comparing against, then the comparison could never succeed!
4988           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4989             Constant *NotCI = ConstantExpr::getNot(CI);
4990             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4991               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
4992           }
4993           break;
4994
4995         case Instruction::And:
4996           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4997             // If bits are being compared against that are and'd out, then the
4998             // comparison can never succeed!
4999             if (!ConstantExpr::getAnd(CI,
5000                                       ConstantExpr::getNot(BOC))->isNullValue())
5001               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
5002
5003             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5004             if (CI == BOC && isOneBitSet(CI))
5005               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5006                                   ICmpInst::ICMP_NE, Op0,
5007                                   Constant::getNullValue(CI->getType()));
5008
5009             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5010             if (isSignBit(BOC)) {
5011               Value *X = BO->getOperand(0);
5012               Constant *Zero = Constant::getNullValue(X->getType());
5013               ICmpInst::Predicate pred = isICMP_NE ? 
5014                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5015               return new ICmpInst(pred, X, Zero);
5016             }
5017
5018             // ((X & ~7) == 0) --> X < 8
5019             if (CI->isNullValue() && isHighOnes(BOC)) {
5020               Value *X = BO->getOperand(0);
5021               Constant *NegX = ConstantExpr::getNeg(BOC);
5022               ICmpInst::Predicate pred = isICMP_NE ? 
5023                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5024               return new ICmpInst(pred, X, NegX);
5025             }
5026
5027           }
5028         default: break;
5029         }
5030       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5031         // Handle set{eq|ne} <intrinsic>, intcst.
5032         switch (II->getIntrinsicID()) {
5033         default: break;
5034         case Intrinsic::bswap_i16: 
5035           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5036           WorkList.push_back(II);  // Dead?
5037           I.setOperand(0, II->getOperand(1));
5038           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5039                                            ByteSwap_16(CI->getZExtValue())));
5040           return &I;
5041         case Intrinsic::bswap_i32:   
5042           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5043           WorkList.push_back(II);  // Dead?
5044           I.setOperand(0, II->getOperand(1));
5045           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5046                                            ByteSwap_32(CI->getZExtValue())));
5047           return &I;
5048         case Intrinsic::bswap_i64:   
5049           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5050           WorkList.push_back(II);  // Dead?
5051           I.setOperand(0, II->getOperand(1));
5052           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5053                                            ByteSwap_64(CI->getZExtValue())));
5054           return &I;
5055         }
5056       }
5057     } else {  // Not a ICMP_EQ/ICMP_NE
5058       // If the LHS is a cast from an integral value of the same size, then 
5059       // since we know the RHS is a constant, try to simlify.
5060       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5061         Value *CastOp = Cast->getOperand(0);
5062         const Type *SrcTy = CastOp->getType();
5063         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5064         if (SrcTy->isInteger() && 
5065             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5066           // If this is an unsigned comparison, try to make the comparison use
5067           // smaller constant values.
5068           switch (I.getPredicate()) {
5069             default: break;
5070             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5071               ConstantInt *CUI = cast<ConstantInt>(CI);
5072               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5073                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5074                                     ConstantInt::get(SrcTy, -1));
5075               break;
5076             }
5077             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5078               ConstantInt *CUI = cast<ConstantInt>(CI);
5079               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5080                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5081                                     Constant::getNullValue(SrcTy));
5082               break;
5083             }
5084           }
5085
5086         }
5087       }
5088     }
5089   }
5090
5091   // Handle icmp with constant RHS
5092   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5093     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5094       switch (LHSI->getOpcode()) {
5095       case Instruction::GetElementPtr:
5096         if (RHSC->isNullValue()) {
5097           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5098           bool isAllZeros = true;
5099           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5100             if (!isa<Constant>(LHSI->getOperand(i)) ||
5101                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5102               isAllZeros = false;
5103               break;
5104             }
5105           if (isAllZeros)
5106             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5107                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5108         }
5109         break;
5110
5111       case Instruction::PHI:
5112         if (Instruction *NV = FoldOpIntoPhi(I))
5113           return NV;
5114         break;
5115       case Instruction::Select:
5116         // If either operand of the select is a constant, we can fold the
5117         // comparison into the select arms, which will cause one to be
5118         // constant folded and the select turned into a bitwise or.
5119         Value *Op1 = 0, *Op2 = 0;
5120         if (LHSI->hasOneUse()) {
5121           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5122             // Fold the known value into the constant operand.
5123             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5124             // Insert a new ICmp of the other select operand.
5125             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5126                                                    LHSI->getOperand(2), RHSC,
5127                                                    I.getName()), I);
5128           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5129             // Fold the known value into the constant operand.
5130             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5131             // Insert a new ICmp of the other select operand.
5132             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5133                                                    LHSI->getOperand(1), RHSC,
5134                                                    I.getName()), I);
5135           }
5136         }
5137
5138         if (Op1)
5139           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5140         break;
5141       }
5142   }
5143
5144   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5145   if (User *GEP = dyn_castGetElementPtr(Op0))
5146     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5147       return NI;
5148   if (User *GEP = dyn_castGetElementPtr(Op1))
5149     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5150                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5151       return NI;
5152
5153   // Test to see if the operands of the icmp are casted versions of other
5154   // values.  If the cast can be stripped off both arguments, we do so now.
5155   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5156     Value *CastOp0 = CI->getOperand(0);
5157     if (CI->isLosslessCast() && I.isEquality() && 
5158         (isa<Constant>(Op1) || isa<CastInst>(Op1))) { 
5159       // We keep moving the cast from the left operand over to the right
5160       // operand, where it can often be eliminated completely.
5161       Op0 = CastOp0;
5162
5163       // If operand #1 is a cast instruction, see if we can eliminate it as
5164       // well.
5165       if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) { 
5166         Value *CI2Op0 = CI2->getOperand(0);
5167         if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5168           Op1 = CI2Op0;
5169       }
5170
5171       // If Op1 is a constant, we can fold the cast into the constant.
5172       if (Op1->getType() != Op0->getType())
5173         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5174           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5175         } else {
5176           // Otherwise, cast the RHS right before the icmp
5177           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5178         }
5179       return new ICmpInst(I.getPredicate(), Op0, Op1);
5180     }
5181
5182     // Handle the special case of: icmp (cast bool to X), <cst>
5183     // This comes up when you have code like
5184     //   int X = A < B;
5185     //   if (X) ...
5186     // For generality, we handle any zero-extension of any operand comparison
5187     // with a constant or another cast from the same type.
5188     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5189       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5190         return R;
5191   }
5192   
5193   if (I.isEquality()) {
5194     Value *A, *B;
5195     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
5196         (A == Op1 || B == Op1)) {
5197       // (A^B) == A  ->  B == 0
5198       Value *OtherVal = A == Op1 ? B : A;
5199       return new ICmpInst(I.getPredicate(), OtherVal,
5200                           Constant::getNullValue(A->getType()));
5201     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5202                (A == Op0 || B == Op0)) {
5203       // A == (A^B)  ->  B == 0
5204       Value *OtherVal = A == Op0 ? B : A;
5205       return new ICmpInst(I.getPredicate(), OtherVal,
5206                           Constant::getNullValue(A->getType()));
5207     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5208       // (A-B) == A  ->  B == 0
5209       return new ICmpInst(I.getPredicate(), B,
5210                           Constant::getNullValue(B->getType()));
5211     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5212       // A == (A-B)  ->  B == 0
5213       return new ICmpInst(I.getPredicate(), B,
5214                           Constant::getNullValue(B->getType()));
5215     }
5216     
5217     Value *C, *D;
5218     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5219     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5220         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5221         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5222       Value *X = 0, *Y = 0, *Z = 0;
5223       
5224       if (A == C) {
5225         X = B; Y = D; Z = A;
5226       } else if (A == D) {
5227         X = B; Y = C; Z = A;
5228       } else if (B == C) {
5229         X = A; Y = D; Z = B;
5230       } else if (B == D) {
5231         X = A; Y = C; Z = B;
5232       }
5233       
5234       if (X) {   // Build (X^Y) & Z
5235         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5236         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5237         I.setOperand(0, Op1);
5238         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5239         return &I;
5240       }
5241     }
5242   }
5243   return Changed ? &I : 0;
5244 }
5245
5246 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5247 // We only handle extending casts so far.
5248 //
5249 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5250   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5251   Value *LHSCIOp        = LHSCI->getOperand(0);
5252   const Type *SrcTy     = LHSCIOp->getType();
5253   const Type *DestTy    = LHSCI->getType();
5254   Value *RHSCIOp;
5255
5256   // We only handle extension cast instructions, so far. Enforce this.
5257   if (LHSCI->getOpcode() != Instruction::ZExt &&
5258       LHSCI->getOpcode() != Instruction::SExt)
5259     return 0;
5260
5261   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5262   bool isSignedCmp = ICI.isSignedPredicate();
5263
5264   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5265     // Not an extension from the same type?
5266     RHSCIOp = CI->getOperand(0);
5267     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5268       return 0;
5269     else
5270       // Okay, just insert a compare of the reduced operands now!
5271       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5272   }
5273
5274   // If we aren't dealing with a constant on the RHS, exit early
5275   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5276   if (!CI)
5277     return 0;
5278
5279   // Compute the constant that would happen if we truncated to SrcTy then
5280   // reextended to DestTy.
5281   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5282   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5283
5284   // If the re-extended constant didn't change...
5285   if (Res2 == CI) {
5286     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5287     // For example, we might have:
5288     //    %A = sext short %X to uint
5289     //    %B = icmp ugt uint %A, 1330
5290     // It is incorrect to transform this into 
5291     //    %B = icmp ugt short %X, 1330 
5292     // because %A may have negative value. 
5293     //
5294     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5295     // OR operation is EQ/NE.
5296     if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5297       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5298     else
5299       return 0;
5300   }
5301
5302   // The re-extended constant changed so the constant cannot be represented 
5303   // in the shorter type. Consequently, we cannot emit a simple comparison.
5304
5305   // First, handle some easy cases. We know the result cannot be equal at this
5306   // point so handle the ICI.isEquality() cases
5307   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5308     return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5309   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5310     return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5311
5312   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5313   // should have been folded away previously and not enter in here.
5314   Value *Result;
5315   if (isSignedCmp) {
5316     // We're performing a signed comparison.
5317     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5318       Result = ConstantBool::getFalse();          // X < (small) --> false
5319     else
5320       Result = ConstantBool::getTrue();           // X < (large) --> true
5321   } else {
5322     // We're performing an unsigned comparison.
5323     if (isSignedExt) {
5324       // We're performing an unsigned comp with a sign extended value.
5325       // This is true if the input is >= 0. [aka >s -1]
5326       Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5327       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5328                                    NegOne, ICI.getName()), ICI);
5329     } else {
5330       // Unsigned extend & unsigned compare -> always true.
5331       Result = ConstantBool::getTrue();
5332     }
5333   }
5334
5335   // Finally, return the value computed.
5336   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5337       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5338     return ReplaceInstUsesWith(ICI, Result);
5339   } else {
5340     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5341             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5342            "ICmp should be folded!");
5343     if (Constant *CI = dyn_cast<Constant>(Result))
5344       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5345     else
5346       return BinaryOperator::createNot(Result);
5347   }
5348 }
5349
5350 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5351   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5352   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5353
5354   // shl X, 0 == X and shr X, 0 == X
5355   // shl 0, X == 0 and shr 0, X == 0
5356   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5357       Op0 == Constant::getNullValue(Op0->getType()))
5358     return ReplaceInstUsesWith(I, Op0);
5359   
5360   if (isa<UndefValue>(Op0)) {            
5361     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5362       return ReplaceInstUsesWith(I, Op0);
5363     else                                    // undef << X -> 0, undef >>u X -> 0
5364       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5365   }
5366   if (isa<UndefValue>(Op1)) {
5367     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5368       return ReplaceInstUsesWith(I, Op0);          
5369     else                                     // X << undef, X >>u undef -> 0
5370       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5371   }
5372
5373   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5374   if (I.getOpcode() == Instruction::AShr)
5375     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5376       if (CSI->isAllOnesValue())
5377         return ReplaceInstUsesWith(I, CSI);
5378
5379   // Try to fold constant and into select arguments.
5380   if (isa<Constant>(Op0))
5381     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5382       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5383         return R;
5384
5385   // See if we can turn a signed shr into an unsigned shr.
5386   if (I.isArithmeticShift()) {
5387     if (MaskedValueIsZero(Op0,
5388                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5389       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5390     }
5391   }
5392
5393   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5394     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5395       return Res;
5396   return 0;
5397 }
5398
5399 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5400                                                ShiftInst &I) {
5401   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5402   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5403   bool isUnsignedShift = !isSignedShift;
5404
5405   // See if we can simplify any instructions used by the instruction whose sole 
5406   // purpose is to compute bits we don't care about.
5407   uint64_t KnownZero, KnownOne;
5408   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5409                            KnownZero, KnownOne))
5410     return &I;
5411   
5412   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5413   // of a signed value.
5414   //
5415   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5416   if (Op1->getZExtValue() >= TypeBits) {
5417     if (isUnsignedShift || isLeftShift)
5418       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5419     else {
5420       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5421       return &I;
5422     }
5423   }
5424   
5425   // ((X*C1) << C2) == (X * (C1 << C2))
5426   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5427     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5428       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5429         return BinaryOperator::createMul(BO->getOperand(0),
5430                                          ConstantExpr::getShl(BOOp, Op1));
5431   
5432   // Try to fold constant and into select arguments.
5433   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5434     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5435       return R;
5436   if (isa<PHINode>(Op0))
5437     if (Instruction *NV = FoldOpIntoPhi(I))
5438       return NV;
5439   
5440   if (Op0->hasOneUse()) {
5441     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5442       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5443       Value *V1, *V2;
5444       ConstantInt *CC;
5445       switch (Op0BO->getOpcode()) {
5446         default: break;
5447         case Instruction::Add:
5448         case Instruction::And:
5449         case Instruction::Or:
5450         case Instruction::Xor:
5451           // These operators commute.
5452           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5453           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5454               match(Op0BO->getOperand(1),
5455                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5456             Instruction *YS = new ShiftInst(Instruction::Shl, 
5457                                             Op0BO->getOperand(0), Op1,
5458                                             Op0BO->getName());
5459             InsertNewInstBefore(YS, I); // (Y << C)
5460             Instruction *X = 
5461               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5462                                      Op0BO->getOperand(1)->getName());
5463             InsertNewInstBefore(X, I);  // (X + (Y << C))
5464             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5465             C2 = ConstantExpr::getShl(C2, Op1);
5466             return BinaryOperator::createAnd(X, C2);
5467           }
5468           
5469           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5470           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5471               match(Op0BO->getOperand(1),
5472                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5473                           m_ConstantInt(CC))) && V2 == Op1 &&
5474       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5475             Instruction *YS = new ShiftInst(Instruction::Shl, 
5476                                             Op0BO->getOperand(0), Op1,
5477                                             Op0BO->getName());
5478             InsertNewInstBefore(YS, I); // (Y << C)
5479             Instruction *XM =
5480               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5481                                         V1->getName()+".mask");
5482             InsertNewInstBefore(XM, I); // X & (CC << C)
5483             
5484             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5485           }
5486           
5487           // FALL THROUGH.
5488         case Instruction::Sub:
5489           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5490           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5491               match(Op0BO->getOperand(0),
5492                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5493             Instruction *YS = new ShiftInst(Instruction::Shl, 
5494                                             Op0BO->getOperand(1), Op1,
5495                                             Op0BO->getName());
5496             InsertNewInstBefore(YS, I); // (Y << C)
5497             Instruction *X =
5498               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5499                                      Op0BO->getOperand(0)->getName());
5500             InsertNewInstBefore(X, I);  // (X + (Y << C))
5501             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5502             C2 = ConstantExpr::getShl(C2, Op1);
5503             return BinaryOperator::createAnd(X, C2);
5504           }
5505           
5506           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5507           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5508               match(Op0BO->getOperand(0),
5509                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5510                           m_ConstantInt(CC))) && V2 == Op1 &&
5511               cast<BinaryOperator>(Op0BO->getOperand(0))
5512                   ->getOperand(0)->hasOneUse()) {
5513             Instruction *YS = new ShiftInst(Instruction::Shl, 
5514                                             Op0BO->getOperand(1), Op1,
5515                                             Op0BO->getName());
5516             InsertNewInstBefore(YS, I); // (Y << C)
5517             Instruction *XM =
5518               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5519                                         V1->getName()+".mask");
5520             InsertNewInstBefore(XM, I); // X & (CC << C)
5521             
5522             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5523           }
5524           
5525           break;
5526       }
5527       
5528       
5529       // If the operand is an bitwise operator with a constant RHS, and the
5530       // shift is the only use, we can pull it out of the shift.
5531       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5532         bool isValid = true;     // Valid only for And, Or, Xor
5533         bool highBitSet = false; // Transform if high bit of constant set?
5534         
5535         switch (Op0BO->getOpcode()) {
5536           default: isValid = false; break;   // Do not perform transform!
5537           case Instruction::Add:
5538             isValid = isLeftShift;
5539             break;
5540           case Instruction::Or:
5541           case Instruction::Xor:
5542             highBitSet = false;
5543             break;
5544           case Instruction::And:
5545             highBitSet = true;
5546             break;
5547         }
5548         
5549         // If this is a signed shift right, and the high bit is modified
5550         // by the logical operation, do not perform the transformation.
5551         // The highBitSet boolean indicates the value of the high bit of
5552         // the constant which would cause it to be modified for this
5553         // operation.
5554         //
5555         if (isValid && !isLeftShift && isSignedShift) {
5556           uint64_t Val = Op0C->getZExtValue();
5557           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5558         }
5559         
5560         if (isValid) {
5561           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5562           
5563           Instruction *NewShift =
5564             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5565                           Op0BO->getName());
5566           Op0BO->setName("");
5567           InsertNewInstBefore(NewShift, I);
5568           
5569           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5570                                         NewRHS);
5571         }
5572       }
5573     }
5574   }
5575   
5576   // Find out if this is a shift of a shift by a constant.
5577   ShiftInst *ShiftOp = 0;
5578   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5579     ShiftOp = Op0SI;
5580   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5581     // If this is a noop-integer cast of a shift instruction, use the shift.
5582     if (isa<ShiftInst>(CI->getOperand(0))) {
5583       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5584     }
5585   }
5586   
5587   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5588     // Find the operands and properties of the input shift.  Note that the
5589     // signedness of the input shift may differ from the current shift if there
5590     // is a noop cast between the two.
5591     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5592     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5593     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5594     
5595     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5596
5597     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5598     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5599     
5600     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5601     if (isLeftShift == isShiftOfLeftShift) {
5602       // Do not fold these shifts if the first one is signed and the second one
5603       // is unsigned and this is a right shift.  Further, don't do any folding
5604       // on them.
5605       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5606         return 0;
5607       
5608       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5609       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5610         Amt = Op0->getType()->getPrimitiveSizeInBits();
5611       
5612       Value *Op = ShiftOp->getOperand(0);
5613       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5614                                           ConstantInt::get(Type::Int8Ty, Amt));
5615       if (I.getType() == ShiftResult->getType())
5616         return ShiftResult;
5617       InsertNewInstBefore(ShiftResult, I);
5618       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5619     }
5620     
5621     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5622     // signed types, we can only support the (A >> c1) << c2 configuration,
5623     // because it can not turn an arbitrary bit of A into a sign bit.
5624     if (isUnsignedShift || isLeftShift) {
5625       // Calculate bitmask for what gets shifted off the edge.
5626       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5627       if (isLeftShift)
5628         C = ConstantExpr::getShl(C, ShiftAmt1C);
5629       else
5630         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5631       
5632       Value *Op = ShiftOp->getOperand(0);
5633       if (Op->getType() != C->getType())
5634         Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
5635       
5636       Instruction *Mask =
5637         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5638       InsertNewInstBefore(Mask, I);
5639       
5640       // Figure out what flavor of shift we should use...
5641       if (ShiftAmt1 == ShiftAmt2) {
5642         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5643       } else if (ShiftAmt1 < ShiftAmt2) {
5644         return new ShiftInst(I.getOpcode(), Mask,
5645                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5646       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5647         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5648           return new ShiftInst(Instruction::LShr, Mask, 
5649             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5650         } else {
5651           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5652                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5653         }
5654       } else {
5655         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5656         Instruction *Shift =
5657           new ShiftInst(ShiftOp->getOpcode(), Mask,
5658                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5659         InsertNewInstBefore(Shift, I);
5660         
5661         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5662         C = ConstantExpr::getShl(C, Op1);
5663         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5664       }
5665     } else {
5666       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5667       // this case, C1 == C2 and C1 is 8, 16, or 32.
5668       if (ShiftAmt1 == ShiftAmt2) {
5669         const Type *SExtType = 0;
5670         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5671         case 8 : SExtType = Type::Int8Ty; break;
5672         case 16: SExtType = Type::Int16Ty; break;
5673         case 32: SExtType = Type::Int32Ty; break;
5674         }
5675         
5676         if (SExtType) {
5677           Instruction *NewTrunc = 
5678             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5679           InsertNewInstBefore(NewTrunc, I);
5680           return new SExtInst(NewTrunc, I.getType());
5681         }
5682       }
5683     }
5684   }
5685   return 0;
5686 }
5687
5688
5689 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5690 /// expression.  If so, decompose it, returning some value X, such that Val is
5691 /// X*Scale+Offset.
5692 ///
5693 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5694                                         unsigned &Offset) {
5695   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5696   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5697     Offset = CI->getZExtValue();
5698     Scale  = 1;
5699     return ConstantInt::get(Type::Int32Ty, 0);
5700   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5701     if (I->getNumOperands() == 2) {
5702       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5703         if (I->getOpcode() == Instruction::Shl) {
5704           // This is a value scaled by '1 << the shift amt'.
5705           Scale = 1U << CUI->getZExtValue();
5706           Offset = 0;
5707           return I->getOperand(0);
5708         } else if (I->getOpcode() == Instruction::Mul) {
5709           // This value is scaled by 'CUI'.
5710           Scale = CUI->getZExtValue();
5711           Offset = 0;
5712           return I->getOperand(0);
5713         } else if (I->getOpcode() == Instruction::Add) {
5714           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5715           // where C1 is divisible by C2.
5716           unsigned SubScale;
5717           Value *SubVal = 
5718             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5719           Offset += CUI->getZExtValue();
5720           if (SubScale > 1 && (Offset % SubScale == 0)) {
5721             Scale = SubScale;
5722             return SubVal;
5723           }
5724         }
5725       }
5726     }
5727   }
5728
5729   // Otherwise, we can't look past this.
5730   Scale = 1;
5731   Offset = 0;
5732   return Val;
5733 }
5734
5735
5736 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5737 /// try to eliminate the cast by moving the type information into the alloc.
5738 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5739                                                    AllocationInst &AI) {
5740   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5741   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5742   
5743   // Remove any uses of AI that are dead.
5744   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5745   std::vector<Instruction*> DeadUsers;
5746   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5747     Instruction *User = cast<Instruction>(*UI++);
5748     if (isInstructionTriviallyDead(User)) {
5749       while (UI != E && *UI == User)
5750         ++UI; // If this instruction uses AI more than once, don't break UI.
5751       
5752       // Add operands to the worklist.
5753       AddUsesToWorkList(*User);
5754       ++NumDeadInst;
5755       DOUT << "IC: DCE: " << *User;
5756       
5757       User->eraseFromParent();
5758       removeFromWorkList(User);
5759     }
5760   }
5761   
5762   // Get the type really allocated and the type casted to.
5763   const Type *AllocElTy = AI.getAllocatedType();
5764   const Type *CastElTy = PTy->getElementType();
5765   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5766
5767   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5768   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5769   if (CastElTyAlign < AllocElTyAlign) return 0;
5770
5771   // If the allocation has multiple uses, only promote it if we are strictly
5772   // increasing the alignment of the resultant allocation.  If we keep it the
5773   // same, we open the door to infinite loops of various kinds.
5774   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5775
5776   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5777   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5778   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5779
5780   // See if we can satisfy the modulus by pulling a scale out of the array
5781   // size argument.
5782   unsigned ArraySizeScale, ArrayOffset;
5783   Value *NumElements = // See if the array size is a decomposable linear expr.
5784     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5785  
5786   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5787   // do the xform.
5788   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5789       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5790
5791   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5792   Value *Amt = 0;
5793   if (Scale == 1) {
5794     Amt = NumElements;
5795   } else {
5796     // If the allocation size is constant, form a constant mul expression
5797     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5798     if (isa<ConstantInt>(NumElements))
5799       Amt = ConstantExpr::getMul(
5800               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5801     // otherwise multiply the amount and the number of elements
5802     else if (Scale != 1) {
5803       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5804       Amt = InsertNewInstBefore(Tmp, AI);
5805     }
5806   }
5807   
5808   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5809     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5810     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5811     Amt = InsertNewInstBefore(Tmp, AI);
5812   }
5813   
5814   std::string Name = AI.getName(); AI.setName("");
5815   AllocationInst *New;
5816   if (isa<MallocInst>(AI))
5817     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5818   else
5819     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5820   InsertNewInstBefore(New, AI);
5821   
5822   // If the allocation has multiple uses, insert a cast and change all things
5823   // that used it to use the new cast.  This will also hack on CI, but it will
5824   // die soon.
5825   if (!AI.hasOneUse()) {
5826     AddUsesToWorkList(AI);
5827     // New is the allocation instruction, pointer typed. AI is the original
5828     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5829     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5830     InsertNewInstBefore(NewCast, AI);
5831     AI.replaceAllUsesWith(NewCast);
5832   }
5833   return ReplaceInstUsesWith(CI, New);
5834 }
5835
5836 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5837 /// and return it without inserting any new casts.  This is used by code that
5838 /// tries to decide whether promoting or shrinking integer operations to wider
5839 /// or smaller types will allow us to eliminate a truncate or extend.
5840 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5841                                        int &NumCastsRemoved) {
5842   if (isa<Constant>(V)) return true;
5843   
5844   Instruction *I = dyn_cast<Instruction>(V);
5845   if (!I || !I->hasOneUse()) return false;
5846   
5847   switch (I->getOpcode()) {
5848   case Instruction::And:
5849   case Instruction::Or:
5850   case Instruction::Xor:
5851     // These operators can all arbitrarily be extended or truncated.
5852     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5853            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5854   case Instruction::AShr:
5855   case Instruction::LShr:
5856   case Instruction::Shl:
5857     // If this is just a bitcast changing the sign of the operation, we can
5858     // convert if the operand can be converted.
5859     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5860       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5861     break;
5862   case Instruction::Trunc:
5863   case Instruction::ZExt:
5864   case Instruction::SExt:
5865   case Instruction::BitCast:
5866     // If this is a cast from the destination type, we can trivially eliminate
5867     // it, and this will remove a cast overall.
5868     if (I->getOperand(0)->getType() == Ty) {
5869       // If the first operand is itself a cast, and is eliminable, do not count
5870       // this as an eliminable cast.  We would prefer to eliminate those two
5871       // casts first.
5872       if (isa<CastInst>(I->getOperand(0)))
5873         return true;
5874       
5875       ++NumCastsRemoved;
5876       return true;
5877     }
5878     break;
5879   default:
5880     // TODO: Can handle more cases here.
5881     break;
5882   }
5883   
5884   return false;
5885 }
5886
5887 /// EvaluateInDifferentType - Given an expression that 
5888 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5889 /// evaluate the expression.
5890 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5891                                              bool isSigned ) {
5892   if (Constant *C = dyn_cast<Constant>(V))
5893     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5894
5895   // Otherwise, it must be an instruction.
5896   Instruction *I = cast<Instruction>(V);
5897   Instruction *Res = 0;
5898   switch (I->getOpcode()) {
5899   case Instruction::And:
5900   case Instruction::Or:
5901   case Instruction::Xor: {
5902     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5903     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5904     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5905                                  LHS, RHS, I->getName());
5906     break;
5907   }
5908   case Instruction::AShr:
5909   case Instruction::LShr:
5910   case Instruction::Shl: {
5911     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5912     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5913                         I->getOperand(1), I->getName());
5914     break;
5915   }    
5916   case Instruction::Trunc:
5917   case Instruction::ZExt:
5918   case Instruction::SExt:
5919   case Instruction::BitCast:
5920     // If the source type of the cast is the type we're trying for then we can
5921     // just return the source. There's no need to insert it because its not new.
5922     if (I->getOperand(0)->getType() == Ty)
5923       return I->getOperand(0);
5924     
5925     // Some other kind of cast, which shouldn't happen, so just ..
5926     // FALL THROUGH
5927   default: 
5928     // TODO: Can handle more cases here.
5929     assert(0 && "Unreachable!");
5930     break;
5931   }
5932   
5933   return InsertNewInstBefore(Res, *I);
5934 }
5935
5936 /// @brief Implement the transforms common to all CastInst visitors.
5937 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5938   Value *Src = CI.getOperand(0);
5939
5940   // Casting undef to anything results in undef so might as just replace it and
5941   // get rid of the cast.
5942   if (isa<UndefValue>(Src))   // cast undef -> undef
5943     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5944
5945   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5946   // eliminate it now.
5947   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5948     if (Instruction::CastOps opc = 
5949         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5950       // The first cast (CSrc) is eliminable so we need to fix up or replace
5951       // the second cast (CI). CSrc will then have a good chance of being dead.
5952       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5953     }
5954   }
5955
5956   // If casting the result of a getelementptr instruction with no offset, turn
5957   // this into a cast of the original pointer!
5958   //
5959   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5960     bool AllZeroOperands = true;
5961     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5962       if (!isa<Constant>(GEP->getOperand(i)) ||
5963           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5964         AllZeroOperands = false;
5965         break;
5966       }
5967     if (AllZeroOperands) {
5968       // Changing the cast operand is usually not a good idea but it is safe
5969       // here because the pointer operand is being replaced with another 
5970       // pointer operand so the opcode doesn't need to change.
5971       CI.setOperand(0, GEP->getOperand(0));
5972       return &CI;
5973     }
5974   }
5975     
5976   // If we are casting a malloc or alloca to a pointer to a type of the same
5977   // size, rewrite the allocation instruction to allocate the "right" type.
5978   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5979     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5980       return V;
5981
5982   // If we are casting a select then fold the cast into the select
5983   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5984     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5985       return NV;
5986
5987   // If we are casting a PHI then fold the cast into the PHI
5988   if (isa<PHINode>(Src))
5989     if (Instruction *NV = FoldOpIntoPhi(CI))
5990       return NV;
5991   
5992   return 0;
5993 }
5994
5995 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5996 /// integers. This function implements the common transforms for all those
5997 /// cases.
5998 /// @brief Implement the transforms common to CastInst with integer operands
5999 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6000   if (Instruction *Result = commonCastTransforms(CI))
6001     return Result;
6002
6003   Value *Src = CI.getOperand(0);
6004   const Type *SrcTy = Src->getType();
6005   const Type *DestTy = CI.getType();
6006   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6007   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6008
6009   // See if we can simplify any instructions used by the LHS whose sole 
6010   // purpose is to compute bits we don't care about.
6011   uint64_t KnownZero = 0, KnownOne = 0;
6012   if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6013                            KnownZero, KnownOne))
6014     return &CI;
6015
6016   // If the source isn't an instruction or has more than one use then we
6017   // can't do anything more. 
6018   Instruction *SrcI = dyn_cast<Instruction>(Src);
6019   if (!SrcI || !Src->hasOneUse())
6020     return 0;
6021
6022   // Attempt to propagate the cast into the instruction.
6023   int NumCastsRemoved = 0;
6024   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6025     // If this cast is a truncate, evaluting in a different type always
6026     // eliminates the cast, so it is always a win.  If this is a noop-cast
6027     // this just removes a noop cast which isn't pointful, but simplifies
6028     // the code.  If this is a zero-extension, we need to do an AND to
6029     // maintain the clear top-part of the computation, so we require that
6030     // the input have eliminated at least one cast.  If this is a sign
6031     // extension, we insert two new casts (to do the extension) so we
6032     // require that two casts have been eliminated.
6033     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6034     if (!DoXForm) {
6035       switch (CI.getOpcode()) {
6036         case Instruction::Trunc:
6037           DoXForm = true;
6038           break;
6039         case Instruction::ZExt:
6040           DoXForm = NumCastsRemoved >= 1;
6041           break;
6042         case Instruction::SExt:
6043           DoXForm = NumCastsRemoved >= 2;
6044           break;
6045         case Instruction::BitCast:
6046           DoXForm = false;
6047           break;
6048         default:
6049           // All the others use floating point so we shouldn't actually 
6050           // get here because of the check above.
6051           assert(!"Unknown cast type .. unreachable");
6052           break;
6053       }
6054     }
6055     
6056     if (DoXForm) {
6057       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6058                                            CI.getOpcode() == Instruction::SExt);
6059       assert(Res->getType() == DestTy);
6060       switch (CI.getOpcode()) {
6061       default: assert(0 && "Unknown cast type!");
6062       case Instruction::Trunc:
6063       case Instruction::BitCast:
6064         // Just replace this cast with the result.
6065         return ReplaceInstUsesWith(CI, Res);
6066       case Instruction::ZExt: {
6067         // We need to emit an AND to clear the high bits.
6068         assert(SrcBitSize < DestBitSize && "Not a zext?");
6069         Constant *C = 
6070           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6071         if (DestBitSize < 64)
6072           C = ConstantExpr::getTrunc(C, DestTy);
6073         else {
6074           assert(DestBitSize == 64);
6075           C = ConstantExpr::getBitCast(C, DestTy);
6076         }
6077         return BinaryOperator::createAnd(Res, C);
6078       }
6079       case Instruction::SExt:
6080         // We need to emit a cast to truncate, then a cast to sext.
6081         return CastInst::create(Instruction::SExt,
6082             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6083                              CI), DestTy);
6084       }
6085     }
6086   }
6087   
6088   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6089   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6090
6091   switch (SrcI->getOpcode()) {
6092   case Instruction::Add:
6093   case Instruction::Mul:
6094   case Instruction::And:
6095   case Instruction::Or:
6096   case Instruction::Xor:
6097     // If we are discarding information, or just changing the sign, 
6098     // rewrite.
6099     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6100       // Don't insert two casts if they cannot be eliminated.  We allow 
6101       // two casts to be inserted if the sizes are the same.  This could 
6102       // only be converting signedness, which is a noop.
6103       if (DestBitSize == SrcBitSize || 
6104           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6105           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6106         Instruction::CastOps opcode = CI.getOpcode();
6107         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6108         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6109         return BinaryOperator::create(
6110             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6111       }
6112     }
6113
6114     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6115     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6116         SrcI->getOpcode() == Instruction::Xor &&
6117         Op1 == ConstantBool::getTrue() &&
6118         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6119       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6120       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6121     }
6122     break;
6123   case Instruction::SDiv:
6124   case Instruction::UDiv:
6125   case Instruction::SRem:
6126   case Instruction::URem:
6127     // If we are just changing the sign, rewrite.
6128     if (DestBitSize == SrcBitSize) {
6129       // Don't insert two casts if they cannot be eliminated.  We allow 
6130       // two casts to be inserted if the sizes are the same.  This could 
6131       // only be converting signedness, which is a noop.
6132       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6133           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6134         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6135                                               Op0, DestTy, SrcI);
6136         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6137                                               Op1, DestTy, SrcI);
6138         return BinaryOperator::create(
6139           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6140       }
6141     }
6142     break;
6143
6144   case Instruction::Shl:
6145     // Allow changing the sign of the source operand.  Do not allow 
6146     // changing the size of the shift, UNLESS the shift amount is a 
6147     // constant.  We must not change variable sized shifts to a smaller 
6148     // size, because it is undefined to shift more bits out than exist 
6149     // in the value.
6150     if (DestBitSize == SrcBitSize ||
6151         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6152       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6153           Instruction::BitCast : Instruction::Trunc);
6154       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6155       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6156     }
6157     break;
6158   case Instruction::AShr:
6159     // If this is a signed shr, and if all bits shifted in are about to be
6160     // truncated off, turn it into an unsigned shr to allow greater
6161     // simplifications.
6162     if (DestBitSize < SrcBitSize &&
6163         isa<ConstantInt>(Op1)) {
6164       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6165       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6166         // Insert the new logical shift right.
6167         return new ShiftInst(Instruction::LShr, Op0, Op1);
6168       }
6169     }
6170     break;
6171
6172   case Instruction::ICmp:
6173     // If we are just checking for a icmp eq of a single bit and casting it
6174     // to an integer, then shift the bit to the appropriate place and then
6175     // cast to integer to avoid the comparison.
6176     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6177       uint64_t Op1CV = Op1C->getZExtValue();
6178       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6179       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6180       // cast (X == 1) to int --> X        iff X has only the low bit set.
6181       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6182       // cast (X != 0) to int --> X        iff X has only the low bit set.
6183       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6184       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6185       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6186       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6187         // If Op1C some other power of two, convert:
6188         uint64_t KnownZero, KnownOne;
6189         uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6190         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6191
6192         // This only works for EQ and NE
6193         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6194         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6195           break;
6196         
6197         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6198           bool isNE = pred == ICmpInst::ICMP_NE;
6199           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6200             // (X&4) == 2 --> false
6201             // (X&4) != 2 --> true
6202             Constant *Res = ConstantBool::get(isNE);
6203             Res = ConstantExpr::getZExt(Res, CI.getType());
6204             return ReplaceInstUsesWith(CI, Res);
6205           }
6206           
6207           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6208           Value *In = Op0;
6209           if (ShiftAmt) {
6210             // Perform a logical shr by shiftamt.
6211             // Insert the shift to put the result in the low bit.
6212             In = InsertNewInstBefore(
6213               new ShiftInst(Instruction::LShr, In,
6214                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6215                             In->getName()+".lobit"), CI);
6216           }
6217           
6218           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6219             Constant *One = ConstantInt::get(In->getType(), 1);
6220             In = BinaryOperator::createXor(In, One, "tmp");
6221             InsertNewInstBefore(cast<Instruction>(In), CI);
6222           }
6223           
6224           if (CI.getType() == In->getType())
6225             return ReplaceInstUsesWith(CI, In);
6226           else
6227             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6228         }
6229       }
6230     }
6231     break;
6232   }
6233   return 0;
6234 }
6235
6236 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6237   if (Instruction *Result = commonIntCastTransforms(CI))
6238     return Result;
6239   
6240   Value *Src = CI.getOperand(0);
6241   const Type *Ty = CI.getType();
6242   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6243   
6244   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6245     switch (SrcI->getOpcode()) {
6246     default: break;
6247     case Instruction::LShr:
6248       // We can shrink lshr to something smaller if we know the bits shifted in
6249       // are already zeros.
6250       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6251         unsigned ShAmt = ShAmtV->getZExtValue();
6252         
6253         // Get a mask for the bits shifting in.
6254         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6255         Value* SrcIOp0 = SrcI->getOperand(0);
6256         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6257           if (ShAmt >= DestBitWidth)        // All zeros.
6258             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6259
6260           // Okay, we can shrink this.  Truncate the input, then return a new
6261           // shift.
6262           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6263           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6264         }
6265       } else {     // This is a variable shr.
6266         
6267         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6268         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6269         // loop-invariant and CSE'd.
6270         if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6271           Value *One = ConstantInt::get(SrcI->getType(), 1);
6272
6273           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6274                                                        SrcI->getOperand(1),
6275                                                        "tmp"), CI);
6276           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6277                                                             SrcI->getOperand(0),
6278                                                             "tmp"), CI);
6279           Value *Zero = Constant::getNullValue(V->getType());
6280           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6281         }
6282       }
6283       break;
6284     }
6285   }
6286   
6287   return 0;
6288 }
6289
6290 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6291   // If one of the common conversion will work ..
6292   if (Instruction *Result = commonIntCastTransforms(CI))
6293     return Result;
6294
6295   Value *Src = CI.getOperand(0);
6296
6297   // If this is a cast of a cast
6298   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6299     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6300     // types and if the sizes are just right we can convert this into a logical
6301     // 'and' which will be much cheaper than the pair of casts.
6302     if (isa<TruncInst>(CSrc)) {
6303       // Get the sizes of the types involved
6304       Value *A = CSrc->getOperand(0);
6305       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6306       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6307       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6308       // If we're actually extending zero bits and the trunc is a no-op
6309       if (MidSize < DstSize && SrcSize == DstSize) {
6310         // Replace both of the casts with an And of the type mask.
6311         uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6312         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6313         Instruction *And = 
6314           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6315         // Unfortunately, if the type changed, we need to cast it back.
6316         if (And->getType() != CI.getType()) {
6317           And->setName(CSrc->getName()+".mask");
6318           InsertNewInstBefore(And, CI);
6319           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6320         }
6321         return And;
6322       }
6323     }
6324   }
6325
6326   return 0;
6327 }
6328
6329 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6330   return commonIntCastTransforms(CI);
6331 }
6332
6333 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6334   return commonCastTransforms(CI);
6335 }
6336
6337 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6338   return commonCastTransforms(CI);
6339 }
6340
6341 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6342   return commonCastTransforms(CI);
6343 }
6344
6345 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6346   return commonCastTransforms(CI);
6347 }
6348
6349 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6350   return commonCastTransforms(CI);
6351 }
6352
6353 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6354   return commonCastTransforms(CI);
6355 }
6356
6357 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6358   return commonCastTransforms(CI);
6359 }
6360
6361 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6362   return commonCastTransforms(CI);
6363 }
6364
6365 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6366
6367   // If the operands are integer typed then apply the integer transforms,
6368   // otherwise just apply the common ones.
6369   Value *Src = CI.getOperand(0);
6370   const Type *SrcTy = Src->getType();
6371   const Type *DestTy = CI.getType();
6372
6373   if (SrcTy->isInteger() && DestTy->isInteger()) {
6374     if (Instruction *Result = commonIntCastTransforms(CI))
6375       return Result;
6376   } else {
6377     if (Instruction *Result = commonCastTransforms(CI))
6378       return Result;
6379   }
6380
6381
6382   // Get rid of casts from one type to the same type. These are useless and can
6383   // be replaced by the operand.
6384   if (DestTy == Src->getType())
6385     return ReplaceInstUsesWith(CI, Src);
6386
6387   // If the source and destination are pointers, and this cast is equivalent to
6388   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6389   // This can enhance SROA and other transforms that want type-safe pointers.
6390   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6391     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6392       const Type *DstElTy = DstPTy->getElementType();
6393       const Type *SrcElTy = SrcPTy->getElementType();
6394       
6395       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6396       unsigned NumZeros = 0;
6397       while (SrcElTy != DstElTy && 
6398              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6399              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6400         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6401         ++NumZeros;
6402       }
6403
6404       // If we found a path from the src to dest, create the getelementptr now.
6405       if (SrcElTy == DstElTy) {
6406         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6407         return new GetElementPtrInst(Src, Idxs);
6408       }
6409     }
6410   }
6411
6412   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6413     if (SVI->hasOneUse()) {
6414       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6415       // a bitconvert to a vector with the same # elts.
6416       if (isa<PackedType>(DestTy) && 
6417           cast<PackedType>(DestTy)->getNumElements() == 
6418                 SVI->getType()->getNumElements()) {
6419         CastInst *Tmp;
6420         // If either of the operands is a cast from CI.getType(), then
6421         // evaluating the shuffle in the casted destination's type will allow
6422         // us to eliminate at least one cast.
6423         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6424              Tmp->getOperand(0)->getType() == DestTy) ||
6425             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6426              Tmp->getOperand(0)->getType() == DestTy)) {
6427           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6428                                                SVI->getOperand(0), DestTy, &CI);
6429           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6430                                                SVI->getOperand(1), DestTy, &CI);
6431           // Return a new shuffle vector.  Use the same element ID's, as we
6432           // know the vector types match #elts.
6433           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6434         }
6435       }
6436     }
6437   }
6438   return 0;
6439 }
6440
6441 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6442 ///   %C = or %A, %B
6443 ///   %D = select %cond, %C, %A
6444 /// into:
6445 ///   %C = select %cond, %B, 0
6446 ///   %D = or %A, %C
6447 ///
6448 /// Assuming that the specified instruction is an operand to the select, return
6449 /// a bitmask indicating which operands of this instruction are foldable if they
6450 /// equal the other incoming value of the select.
6451 ///
6452 static unsigned GetSelectFoldableOperands(Instruction *I) {
6453   switch (I->getOpcode()) {
6454   case Instruction::Add:
6455   case Instruction::Mul:
6456   case Instruction::And:
6457   case Instruction::Or:
6458   case Instruction::Xor:
6459     return 3;              // Can fold through either operand.
6460   case Instruction::Sub:   // Can only fold on the amount subtracted.
6461   case Instruction::Shl:   // Can only fold on the shift amount.
6462   case Instruction::LShr:
6463   case Instruction::AShr:
6464     return 1;
6465   default:
6466     return 0;              // Cannot fold
6467   }
6468 }
6469
6470 /// GetSelectFoldableConstant - For the same transformation as the previous
6471 /// function, return the identity constant that goes into the select.
6472 static Constant *GetSelectFoldableConstant(Instruction *I) {
6473   switch (I->getOpcode()) {
6474   default: assert(0 && "This cannot happen!"); abort();
6475   case Instruction::Add:
6476   case Instruction::Sub:
6477   case Instruction::Or:
6478   case Instruction::Xor:
6479     return Constant::getNullValue(I->getType());
6480   case Instruction::Shl:
6481   case Instruction::LShr:
6482   case Instruction::AShr:
6483     return Constant::getNullValue(Type::Int8Ty);
6484   case Instruction::And:
6485     return ConstantInt::getAllOnesValue(I->getType());
6486   case Instruction::Mul:
6487     return ConstantInt::get(I->getType(), 1);
6488   }
6489 }
6490
6491 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6492 /// have the same opcode and only one use each.  Try to simplify this.
6493 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6494                                           Instruction *FI) {
6495   if (TI->getNumOperands() == 1) {
6496     // If this is a non-volatile load or a cast from the same type,
6497     // merge.
6498     if (TI->isCast()) {
6499       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6500         return 0;
6501     } else {
6502       return 0;  // unknown unary op.
6503     }
6504
6505     // Fold this by inserting a select from the input values.
6506     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6507                                        FI->getOperand(0), SI.getName()+".v");
6508     InsertNewInstBefore(NewSI, SI);
6509     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6510                             TI->getType());
6511   }
6512
6513   // Only handle binary, compare and shift operators here.
6514   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6515     return 0;
6516
6517   // Figure out if the operations have any operands in common.
6518   Value *MatchOp, *OtherOpT, *OtherOpF;
6519   bool MatchIsOpZero;
6520   if (TI->getOperand(0) == FI->getOperand(0)) {
6521     MatchOp  = TI->getOperand(0);
6522     OtherOpT = TI->getOperand(1);
6523     OtherOpF = FI->getOperand(1);
6524     MatchIsOpZero = true;
6525   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6526     MatchOp  = TI->getOperand(1);
6527     OtherOpT = TI->getOperand(0);
6528     OtherOpF = FI->getOperand(0);
6529     MatchIsOpZero = false;
6530   } else if (!TI->isCommutative()) {
6531     return 0;
6532   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6533     MatchOp  = TI->getOperand(0);
6534     OtherOpT = TI->getOperand(1);
6535     OtherOpF = FI->getOperand(0);
6536     MatchIsOpZero = true;
6537   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6538     MatchOp  = TI->getOperand(1);
6539     OtherOpT = TI->getOperand(0);
6540     OtherOpF = FI->getOperand(1);
6541     MatchIsOpZero = true;
6542   } else {
6543     return 0;
6544   }
6545
6546   // If we reach here, they do have operations in common.
6547   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6548                                      OtherOpF, SI.getName()+".v");
6549   InsertNewInstBefore(NewSI, SI);
6550
6551   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6552     if (MatchIsOpZero)
6553       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6554     else
6555       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6556   }
6557
6558   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6559   if (MatchIsOpZero)
6560     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6561   else
6562     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6563 }
6564
6565 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6566   Value *CondVal = SI.getCondition();
6567   Value *TrueVal = SI.getTrueValue();
6568   Value *FalseVal = SI.getFalseValue();
6569
6570   // select true, X, Y  -> X
6571   // select false, X, Y -> Y
6572   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6573     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6574
6575   // select C, X, X -> X
6576   if (TrueVal == FalseVal)
6577     return ReplaceInstUsesWith(SI, TrueVal);
6578
6579   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6580     return ReplaceInstUsesWith(SI, FalseVal);
6581   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6582     return ReplaceInstUsesWith(SI, TrueVal);
6583   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6584     if (isa<Constant>(TrueVal))
6585       return ReplaceInstUsesWith(SI, TrueVal);
6586     else
6587       return ReplaceInstUsesWith(SI, FalseVal);
6588   }
6589
6590   if (SI.getType() == Type::BoolTy)
6591     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6592       if (C->getValue()) {
6593         // Change: A = select B, true, C --> A = or B, C
6594         return BinaryOperator::createOr(CondVal, FalseVal);
6595       } else {
6596         // Change: A = select B, false, C --> A = and !B, C
6597         Value *NotCond =
6598           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6599                                              "not."+CondVal->getName()), SI);
6600         return BinaryOperator::createAnd(NotCond, FalseVal);
6601       }
6602     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6603       if (C->getValue() == false) {
6604         // Change: A = select B, C, false --> A = and B, C
6605         return BinaryOperator::createAnd(CondVal, TrueVal);
6606       } else {
6607         // Change: A = select B, C, true --> A = or !B, C
6608         Value *NotCond =
6609           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6610                                              "not."+CondVal->getName()), SI);
6611         return BinaryOperator::createOr(NotCond, TrueVal);
6612       }
6613     }
6614
6615   // Selecting between two integer constants?
6616   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6617     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6618       // select C, 1, 0 -> cast C to int
6619       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6620         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6621       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6622         // select C, 0, 1 -> cast !C to int
6623         Value *NotCond =
6624           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6625                                                "not."+CondVal->getName()), SI);
6626         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6627       }
6628
6629       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6630
6631         // (x <s 0) ? -1 : 0 -> ashr x, 31
6632         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6633         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6634           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6635             bool CanXForm = false;
6636             if (IC->isSignedPredicate())
6637               CanXForm = CmpCst->isNullValue() && 
6638                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6639             else {
6640               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6641               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6642                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6643             }
6644             
6645             if (CanXForm) {
6646               // The comparison constant and the result are not neccessarily the
6647               // same width. Make an all-ones value by inserting a AShr.
6648               Value *X = IC->getOperand(0);
6649               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6650               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6651               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6652                                                ShAmt, "ones");
6653               InsertNewInstBefore(SRA, SI);
6654               
6655               // Finally, convert to the type of the select RHS.  We figure out
6656               // if this requires a SExt, Trunc or BitCast based on the sizes.
6657               Instruction::CastOps opc = Instruction::BitCast;
6658               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6659               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6660               if (SRASize < SISize)
6661                 opc = Instruction::SExt;
6662               else if (SRASize > SISize)
6663                 opc = Instruction::Trunc;
6664               return CastInst::create(opc, SRA, SI.getType());
6665             }
6666           }
6667
6668
6669         // If one of the constants is zero (we know they can't both be) and we
6670         // have a fcmp instruction with zero, and we have an 'and' with the
6671         // non-constant value, eliminate this whole mess.  This corresponds to
6672         // cases like this: ((X & 27) ? 27 : 0)
6673         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6674           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6675               cast<Constant>(IC->getOperand(1))->isNullValue())
6676             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6677               if (ICA->getOpcode() == Instruction::And &&
6678                   isa<ConstantInt>(ICA->getOperand(1)) &&
6679                   (ICA->getOperand(1) == TrueValC ||
6680                    ICA->getOperand(1) == FalseValC) &&
6681                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6682                 // Okay, now we know that everything is set up, we just don't
6683                 // know whether we have a icmp_ne or icmp_eq and whether the 
6684                 // true or false val is the zero.
6685                 bool ShouldNotVal = !TrueValC->isNullValue();
6686                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6687                 Value *V = ICA;
6688                 if (ShouldNotVal)
6689                   V = InsertNewInstBefore(BinaryOperator::create(
6690                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6691                 return ReplaceInstUsesWith(SI, V);
6692               }
6693       }
6694     }
6695
6696   // See if we are selecting two values based on a comparison of the two values.
6697   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6698     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6699       // Transform (X == Y) ? X : Y  -> Y
6700       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6701         return ReplaceInstUsesWith(SI, FalseVal);
6702       // Transform (X != Y) ? X : Y  -> X
6703       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6704         return ReplaceInstUsesWith(SI, TrueVal);
6705       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6706
6707     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6708       // Transform (X == Y) ? Y : X  -> X
6709       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6710         return ReplaceInstUsesWith(SI, FalseVal);
6711       // Transform (X != Y) ? Y : X  -> Y
6712       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6713         return ReplaceInstUsesWith(SI, TrueVal);
6714       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6715     }
6716   }
6717
6718   // See if we are selecting two values based on a comparison of the two values.
6719   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6720     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6721       // Transform (X == Y) ? X : Y  -> Y
6722       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6723         return ReplaceInstUsesWith(SI, FalseVal);
6724       // Transform (X != Y) ? X : Y  -> X
6725       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6726         return ReplaceInstUsesWith(SI, TrueVal);
6727       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6728
6729     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6730       // Transform (X == Y) ? Y : X  -> X
6731       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6732         return ReplaceInstUsesWith(SI, FalseVal);
6733       // Transform (X != Y) ? Y : X  -> Y
6734       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6735         return ReplaceInstUsesWith(SI, TrueVal);
6736       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6737     }
6738   }
6739
6740   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6741     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6742       if (TI->hasOneUse() && FI->hasOneUse()) {
6743         Instruction *AddOp = 0, *SubOp = 0;
6744
6745         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6746         if (TI->getOpcode() == FI->getOpcode())
6747           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6748             return IV;
6749
6750         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6751         // even legal for FP.
6752         if (TI->getOpcode() == Instruction::Sub &&
6753             FI->getOpcode() == Instruction::Add) {
6754           AddOp = FI; SubOp = TI;
6755         } else if (FI->getOpcode() == Instruction::Sub &&
6756                    TI->getOpcode() == Instruction::Add) {
6757           AddOp = TI; SubOp = FI;
6758         }
6759
6760         if (AddOp) {
6761           Value *OtherAddOp = 0;
6762           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6763             OtherAddOp = AddOp->getOperand(1);
6764           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6765             OtherAddOp = AddOp->getOperand(0);
6766           }
6767
6768           if (OtherAddOp) {
6769             // So at this point we know we have (Y -> OtherAddOp):
6770             //        select C, (add X, Y), (sub X, Z)
6771             Value *NegVal;  // Compute -Z
6772             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6773               NegVal = ConstantExpr::getNeg(C);
6774             } else {
6775               NegVal = InsertNewInstBefore(
6776                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6777             }
6778
6779             Value *NewTrueOp = OtherAddOp;
6780             Value *NewFalseOp = NegVal;
6781             if (AddOp != TI)
6782               std::swap(NewTrueOp, NewFalseOp);
6783             Instruction *NewSel =
6784               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6785
6786             NewSel = InsertNewInstBefore(NewSel, SI);
6787             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6788           }
6789         }
6790       }
6791
6792   // See if we can fold the select into one of our operands.
6793   if (SI.getType()->isInteger()) {
6794     // See the comment above GetSelectFoldableOperands for a description of the
6795     // transformation we are doing here.
6796     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6797       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6798           !isa<Constant>(FalseVal))
6799         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6800           unsigned OpToFold = 0;
6801           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6802             OpToFold = 1;
6803           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6804             OpToFold = 2;
6805           }
6806
6807           if (OpToFold) {
6808             Constant *C = GetSelectFoldableConstant(TVI);
6809             std::string Name = TVI->getName(); TVI->setName("");
6810             Instruction *NewSel =
6811               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6812                              Name);
6813             InsertNewInstBefore(NewSel, SI);
6814             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6815               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6816             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6817               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6818             else {
6819               assert(0 && "Unknown instruction!!");
6820             }
6821           }
6822         }
6823
6824     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6825       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6826           !isa<Constant>(TrueVal))
6827         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6828           unsigned OpToFold = 0;
6829           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6830             OpToFold = 1;
6831           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6832             OpToFold = 2;
6833           }
6834
6835           if (OpToFold) {
6836             Constant *C = GetSelectFoldableConstant(FVI);
6837             std::string Name = FVI->getName(); FVI->setName("");
6838             Instruction *NewSel =
6839               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6840                              Name);
6841             InsertNewInstBefore(NewSel, SI);
6842             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6843               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6844             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6845               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6846             else {
6847               assert(0 && "Unknown instruction!!");
6848             }
6849           }
6850         }
6851   }
6852
6853   if (BinaryOperator::isNot(CondVal)) {
6854     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6855     SI.setOperand(1, FalseVal);
6856     SI.setOperand(2, TrueVal);
6857     return &SI;
6858   }
6859
6860   return 0;
6861 }
6862
6863 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6864 /// determine, return it, otherwise return 0.
6865 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6866   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6867     unsigned Align = GV->getAlignment();
6868     if (Align == 0 && TD) 
6869       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6870     return Align;
6871   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6872     unsigned Align = AI->getAlignment();
6873     if (Align == 0 && TD) {
6874       if (isa<AllocaInst>(AI))
6875         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6876       else if (isa<MallocInst>(AI)) {
6877         // Malloc returns maximally aligned memory.
6878         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6879         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6880         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6881       }
6882     }
6883     return Align;
6884   } else if (isa<BitCastInst>(V) ||
6885              (isa<ConstantExpr>(V) && 
6886               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6887     User *CI = cast<User>(V);
6888     if (isa<PointerType>(CI->getOperand(0)->getType()))
6889       return GetKnownAlignment(CI->getOperand(0), TD);
6890     return 0;
6891   } else if (isa<GetElementPtrInst>(V) ||
6892              (isa<ConstantExpr>(V) && 
6893               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6894     User *GEPI = cast<User>(V);
6895     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6896     if (BaseAlignment == 0) return 0;
6897     
6898     // If all indexes are zero, it is just the alignment of the base pointer.
6899     bool AllZeroOperands = true;
6900     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6901       if (!isa<Constant>(GEPI->getOperand(i)) ||
6902           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6903         AllZeroOperands = false;
6904         break;
6905       }
6906     if (AllZeroOperands)
6907       return BaseAlignment;
6908     
6909     // Otherwise, if the base alignment is >= the alignment we expect for the
6910     // base pointer type, then we know that the resultant pointer is aligned at
6911     // least as much as its type requires.
6912     if (!TD) return 0;
6913
6914     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6915     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6916         <= BaseAlignment) {
6917       const Type *GEPTy = GEPI->getType();
6918       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6919     }
6920     return 0;
6921   }
6922   return 0;
6923 }
6924
6925
6926 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6927 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6928 /// the heavy lifting.
6929 ///
6930 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6931   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6932   if (!II) return visitCallSite(&CI);
6933   
6934   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6935   // visitCallSite.
6936   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6937     bool Changed = false;
6938
6939     // memmove/cpy/set of zero bytes is a noop.
6940     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6941       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6942
6943       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6944         if (CI->getZExtValue() == 1) {
6945           // Replace the instruction with just byte operations.  We would
6946           // transform other cases to loads/stores, but we don't know if
6947           // alignment is sufficient.
6948         }
6949     }
6950
6951     // If we have a memmove and the source operation is a constant global,
6952     // then the source and dest pointers can't alias, so we can change this
6953     // into a call to memcpy.
6954     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6955       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6956         if (GVSrc->isConstant()) {
6957           Module *M = CI.getParent()->getParent()->getParent();
6958           const char *Name;
6959           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6960               Type::Int32Ty)
6961             Name = "llvm.memcpy.i32";
6962           else
6963             Name = "llvm.memcpy.i64";
6964           Function *MemCpy = M->getOrInsertFunction(Name,
6965                                      CI.getCalledFunction()->getFunctionType());
6966           CI.setOperand(0, MemCpy);
6967           Changed = true;
6968         }
6969     }
6970
6971     // If we can determine a pointer alignment that is bigger than currently
6972     // set, update the alignment.
6973     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6974       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6975       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6976       unsigned Align = std::min(Alignment1, Alignment2);
6977       if (MI->getAlignment()->getZExtValue() < Align) {
6978         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
6979         Changed = true;
6980       }
6981     } else if (isa<MemSetInst>(MI)) {
6982       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6983       if (MI->getAlignment()->getZExtValue() < Alignment) {
6984         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
6985         Changed = true;
6986       }
6987     }
6988           
6989     if (Changed) return II;
6990   } else {
6991     switch (II->getIntrinsicID()) {
6992     default: break;
6993     case Intrinsic::ppc_altivec_lvx:
6994     case Intrinsic::ppc_altivec_lvxl:
6995     case Intrinsic::x86_sse_loadu_ps:
6996     case Intrinsic::x86_sse2_loadu_pd:
6997     case Intrinsic::x86_sse2_loadu_dq:
6998       // Turn PPC lvx     -> load if the pointer is known aligned.
6999       // Turn X86 loadups -> load if the pointer is known aligned.
7000       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7001         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7002                                       PointerType::get(II->getType()), CI);
7003         return new LoadInst(Ptr);
7004       }
7005       break;
7006     case Intrinsic::ppc_altivec_stvx:
7007     case Intrinsic::ppc_altivec_stvxl:
7008       // Turn stvx -> store if the pointer is known aligned.
7009       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7010         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7011         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7012                                       OpPtrTy, CI);
7013         return new StoreInst(II->getOperand(1), Ptr);
7014       }
7015       break;
7016     case Intrinsic::x86_sse_storeu_ps:
7017     case Intrinsic::x86_sse2_storeu_pd:
7018     case Intrinsic::x86_sse2_storeu_dq:
7019     case Intrinsic::x86_sse2_storel_dq:
7020       // Turn X86 storeu -> store if the pointer is known aligned.
7021       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7022         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7023         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7024                                       OpPtrTy, CI);
7025         return new StoreInst(II->getOperand(2), Ptr);
7026       }
7027       break;
7028       
7029     case Intrinsic::x86_sse_cvttss2si: {
7030       // These intrinsics only demands the 0th element of its input vector.  If
7031       // we can simplify the input based on that, do so now.
7032       uint64_t UndefElts;
7033       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7034                                                 UndefElts)) {
7035         II->setOperand(1, V);
7036         return II;
7037       }
7038       break;
7039     }
7040       
7041     case Intrinsic::ppc_altivec_vperm:
7042       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7043       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7044         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7045         
7046         // Check that all of the elements are integer constants or undefs.
7047         bool AllEltsOk = true;
7048         for (unsigned i = 0; i != 16; ++i) {
7049           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7050               !isa<UndefValue>(Mask->getOperand(i))) {
7051             AllEltsOk = false;
7052             break;
7053           }
7054         }
7055         
7056         if (AllEltsOk) {
7057           // Cast the input vectors to byte vectors.
7058           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7059                                         II->getOperand(1), Mask->getType(), CI);
7060           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7061                                         II->getOperand(2), Mask->getType(), CI);
7062           Value *Result = UndefValue::get(Op0->getType());
7063           
7064           // Only extract each element once.
7065           Value *ExtractedElts[32];
7066           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7067           
7068           for (unsigned i = 0; i != 16; ++i) {
7069             if (isa<UndefValue>(Mask->getOperand(i)))
7070               continue;
7071             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7072             Idx &= 31;  // Match the hardware behavior.
7073             
7074             if (ExtractedElts[Idx] == 0) {
7075               Instruction *Elt = 
7076                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7077               InsertNewInstBefore(Elt, CI);
7078               ExtractedElts[Idx] = Elt;
7079             }
7080           
7081             // Insert this value into the result vector.
7082             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7083             InsertNewInstBefore(cast<Instruction>(Result), CI);
7084           }
7085           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7086         }
7087       }
7088       break;
7089
7090     case Intrinsic::stackrestore: {
7091       // If the save is right next to the restore, remove the restore.  This can
7092       // happen when variable allocas are DCE'd.
7093       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7094         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7095           BasicBlock::iterator BI = SS;
7096           if (&*++BI == II)
7097             return EraseInstFromFunction(CI);
7098         }
7099       }
7100       
7101       // If the stack restore is in a return/unwind block and if there are no
7102       // allocas or calls between the restore and the return, nuke the restore.
7103       TerminatorInst *TI = II->getParent()->getTerminator();
7104       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7105         BasicBlock::iterator BI = II;
7106         bool CannotRemove = false;
7107         for (++BI; &*BI != TI; ++BI) {
7108           if (isa<AllocaInst>(BI) ||
7109               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7110             CannotRemove = true;
7111             break;
7112           }
7113         }
7114         if (!CannotRemove)
7115           return EraseInstFromFunction(CI);
7116       }
7117       break;
7118     }
7119     }
7120   }
7121
7122   return visitCallSite(II);
7123 }
7124
7125 // InvokeInst simplification
7126 //
7127 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7128   return visitCallSite(&II);
7129 }
7130
7131 // visitCallSite - Improvements for call and invoke instructions.
7132 //
7133 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7134   bool Changed = false;
7135
7136   // If the callee is a constexpr cast of a function, attempt to move the cast
7137   // to the arguments of the call/invoke.
7138   if (transformConstExprCastCall(CS)) return 0;
7139
7140   Value *Callee = CS.getCalledValue();
7141
7142   if (Function *CalleeF = dyn_cast<Function>(Callee))
7143     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7144       Instruction *OldCall = CS.getInstruction();
7145       // If the call and callee calling conventions don't match, this call must
7146       // be unreachable, as the call is undefined.
7147       new StoreInst(ConstantBool::getTrue(),
7148                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7149       if (!OldCall->use_empty())
7150         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7151       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7152         return EraseInstFromFunction(*OldCall);
7153       return 0;
7154     }
7155
7156   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7157     // This instruction is not reachable, just remove it.  We insert a store to
7158     // undef so that we know that this code is not reachable, despite the fact
7159     // that we can't modify the CFG here.
7160     new StoreInst(ConstantBool::getTrue(),
7161                   UndefValue::get(PointerType::get(Type::BoolTy)),
7162                   CS.getInstruction());
7163
7164     if (!CS.getInstruction()->use_empty())
7165       CS.getInstruction()->
7166         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7167
7168     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7169       // Don't break the CFG, insert a dummy cond branch.
7170       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7171                      ConstantBool::getTrue(), II);
7172     }
7173     return EraseInstFromFunction(*CS.getInstruction());
7174   }
7175
7176   const PointerType *PTy = cast<PointerType>(Callee->getType());
7177   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7178   if (FTy->isVarArg()) {
7179     // See if we can optimize any arguments passed through the varargs area of
7180     // the call.
7181     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7182            E = CS.arg_end(); I != E; ++I)
7183       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7184         // If this cast does not effect the value passed through the varargs
7185         // area, we can eliminate the use of the cast.
7186         Value *Op = CI->getOperand(0);
7187         if (CI->isLosslessCast()) {
7188           *I = Op;
7189           Changed = true;
7190         }
7191       }
7192   }
7193
7194   return Changed ? CS.getInstruction() : 0;
7195 }
7196
7197 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7198 // attempt to move the cast to the arguments of the call/invoke.
7199 //
7200 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7201   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7202   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7203   if (CE->getOpcode() != Instruction::BitCast || 
7204       !isa<Function>(CE->getOperand(0)))
7205     return false;
7206   Function *Callee = cast<Function>(CE->getOperand(0));
7207   Instruction *Caller = CS.getInstruction();
7208
7209   // Okay, this is a cast from a function to a different type.  Unless doing so
7210   // would cause a type conversion of one of our arguments, change this call to
7211   // be a direct call with arguments casted to the appropriate types.
7212   //
7213   const FunctionType *FT = Callee->getFunctionType();
7214   const Type *OldRetTy = Caller->getType();
7215
7216   // Check to see if we are changing the return type...
7217   if (OldRetTy != FT->getReturnType()) {
7218     if (Callee->isExternal() &&
7219         !Caller->use_empty() && 
7220         !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
7221           (isa<PointerType>(FT->getReturnType()) && 
7222            TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7223         )
7224       return false;   // Cannot transform this return value...
7225
7226     // If the callsite is an invoke instruction, and the return value is used by
7227     // a PHI node in a successor, we cannot change the return type of the call
7228     // because there is no place to put the cast instruction (without breaking
7229     // the critical edge).  Bail out in this case.
7230     if (!Caller->use_empty())
7231       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7232         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7233              UI != E; ++UI)
7234           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7235             if (PN->getParent() == II->getNormalDest() ||
7236                 PN->getParent() == II->getUnwindDest())
7237               return false;
7238   }
7239
7240   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7241   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7242
7243   CallSite::arg_iterator AI = CS.arg_begin();
7244   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7245     const Type *ParamTy = FT->getParamType(i);
7246     const Type *ActTy = (*AI)->getType();
7247     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7248     //Either we can cast directly, or we can upconvert the argument
7249     bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
7250       (ParamTy->isIntegral() && ActTy->isIntegral() &&
7251        ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7252       (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
7253        c->getSExtValue() > 0);
7254     if (Callee->isExternal() && !isConvertible) return false;
7255   }
7256
7257   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7258       Callee->isExternal())
7259     return false;   // Do not delete arguments unless we have a function body...
7260
7261   // Okay, we decided that this is a safe thing to do: go ahead and start
7262   // inserting cast instructions as necessary...
7263   std::vector<Value*> Args;
7264   Args.reserve(NumActualArgs);
7265
7266   AI = CS.arg_begin();
7267   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7268     const Type *ParamTy = FT->getParamType(i);
7269     if ((*AI)->getType() == ParamTy) {
7270       Args.push_back(*AI);
7271     } else {
7272       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7273           false, ParamTy, false);
7274       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7275       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7276     }
7277   }
7278
7279   // If the function takes more arguments than the call was taking, add them
7280   // now...
7281   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7282     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7283
7284   // If we are removing arguments to the function, emit an obnoxious warning...
7285   if (FT->getNumParams() < NumActualArgs)
7286     if (!FT->isVarArg()) {
7287       cerr << "WARNING: While resolving call to function '"
7288            << Callee->getName() << "' arguments were dropped!\n";
7289     } else {
7290       // Add all of the arguments in their promoted form to the arg list...
7291       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7292         const Type *PTy = getPromotedType((*AI)->getType());
7293         if (PTy != (*AI)->getType()) {
7294           // Must promote to pass through va_arg area!
7295           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7296                                                                 PTy, false);
7297           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7298           InsertNewInstBefore(Cast, *Caller);
7299           Args.push_back(Cast);
7300         } else {
7301           Args.push_back(*AI);
7302         }
7303       }
7304     }
7305
7306   if (FT->getReturnType() == Type::VoidTy)
7307     Caller->setName("");   // Void type should not have a name...
7308
7309   Instruction *NC;
7310   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7311     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7312                         Args, Caller->getName(), Caller);
7313     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7314   } else {
7315     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7316     if (cast<CallInst>(Caller)->isTailCall())
7317       cast<CallInst>(NC)->setTailCall();
7318    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7319   }
7320
7321   // Insert a cast of the return type as necessary...
7322   Value *NV = NC;
7323   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7324     if (NV->getType() != Type::VoidTy) {
7325       const Type *CallerTy = Caller->getType();
7326       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7327                                                             CallerTy, false);
7328       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7329
7330       // If this is an invoke instruction, we should insert it after the first
7331       // non-phi, instruction in the normal successor block.
7332       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7333         BasicBlock::iterator I = II->getNormalDest()->begin();
7334         while (isa<PHINode>(I)) ++I;
7335         InsertNewInstBefore(NC, *I);
7336       } else {
7337         // Otherwise, it's a call, just insert cast right after the call instr
7338         InsertNewInstBefore(NC, *Caller);
7339       }
7340       AddUsersToWorkList(*Caller);
7341     } else {
7342       NV = UndefValue::get(Caller->getType());
7343     }
7344   }
7345
7346   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7347     Caller->replaceAllUsesWith(NV);
7348   Caller->getParent()->getInstList().erase(Caller);
7349   removeFromWorkList(Caller);
7350   return true;
7351 }
7352
7353 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7354 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7355 /// and a single binop.
7356 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7357   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7358   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7359          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7360   unsigned Opc = FirstInst->getOpcode();
7361   Value *LHSVal = FirstInst->getOperand(0);
7362   Value *RHSVal = FirstInst->getOperand(1);
7363     
7364   const Type *LHSType = LHSVal->getType();
7365   const Type *RHSType = RHSVal->getType();
7366   
7367   // Scan to see if all operands are the same opcode, all have one use, and all
7368   // kill their operands (i.e. the operands have one use).
7369   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7370     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7371     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7372         // Verify type of the LHS matches so we don't fold cmp's of different
7373         // types or GEP's with different index types.
7374         I->getOperand(0)->getType() != LHSType ||
7375         I->getOperand(1)->getType() != RHSType)
7376       return 0;
7377
7378     // If they are CmpInst instructions, check their predicates
7379     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7380       if (cast<CmpInst>(I)->getPredicate() !=
7381           cast<CmpInst>(FirstInst)->getPredicate())
7382         return 0;
7383     
7384     // Keep track of which operand needs a phi node.
7385     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7386     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7387   }
7388   
7389   // Otherwise, this is safe to transform, determine if it is profitable.
7390
7391   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7392   // Indexes are often folded into load/store instructions, so we don't want to
7393   // hide them behind a phi.
7394   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7395     return 0;
7396   
7397   Value *InLHS = FirstInst->getOperand(0);
7398   Value *InRHS = FirstInst->getOperand(1);
7399   PHINode *NewLHS = 0, *NewRHS = 0;
7400   if (LHSVal == 0) {
7401     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7402     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7403     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7404     InsertNewInstBefore(NewLHS, PN);
7405     LHSVal = NewLHS;
7406   }
7407   
7408   if (RHSVal == 0) {
7409     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7410     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7411     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7412     InsertNewInstBefore(NewRHS, PN);
7413     RHSVal = NewRHS;
7414   }
7415   
7416   // Add all operands to the new PHIs.
7417   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7418     if (NewLHS) {
7419       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7420       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7421     }
7422     if (NewRHS) {
7423       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7424       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7425     }
7426   }
7427     
7428   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7429     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7430   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7431     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7432                            RHSVal);
7433   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7434     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7435   else {
7436     assert(isa<GetElementPtrInst>(FirstInst));
7437     return new GetElementPtrInst(LHSVal, RHSVal);
7438   }
7439 }
7440
7441 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7442 /// of the block that defines it.  This means that it must be obvious the value
7443 /// of the load is not changed from the point of the load to the end of the
7444 /// block it is in.
7445 static bool isSafeToSinkLoad(LoadInst *L) {
7446   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7447   
7448   for (++BBI; BBI != E; ++BBI)
7449     if (BBI->mayWriteToMemory())
7450       return false;
7451   return true;
7452 }
7453
7454
7455 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7456 // operator and they all are only used by the PHI, PHI together their
7457 // inputs, and do the operation once, to the result of the PHI.
7458 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7459   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7460
7461   // Scan the instruction, looking for input operations that can be folded away.
7462   // If all input operands to the phi are the same instruction (e.g. a cast from
7463   // the same type or "+42") we can pull the operation through the PHI, reducing
7464   // code size and simplifying code.
7465   Constant *ConstantOp = 0;
7466   const Type *CastSrcTy = 0;
7467   bool isVolatile = false;
7468   if (isa<CastInst>(FirstInst)) {
7469     CastSrcTy = FirstInst->getOperand(0)->getType();
7470   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7471              isa<CmpInst>(FirstInst)) {
7472     // Can fold binop, compare or shift here if the RHS is a constant, 
7473     // otherwise call FoldPHIArgBinOpIntoPHI.
7474     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7475     if (ConstantOp == 0)
7476       return FoldPHIArgBinOpIntoPHI(PN);
7477   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7478     isVolatile = LI->isVolatile();
7479     // We can't sink the load if the loaded value could be modified between the
7480     // load and the PHI.
7481     if (LI->getParent() != PN.getIncomingBlock(0) ||
7482         !isSafeToSinkLoad(LI))
7483       return 0;
7484   } else if (isa<GetElementPtrInst>(FirstInst)) {
7485     if (FirstInst->getNumOperands() == 2)
7486       return FoldPHIArgBinOpIntoPHI(PN);
7487     // Can't handle general GEPs yet.
7488     return 0;
7489   } else {
7490     return 0;  // Cannot fold this operation.
7491   }
7492
7493   // Check to see if all arguments are the same operation.
7494   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7495     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7496     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7497     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7498       return 0;
7499     if (CastSrcTy) {
7500       if (I->getOperand(0)->getType() != CastSrcTy)
7501         return 0;  // Cast operation must match.
7502     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7503       // We can't sink the load if the loaded value could be modified between 
7504       // the load and the PHI.
7505       if (LI->isVolatile() != isVolatile ||
7506           LI->getParent() != PN.getIncomingBlock(i) ||
7507           !isSafeToSinkLoad(LI))
7508         return 0;
7509     } else if (I->getOperand(1) != ConstantOp) {
7510       return 0;
7511     }
7512   }
7513
7514   // Okay, they are all the same operation.  Create a new PHI node of the
7515   // correct type, and PHI together all of the LHS's of the instructions.
7516   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7517                                PN.getName()+".in");
7518   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7519
7520   Value *InVal = FirstInst->getOperand(0);
7521   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7522
7523   // Add all operands to the new PHI.
7524   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7525     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7526     if (NewInVal != InVal)
7527       InVal = 0;
7528     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7529   }
7530
7531   Value *PhiVal;
7532   if (InVal) {
7533     // The new PHI unions all of the same values together.  This is really
7534     // common, so we handle it intelligently here for compile-time speed.
7535     PhiVal = InVal;
7536     delete NewPN;
7537   } else {
7538     InsertNewInstBefore(NewPN, PN);
7539     PhiVal = NewPN;
7540   }
7541
7542   // Insert and return the new operation.
7543   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7544     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7545   else if (isa<LoadInst>(FirstInst))
7546     return new LoadInst(PhiVal, "", isVolatile);
7547   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7548     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7549   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7550     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7551                            PhiVal, ConstantOp);
7552   else
7553     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7554                          PhiVal, ConstantOp);
7555 }
7556
7557 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7558 /// that is dead.
7559 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7560   if (PN->use_empty()) return true;
7561   if (!PN->hasOneUse()) return false;
7562
7563   // Remember this node, and if we find the cycle, return.
7564   if (!PotentiallyDeadPHIs.insert(PN).second)
7565     return true;
7566
7567   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7568     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7569
7570   return false;
7571 }
7572
7573 // PHINode simplification
7574 //
7575 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7576   // If LCSSA is around, don't mess with Phi nodes
7577   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7578   
7579   if (Value *V = PN.hasConstantValue())
7580     return ReplaceInstUsesWith(PN, V);
7581
7582   // If all PHI operands are the same operation, pull them through the PHI,
7583   // reducing code size.
7584   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7585       PN.getIncomingValue(0)->hasOneUse())
7586     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7587       return Result;
7588
7589   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7590   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7591   // PHI)... break the cycle.
7592   if (PN.hasOneUse())
7593     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7594       std::set<PHINode*> PotentiallyDeadPHIs;
7595       PotentiallyDeadPHIs.insert(&PN);
7596       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7597         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7598     }
7599
7600   return 0;
7601 }
7602
7603 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7604                                    Instruction *InsertPoint,
7605                                    InstCombiner *IC) {
7606   unsigned PtrSize = DTy->getPrimitiveSize();
7607   unsigned VTySize = V->getType()->getPrimitiveSize();
7608   // We must cast correctly to the pointer type. Ensure that we
7609   // sign extend the integer value if it is smaller as this is
7610   // used for address computation.
7611   Instruction::CastOps opcode = 
7612      (VTySize < PtrSize ? Instruction::SExt :
7613       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7614   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7615 }
7616
7617
7618 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7619   Value *PtrOp = GEP.getOperand(0);
7620   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7621   // If so, eliminate the noop.
7622   if (GEP.getNumOperands() == 1)
7623     return ReplaceInstUsesWith(GEP, PtrOp);
7624
7625   if (isa<UndefValue>(GEP.getOperand(0)))
7626     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7627
7628   bool HasZeroPointerIndex = false;
7629   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7630     HasZeroPointerIndex = C->isNullValue();
7631
7632   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7633     return ReplaceInstUsesWith(GEP, PtrOp);
7634
7635   // Eliminate unneeded casts for indices.
7636   bool MadeChange = false;
7637   gep_type_iterator GTI = gep_type_begin(GEP);
7638   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7639     if (isa<SequentialType>(*GTI)) {
7640       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7641         Value *Src = CI->getOperand(0);
7642         const Type *SrcTy = Src->getType();
7643         const Type *DestTy = CI->getType();
7644         if (Src->getType()->isInteger()) {
7645           if (SrcTy->getPrimitiveSizeInBits() ==
7646                        DestTy->getPrimitiveSizeInBits()) {
7647             // We can always eliminate a cast from ulong or long to the other.
7648             // We can always eliminate a cast from uint to int or the other on
7649             // 32-bit pointer platforms.
7650             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7651               MadeChange = true;
7652               GEP.setOperand(i, Src);
7653             }
7654           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7655                      SrcTy->getPrimitiveSize() == 4) {
7656             // We can eliminate a cast from [u]int to [u]long iff the target 
7657             // is a 32-bit pointer target.
7658             if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7659               MadeChange = true;
7660               GEP.setOperand(i, Src);
7661             }
7662           }
7663         }
7664       }
7665       // If we are using a wider index than needed for this platform, shrink it
7666       // to what we need.  If the incoming value needs a cast instruction,
7667       // insert it.  This explicit cast can make subsequent optimizations more
7668       // obvious.
7669       Value *Op = GEP.getOperand(i);
7670       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7671         if (Constant *C = dyn_cast<Constant>(Op)) {
7672           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7673           MadeChange = true;
7674         } else {
7675           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7676                                 GEP);
7677           GEP.setOperand(i, Op);
7678           MadeChange = true;
7679         }
7680     }
7681   if (MadeChange) return &GEP;
7682
7683   // Combine Indices - If the source pointer to this getelementptr instruction
7684   // is a getelementptr instruction, combine the indices of the two
7685   // getelementptr instructions into a single instruction.
7686   //
7687   std::vector<Value*> SrcGEPOperands;
7688   if (User *Src = dyn_castGetElementPtr(PtrOp))
7689     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7690
7691   if (!SrcGEPOperands.empty()) {
7692     // Note that if our source is a gep chain itself that we wait for that
7693     // chain to be resolved before we perform this transformation.  This
7694     // avoids us creating a TON of code in some cases.
7695     //
7696     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7697         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7698       return 0;   // Wait until our source is folded to completion.
7699
7700     std::vector<Value *> Indices;
7701
7702     // Find out whether the last index in the source GEP is a sequential idx.
7703     bool EndsWithSequential = false;
7704     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7705            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7706       EndsWithSequential = !isa<StructType>(*I);
7707
7708     // Can we combine the two pointer arithmetics offsets?
7709     if (EndsWithSequential) {
7710       // Replace: gep (gep %P, long B), long A, ...
7711       // With:    T = long A+B; gep %P, T, ...
7712       //
7713       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7714       if (SO1 == Constant::getNullValue(SO1->getType())) {
7715         Sum = GO1;
7716       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7717         Sum = SO1;
7718       } else {
7719         // If they aren't the same type, convert both to an integer of the
7720         // target's pointer size.
7721         if (SO1->getType() != GO1->getType()) {
7722           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7723             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7724           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7725             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7726           } else {
7727             unsigned PS = TD->getPointerSize();
7728             if (SO1->getType()->getPrimitiveSize() == PS) {
7729               // Convert GO1 to SO1's type.
7730               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7731
7732             } else if (GO1->getType()->getPrimitiveSize() == PS) {
7733               // Convert SO1 to GO1's type.
7734               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7735             } else {
7736               const Type *PT = TD->getIntPtrType();
7737               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7738               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7739             }
7740           }
7741         }
7742         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7743           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7744         else {
7745           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7746           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7747         }
7748       }
7749
7750       // Recycle the GEP we already have if possible.
7751       if (SrcGEPOperands.size() == 2) {
7752         GEP.setOperand(0, SrcGEPOperands[0]);
7753         GEP.setOperand(1, Sum);
7754         return &GEP;
7755       } else {
7756         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7757                        SrcGEPOperands.end()-1);
7758         Indices.push_back(Sum);
7759         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7760       }
7761     } else if (isa<Constant>(*GEP.idx_begin()) &&
7762                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7763                SrcGEPOperands.size() != 1) {
7764       // Otherwise we can do the fold if the first index of the GEP is a zero
7765       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7766                      SrcGEPOperands.end());
7767       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7768     }
7769
7770     if (!Indices.empty())
7771       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7772
7773   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7774     // GEP of global variable.  If all of the indices for this GEP are
7775     // constants, we can promote this to a constexpr instead of an instruction.
7776
7777     // Scan for nonconstants...
7778     std::vector<Constant*> Indices;
7779     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7780     for (; I != E && isa<Constant>(*I); ++I)
7781       Indices.push_back(cast<Constant>(*I));
7782
7783     if (I == E) {  // If they are all constants...
7784       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7785
7786       // Replace all uses of the GEP with the new constexpr...
7787       return ReplaceInstUsesWith(GEP, CE);
7788     }
7789   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7790     if (!isa<PointerType>(X->getType())) {
7791       // Not interesting.  Source pointer must be a cast from pointer.
7792     } else if (HasZeroPointerIndex) {
7793       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7794       // into     : GEP [10 x ubyte]* X, long 0, ...
7795       //
7796       // This occurs when the program declares an array extern like "int X[];"
7797       //
7798       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7799       const PointerType *XTy = cast<PointerType>(X->getType());
7800       if (const ArrayType *XATy =
7801           dyn_cast<ArrayType>(XTy->getElementType()))
7802         if (const ArrayType *CATy =
7803             dyn_cast<ArrayType>(CPTy->getElementType()))
7804           if (CATy->getElementType() == XATy->getElementType()) {
7805             // At this point, we know that the cast source type is a pointer
7806             // to an array of the same type as the destination pointer
7807             // array.  Because the array type is never stepped over (there
7808             // is a leading zero) we can fold the cast into this GEP.
7809             GEP.setOperand(0, X);
7810             return &GEP;
7811           }
7812     } else if (GEP.getNumOperands() == 2) {
7813       // Transform things like:
7814       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7815       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7816       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7817       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7818       if (isa<ArrayType>(SrcElTy) &&
7819           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7820           TD->getTypeSize(ResElTy)) {
7821         Value *V = InsertNewInstBefore(
7822                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7823                                      GEP.getOperand(1), GEP.getName()), GEP);
7824         // V and GEP are both pointer types --> BitCast
7825         return new BitCastInst(V, GEP.getType());
7826       }
7827       
7828       // Transform things like:
7829       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7830       //   (where tmp = 8*tmp2) into:
7831       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7832       
7833       if (isa<ArrayType>(SrcElTy) &&
7834           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7835         uint64_t ArrayEltSize =
7836             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7837         
7838         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7839         // allow either a mul, shift, or constant here.
7840         Value *NewIdx = 0;
7841         ConstantInt *Scale = 0;
7842         if (ArrayEltSize == 1) {
7843           NewIdx = GEP.getOperand(1);
7844           Scale = ConstantInt::get(NewIdx->getType(), 1);
7845         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7846           NewIdx = ConstantInt::get(CI->getType(), 1);
7847           Scale = CI;
7848         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7849           if (Inst->getOpcode() == Instruction::Shl &&
7850               isa<ConstantInt>(Inst->getOperand(1))) {
7851             unsigned ShAmt =
7852               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7853             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7854             NewIdx = Inst->getOperand(0);
7855           } else if (Inst->getOpcode() == Instruction::Mul &&
7856                      isa<ConstantInt>(Inst->getOperand(1))) {
7857             Scale = cast<ConstantInt>(Inst->getOperand(1));
7858             NewIdx = Inst->getOperand(0);
7859           }
7860         }
7861
7862         // If the index will be to exactly the right offset with the scale taken
7863         // out, perform the transformation.
7864         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7865           if (isa<ConstantInt>(Scale))
7866             Scale = ConstantInt::get(Scale->getType(),
7867                                       Scale->getZExtValue() / ArrayEltSize);
7868           if (Scale->getZExtValue() != 1) {
7869             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7870                                                        true /*SExt*/);
7871             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7872             NewIdx = InsertNewInstBefore(Sc, GEP);
7873           }
7874
7875           // Insert the new GEP instruction.
7876           Instruction *NewGEP =
7877             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7878                                   NewIdx, GEP.getName());
7879           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7880           // The NewGEP must be pointer typed, so must the old one -> BitCast
7881           return new BitCastInst(NewGEP, GEP.getType());
7882         }
7883       }
7884     }
7885   }
7886
7887   return 0;
7888 }
7889
7890 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7891   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7892   if (AI.isArrayAllocation())    // Check C != 1
7893     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7894       const Type *NewTy = 
7895         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7896       AllocationInst *New = 0;
7897
7898       // Create and insert the replacement instruction...
7899       if (isa<MallocInst>(AI))
7900         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7901       else {
7902         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7903         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7904       }
7905
7906       InsertNewInstBefore(New, AI);
7907
7908       // Scan to the end of the allocation instructions, to skip over a block of
7909       // allocas if possible...
7910       //
7911       BasicBlock::iterator It = New;
7912       while (isa<AllocationInst>(*It)) ++It;
7913
7914       // Now that I is pointing to the first non-allocation-inst in the block,
7915       // insert our getelementptr instruction...
7916       //
7917       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7918       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7919                                        New->getName()+".sub", It);
7920
7921       // Now make everything use the getelementptr instead of the original
7922       // allocation.
7923       return ReplaceInstUsesWith(AI, V);
7924     } else if (isa<UndefValue>(AI.getArraySize())) {
7925       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7926     }
7927
7928   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7929   // Note that we only do this for alloca's, because malloc should allocate and
7930   // return a unique pointer, even for a zero byte allocation.
7931   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7932       TD->getTypeSize(AI.getAllocatedType()) == 0)
7933     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7934
7935   return 0;
7936 }
7937
7938 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7939   Value *Op = FI.getOperand(0);
7940
7941   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7942   if (CastInst *CI = dyn_cast<CastInst>(Op))
7943     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7944       FI.setOperand(0, CI->getOperand(0));
7945       return &FI;
7946     }
7947
7948   // free undef -> unreachable.
7949   if (isa<UndefValue>(Op)) {
7950     // Insert a new store to null because we cannot modify the CFG here.
7951     new StoreInst(ConstantBool::getTrue(),
7952                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7953     return EraseInstFromFunction(FI);
7954   }
7955
7956   // If we have 'free null' delete the instruction.  This can happen in stl code
7957   // when lots of inlining happens.
7958   if (isa<ConstantPointerNull>(Op))
7959     return EraseInstFromFunction(FI);
7960
7961   return 0;
7962 }
7963
7964
7965 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7966 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7967   User *CI = cast<User>(LI.getOperand(0));
7968   Value *CastOp = CI->getOperand(0);
7969
7970   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7971   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7972     const Type *SrcPTy = SrcTy->getElementType();
7973
7974     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7975         isa<PackedType>(DestPTy)) {
7976       // If the source is an array, the code below will not succeed.  Check to
7977       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7978       // constants.
7979       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7980         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7981           if (ASrcTy->getNumElements() != 0) {
7982             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
7983             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7984             SrcTy = cast<PointerType>(CastOp->getType());
7985             SrcPTy = SrcTy->getElementType();
7986           }
7987
7988       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7989            isa<PackedType>(SrcPTy)) &&
7990           // Do not allow turning this into a load of an integer, which is then
7991           // casted to a pointer, this pessimizes pointer analysis a lot.
7992           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7993           IC.getTargetData().getTypeSize(SrcPTy) ==
7994                IC.getTargetData().getTypeSize(DestPTy)) {
7995
7996         // Okay, we are casting from one integer or pointer type to another of
7997         // the same size.  Instead of casting the pointer before the load, cast
7998         // the result of the loaded value.
7999         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8000                                                              CI->getName(),
8001                                                          LI.isVolatile()),LI);
8002         // Now cast the result of the load.
8003         return new BitCastInst(NewLoad, LI.getType());
8004       }
8005     }
8006   }
8007   return 0;
8008 }
8009
8010 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8011 /// from this value cannot trap.  If it is not obviously safe to load from the
8012 /// specified pointer, we do a quick local scan of the basic block containing
8013 /// ScanFrom, to determine if the address is already accessed.
8014 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8015   // If it is an alloca or global variable, it is always safe to load from.
8016   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8017
8018   // Otherwise, be a little bit agressive by scanning the local block where we
8019   // want to check to see if the pointer is already being loaded or stored
8020   // from/to.  If so, the previous load or store would have already trapped,
8021   // so there is no harm doing an extra load (also, CSE will later eliminate
8022   // the load entirely).
8023   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8024
8025   while (BBI != E) {
8026     --BBI;
8027
8028     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8029       if (LI->getOperand(0) == V) return true;
8030     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8031       if (SI->getOperand(1) == V) return true;
8032
8033   }
8034   return false;
8035 }
8036
8037 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8038   Value *Op = LI.getOperand(0);
8039
8040   // load (cast X) --> cast (load X) iff safe
8041   if (isa<CastInst>(Op))
8042     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8043       return Res;
8044
8045   // None of the following transforms are legal for volatile loads.
8046   if (LI.isVolatile()) return 0;
8047   
8048   if (&LI.getParent()->front() != &LI) {
8049     BasicBlock::iterator BBI = &LI; --BBI;
8050     // If the instruction immediately before this is a store to the same
8051     // address, do a simple form of store->load forwarding.
8052     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8053       if (SI->getOperand(1) == LI.getOperand(0))
8054         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8055     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8056       if (LIB->getOperand(0) == LI.getOperand(0))
8057         return ReplaceInstUsesWith(LI, LIB);
8058   }
8059
8060   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8061     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8062         isa<UndefValue>(GEPI->getOperand(0))) {
8063       // Insert a new store to null instruction before the load to indicate
8064       // that this code is not reachable.  We do this instead of inserting
8065       // an unreachable instruction directly because we cannot modify the
8066       // CFG.
8067       new StoreInst(UndefValue::get(LI.getType()),
8068                     Constant::getNullValue(Op->getType()), &LI);
8069       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8070     }
8071
8072   if (Constant *C = dyn_cast<Constant>(Op)) {
8073     // load null/undef -> undef
8074     if ((C->isNullValue() || isa<UndefValue>(C))) {
8075       // Insert a new store to null instruction before the load to indicate that
8076       // this code is not reachable.  We do this instead of inserting an
8077       // unreachable instruction directly because we cannot modify the CFG.
8078       new StoreInst(UndefValue::get(LI.getType()),
8079                     Constant::getNullValue(Op->getType()), &LI);
8080       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8081     }
8082
8083     // Instcombine load (constant global) into the value loaded.
8084     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8085       if (GV->isConstant() && !GV->isExternal())
8086         return ReplaceInstUsesWith(LI, GV->getInitializer());
8087
8088     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8089     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8090       if (CE->getOpcode() == Instruction::GetElementPtr) {
8091         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8092           if (GV->isConstant() && !GV->isExternal())
8093             if (Constant *V = 
8094                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8095               return ReplaceInstUsesWith(LI, V);
8096         if (CE->getOperand(0)->isNullValue()) {
8097           // Insert a new store to null instruction before the load to indicate
8098           // that this code is not reachable.  We do this instead of inserting
8099           // an unreachable instruction directly because we cannot modify the
8100           // CFG.
8101           new StoreInst(UndefValue::get(LI.getType()),
8102                         Constant::getNullValue(Op->getType()), &LI);
8103           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8104         }
8105
8106       } else if (CE->isCast()) {
8107         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8108           return Res;
8109       }
8110   }
8111
8112   if (Op->hasOneUse()) {
8113     // Change select and PHI nodes to select values instead of addresses: this
8114     // helps alias analysis out a lot, allows many others simplifications, and
8115     // exposes redundancy in the code.
8116     //
8117     // Note that we cannot do the transformation unless we know that the
8118     // introduced loads cannot trap!  Something like this is valid as long as
8119     // the condition is always false: load (select bool %C, int* null, int* %G),
8120     // but it would not be valid if we transformed it to load from null
8121     // unconditionally.
8122     //
8123     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8124       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8125       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8126           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8127         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8128                                      SI->getOperand(1)->getName()+".val"), LI);
8129         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8130                                      SI->getOperand(2)->getName()+".val"), LI);
8131         return new SelectInst(SI->getCondition(), V1, V2);
8132       }
8133
8134       // load (select (cond, null, P)) -> load P
8135       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8136         if (C->isNullValue()) {
8137           LI.setOperand(0, SI->getOperand(2));
8138           return &LI;
8139         }
8140
8141       // load (select (cond, P, null)) -> load P
8142       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8143         if (C->isNullValue()) {
8144           LI.setOperand(0, SI->getOperand(1));
8145           return &LI;
8146         }
8147     }
8148   }
8149   return 0;
8150 }
8151
8152 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8153 /// when possible.
8154 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8155   User *CI = cast<User>(SI.getOperand(1));
8156   Value *CastOp = CI->getOperand(0);
8157
8158   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8159   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8160     const Type *SrcPTy = SrcTy->getElementType();
8161
8162     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8163       // If the source is an array, the code below will not succeed.  Check to
8164       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8165       // constants.
8166       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8167         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8168           if (ASrcTy->getNumElements() != 0) {
8169             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8170             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8171             SrcTy = cast<PointerType>(CastOp->getType());
8172             SrcPTy = SrcTy->getElementType();
8173           }
8174
8175       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8176           IC.getTargetData().getTypeSize(SrcPTy) ==
8177                IC.getTargetData().getTypeSize(DestPTy)) {
8178
8179         // Okay, we are casting from one integer or pointer type to another of
8180         // the same size.  Instead of casting the pointer before the store, cast
8181         // the value to be stored.
8182         Value *NewCast;
8183         Instruction::CastOps opcode = Instruction::BitCast;
8184         Value *SIOp0 = SI.getOperand(0);
8185         if (isa<PointerType>(SrcPTy)) {
8186           if (SIOp0->getType()->isIntegral())
8187             opcode = Instruction::IntToPtr;
8188         } else if (SrcPTy->isIntegral()) {
8189           if (isa<PointerType>(SIOp0->getType()))
8190             opcode = Instruction::PtrToInt;
8191         }
8192         if (Constant *C = dyn_cast<Constant>(SIOp0))
8193           NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
8194         else
8195           NewCast = IC.InsertNewInstBefore(
8196             CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
8197         return new StoreInst(NewCast, CastOp);
8198       }
8199     }
8200   }
8201   return 0;
8202 }
8203
8204 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8205   Value *Val = SI.getOperand(0);
8206   Value *Ptr = SI.getOperand(1);
8207
8208   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8209     EraseInstFromFunction(SI);
8210     ++NumCombined;
8211     return 0;
8212   }
8213
8214   // Do really simple DSE, to catch cases where there are several consequtive
8215   // stores to the same location, separated by a few arithmetic operations. This
8216   // situation often occurs with bitfield accesses.
8217   BasicBlock::iterator BBI = &SI;
8218   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8219        --ScanInsts) {
8220     --BBI;
8221     
8222     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8223       // Prev store isn't volatile, and stores to the same location?
8224       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8225         ++NumDeadStore;
8226         ++BBI;
8227         EraseInstFromFunction(*PrevSI);
8228         continue;
8229       }
8230       break;
8231     }
8232     
8233     // If this is a load, we have to stop.  However, if the loaded value is from
8234     // the pointer we're loading and is producing the pointer we're storing,
8235     // then *this* store is dead (X = load P; store X -> P).
8236     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8237       if (LI == Val && LI->getOperand(0) == Ptr) {
8238         EraseInstFromFunction(SI);
8239         ++NumCombined;
8240         return 0;
8241       }
8242       // Otherwise, this is a load from some other location.  Stores before it
8243       // may not be dead.
8244       break;
8245     }
8246     
8247     // Don't skip over loads or things that can modify memory.
8248     if (BBI->mayWriteToMemory())
8249       break;
8250   }
8251   
8252   
8253   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8254
8255   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8256   if (isa<ConstantPointerNull>(Ptr)) {
8257     if (!isa<UndefValue>(Val)) {
8258       SI.setOperand(0, UndefValue::get(Val->getType()));
8259       if (Instruction *U = dyn_cast<Instruction>(Val))
8260         WorkList.push_back(U);  // Dropped a use.
8261       ++NumCombined;
8262     }
8263     return 0;  // Do not modify these!
8264   }
8265
8266   // store undef, Ptr -> noop
8267   if (isa<UndefValue>(Val)) {
8268     EraseInstFromFunction(SI);
8269     ++NumCombined;
8270     return 0;
8271   }
8272
8273   // If the pointer destination is a cast, see if we can fold the cast into the
8274   // source instead.
8275   if (isa<CastInst>(Ptr))
8276     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8277       return Res;
8278   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8279     if (CE->isCast())
8280       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8281         return Res;
8282
8283   
8284   // If this store is the last instruction in the basic block, and if the block
8285   // ends with an unconditional branch, try to move it to the successor block.
8286   BBI = &SI; ++BBI;
8287   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8288     if (BI->isUnconditional()) {
8289       // Check to see if the successor block has exactly two incoming edges.  If
8290       // so, see if the other predecessor contains a store to the same location.
8291       // if so, insert a PHI node (if needed) and move the stores down.
8292       BasicBlock *Dest = BI->getSuccessor(0);
8293
8294       pred_iterator PI = pred_begin(Dest);
8295       BasicBlock *Other = 0;
8296       if (*PI != BI->getParent())
8297         Other = *PI;
8298       ++PI;
8299       if (PI != pred_end(Dest)) {
8300         if (*PI != BI->getParent())
8301           if (Other)
8302             Other = 0;
8303           else
8304             Other = *PI;
8305         if (++PI != pred_end(Dest))
8306           Other = 0;
8307       }
8308       if (Other) {  // If only one other pred...
8309         BBI = Other->getTerminator();
8310         // Make sure this other block ends in an unconditional branch and that
8311         // there is an instruction before the branch.
8312         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8313             BBI != Other->begin()) {
8314           --BBI;
8315           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8316           
8317           // If this instruction is a store to the same location.
8318           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8319             // Okay, we know we can perform this transformation.  Insert a PHI
8320             // node now if we need it.
8321             Value *MergedVal = OtherStore->getOperand(0);
8322             if (MergedVal != SI.getOperand(0)) {
8323               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8324               PN->reserveOperandSpace(2);
8325               PN->addIncoming(SI.getOperand(0), SI.getParent());
8326               PN->addIncoming(OtherStore->getOperand(0), Other);
8327               MergedVal = InsertNewInstBefore(PN, Dest->front());
8328             }
8329             
8330             // Advance to a place where it is safe to insert the new store and
8331             // insert it.
8332             BBI = Dest->begin();
8333             while (isa<PHINode>(BBI)) ++BBI;
8334             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8335                                               OtherStore->isVolatile()), *BBI);
8336
8337             // Nuke the old stores.
8338             EraseInstFromFunction(SI);
8339             EraseInstFromFunction(*OtherStore);
8340             ++NumCombined;
8341             return 0;
8342           }
8343         }
8344       }
8345     }
8346   
8347   return 0;
8348 }
8349
8350
8351 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8352   // Change br (not X), label True, label False to: br X, label False, True
8353   Value *X = 0;
8354   BasicBlock *TrueDest;
8355   BasicBlock *FalseDest;
8356   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8357       !isa<Constant>(X)) {
8358     // Swap Destinations and condition...
8359     BI.setCondition(X);
8360     BI.setSuccessor(0, FalseDest);
8361     BI.setSuccessor(1, TrueDest);
8362     return &BI;
8363   }
8364
8365   // Cannonicalize fcmp_one -> fcmp_oeq
8366   FCmpInst::Predicate FPred; Value *Y;
8367   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8368                              TrueDest, FalseDest)))
8369     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8370          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8371       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8372       std::string Name = I->getName(); I->setName("");
8373       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8374       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8375       // Swap Destinations and condition...
8376       BI.setCondition(NewSCC);
8377       BI.setSuccessor(0, FalseDest);
8378       BI.setSuccessor(1, TrueDest);
8379       removeFromWorkList(I);
8380       I->getParent()->getInstList().erase(I);
8381       WorkList.push_back(cast<Instruction>(NewSCC));
8382       return &BI;
8383     }
8384
8385   // Cannonicalize icmp_ne -> icmp_eq
8386   ICmpInst::Predicate IPred;
8387   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8388                       TrueDest, FalseDest)))
8389     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8390          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8391          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8392       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8393       std::string Name = I->getName(); I->setName("");
8394       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8395       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8396       // Swap Destinations and condition...
8397       BI.setCondition(NewSCC);
8398       BI.setSuccessor(0, FalseDest);
8399       BI.setSuccessor(1, TrueDest);
8400       removeFromWorkList(I);
8401       I->getParent()->getInstList().erase(I);
8402       WorkList.push_back(cast<Instruction>(NewSCC));
8403       return &BI;
8404     }
8405
8406   return 0;
8407 }
8408
8409 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8410   Value *Cond = SI.getCondition();
8411   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8412     if (I->getOpcode() == Instruction::Add)
8413       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8414         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8415         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8416           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8417                                                 AddRHS));
8418         SI.setOperand(0, I->getOperand(0));
8419         WorkList.push_back(I);
8420         return &SI;
8421       }
8422   }
8423   return 0;
8424 }
8425
8426 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8427 /// is to leave as a vector operation.
8428 static bool CheapToScalarize(Value *V, bool isConstant) {
8429   if (isa<ConstantAggregateZero>(V)) 
8430     return true;
8431   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8432     if (isConstant) return true;
8433     // If all elts are the same, we can extract.
8434     Constant *Op0 = C->getOperand(0);
8435     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8436       if (C->getOperand(i) != Op0)
8437         return false;
8438     return true;
8439   }
8440   Instruction *I = dyn_cast<Instruction>(V);
8441   if (!I) return false;
8442   
8443   // Insert element gets simplified to the inserted element or is deleted if
8444   // this is constant idx extract element and its a constant idx insertelt.
8445   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8446       isa<ConstantInt>(I->getOperand(2)))
8447     return true;
8448   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8449     return true;
8450   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8451     if (BO->hasOneUse() &&
8452         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8453          CheapToScalarize(BO->getOperand(1), isConstant)))
8454       return true;
8455   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8456     if (CI->hasOneUse() &&
8457         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8458          CheapToScalarize(CI->getOperand(1), isConstant)))
8459       return true;
8460   
8461   return false;
8462 }
8463
8464 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8465 /// elements into values that are larger than the #elts in the input.
8466 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8467   unsigned NElts = SVI->getType()->getNumElements();
8468   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8469     return std::vector<unsigned>(NElts, 0);
8470   if (isa<UndefValue>(SVI->getOperand(2)))
8471     return std::vector<unsigned>(NElts, 2*NElts);
8472
8473   std::vector<unsigned> Result;
8474   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8475   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8476     if (isa<UndefValue>(CP->getOperand(i)))
8477       Result.push_back(NElts*2);  // undef -> 8
8478     else
8479       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8480   return Result;
8481 }
8482
8483 /// FindScalarElement - Given a vector and an element number, see if the scalar
8484 /// value is already around as a register, for example if it were inserted then
8485 /// extracted from the vector.
8486 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8487   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8488   const PackedType *PTy = cast<PackedType>(V->getType());
8489   unsigned Width = PTy->getNumElements();
8490   if (EltNo >= Width)  // Out of range access.
8491     return UndefValue::get(PTy->getElementType());
8492   
8493   if (isa<UndefValue>(V))
8494     return UndefValue::get(PTy->getElementType());
8495   else if (isa<ConstantAggregateZero>(V))
8496     return Constant::getNullValue(PTy->getElementType());
8497   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8498     return CP->getOperand(EltNo);
8499   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8500     // If this is an insert to a variable element, we don't know what it is.
8501     if (!isa<ConstantInt>(III->getOperand(2))) 
8502       return 0;
8503     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8504     
8505     // If this is an insert to the element we are looking for, return the
8506     // inserted value.
8507     if (EltNo == IIElt) 
8508       return III->getOperand(1);
8509     
8510     // Otherwise, the insertelement doesn't modify the value, recurse on its
8511     // vector input.
8512     return FindScalarElement(III->getOperand(0), EltNo);
8513   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8514     unsigned InEl = getShuffleMask(SVI)[EltNo];
8515     if (InEl < Width)
8516       return FindScalarElement(SVI->getOperand(0), InEl);
8517     else if (InEl < Width*2)
8518       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8519     else
8520       return UndefValue::get(PTy->getElementType());
8521   }
8522   
8523   // Otherwise, we don't know.
8524   return 0;
8525 }
8526
8527 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8528
8529   // If packed val is undef, replace extract with scalar undef.
8530   if (isa<UndefValue>(EI.getOperand(0)))
8531     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8532
8533   // If packed val is constant 0, replace extract with scalar 0.
8534   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8535     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8536   
8537   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8538     // If packed val is constant with uniform operands, replace EI
8539     // with that operand
8540     Constant *op0 = C->getOperand(0);
8541     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8542       if (C->getOperand(i) != op0) {
8543         op0 = 0; 
8544         break;
8545       }
8546     if (op0)
8547       return ReplaceInstUsesWith(EI, op0);
8548   }
8549   
8550   // If extracting a specified index from the vector, see if we can recursively
8551   // find a previously computed scalar that was inserted into the vector.
8552   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8553     // This instruction only demands the single element from the input vector.
8554     // If the input vector has a single use, simplify it based on this use
8555     // property.
8556     uint64_t IndexVal = IdxC->getZExtValue();
8557     if (EI.getOperand(0)->hasOneUse()) {
8558       uint64_t UndefElts;
8559       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8560                                                 1 << IndexVal,
8561                                                 UndefElts)) {
8562         EI.setOperand(0, V);
8563         return &EI;
8564       }
8565     }
8566     
8567     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8568       return ReplaceInstUsesWith(EI, Elt);
8569   }
8570   
8571   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8572     if (I->hasOneUse()) {
8573       // Push extractelement into predecessor operation if legal and
8574       // profitable to do so
8575       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8576         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8577         if (CheapToScalarize(BO, isConstantElt)) {
8578           ExtractElementInst *newEI0 = 
8579             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8580                                    EI.getName()+".lhs");
8581           ExtractElementInst *newEI1 =
8582             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8583                                    EI.getName()+".rhs");
8584           InsertNewInstBefore(newEI0, EI);
8585           InsertNewInstBefore(newEI1, EI);
8586           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8587         }
8588       } else if (isa<LoadInst>(I)) {
8589         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8590                                       PointerType::get(EI.getType()), EI);
8591         GetElementPtrInst *GEP = 
8592           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8593         InsertNewInstBefore(GEP, EI);
8594         return new LoadInst(GEP);
8595       }
8596     }
8597     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8598       // Extracting the inserted element?
8599       if (IE->getOperand(2) == EI.getOperand(1))
8600         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8601       // If the inserted and extracted elements are constants, they must not
8602       // be the same value, extract from the pre-inserted value instead.
8603       if (isa<Constant>(IE->getOperand(2)) &&
8604           isa<Constant>(EI.getOperand(1))) {
8605         AddUsesToWorkList(EI);
8606         EI.setOperand(0, IE->getOperand(0));
8607         return &EI;
8608       }
8609     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8610       // If this is extracting an element from a shufflevector, figure out where
8611       // it came from and extract from the appropriate input element instead.
8612       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8613         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8614         Value *Src;
8615         if (SrcIdx < SVI->getType()->getNumElements())
8616           Src = SVI->getOperand(0);
8617         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8618           SrcIdx -= SVI->getType()->getNumElements();
8619           Src = SVI->getOperand(1);
8620         } else {
8621           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8622         }
8623         return new ExtractElementInst(Src, SrcIdx);
8624       }
8625     }
8626   }
8627   return 0;
8628 }
8629
8630 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8631 /// elements from either LHS or RHS, return the shuffle mask and true. 
8632 /// Otherwise, return false.
8633 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8634                                          std::vector<Constant*> &Mask) {
8635   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8636          "Invalid CollectSingleShuffleElements");
8637   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8638
8639   if (isa<UndefValue>(V)) {
8640     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8641     return true;
8642   } else if (V == LHS) {
8643     for (unsigned i = 0; i != NumElts; ++i)
8644       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8645     return true;
8646   } else if (V == RHS) {
8647     for (unsigned i = 0; i != NumElts; ++i)
8648       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8649     return true;
8650   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8651     // If this is an insert of an extract from some other vector, include it.
8652     Value *VecOp    = IEI->getOperand(0);
8653     Value *ScalarOp = IEI->getOperand(1);
8654     Value *IdxOp    = IEI->getOperand(2);
8655     
8656     if (!isa<ConstantInt>(IdxOp))
8657       return false;
8658     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8659     
8660     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8661       // Okay, we can handle this if the vector we are insertinting into is
8662       // transitively ok.
8663       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8664         // If so, update the mask to reflect the inserted undef.
8665         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8666         return true;
8667       }      
8668     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8669       if (isa<ConstantInt>(EI->getOperand(1)) &&
8670           EI->getOperand(0)->getType() == V->getType()) {
8671         unsigned ExtractedIdx =
8672           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8673         
8674         // This must be extracting from either LHS or RHS.
8675         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8676           // Okay, we can handle this if the vector we are insertinting into is
8677           // transitively ok.
8678           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8679             // If so, update the mask to reflect the inserted value.
8680             if (EI->getOperand(0) == LHS) {
8681               Mask[InsertedIdx & (NumElts-1)] = 
8682                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8683             } else {
8684               assert(EI->getOperand(0) == RHS);
8685               Mask[InsertedIdx & (NumElts-1)] = 
8686                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8687               
8688             }
8689             return true;
8690           }
8691         }
8692       }
8693     }
8694   }
8695   // TODO: Handle shufflevector here!
8696   
8697   return false;
8698 }
8699
8700 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8701 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8702 /// that computes V and the LHS value of the shuffle.
8703 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8704                                      Value *&RHS) {
8705   assert(isa<PackedType>(V->getType()) && 
8706          (RHS == 0 || V->getType() == RHS->getType()) &&
8707          "Invalid shuffle!");
8708   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8709
8710   if (isa<UndefValue>(V)) {
8711     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8712     return V;
8713   } else if (isa<ConstantAggregateZero>(V)) {
8714     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8715     return V;
8716   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8717     // If this is an insert of an extract from some other vector, include it.
8718     Value *VecOp    = IEI->getOperand(0);
8719     Value *ScalarOp = IEI->getOperand(1);
8720     Value *IdxOp    = IEI->getOperand(2);
8721     
8722     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8723       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8724           EI->getOperand(0)->getType() == V->getType()) {
8725         unsigned ExtractedIdx =
8726           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8727         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8728         
8729         // Either the extracted from or inserted into vector must be RHSVec,
8730         // otherwise we'd end up with a shuffle of three inputs.
8731         if (EI->getOperand(0) == RHS || RHS == 0) {
8732           RHS = EI->getOperand(0);
8733           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8734           Mask[InsertedIdx & (NumElts-1)] = 
8735             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8736           return V;
8737         }
8738         
8739         if (VecOp == RHS) {
8740           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8741           // Everything but the extracted element is replaced with the RHS.
8742           for (unsigned i = 0; i != NumElts; ++i) {
8743             if (i != InsertedIdx)
8744               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8745           }
8746           return V;
8747         }
8748         
8749         // If this insertelement is a chain that comes from exactly these two
8750         // vectors, return the vector and the effective shuffle.
8751         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8752           return EI->getOperand(0);
8753         
8754       }
8755     }
8756   }
8757   // TODO: Handle shufflevector here!
8758   
8759   // Otherwise, can't do anything fancy.  Return an identity vector.
8760   for (unsigned i = 0; i != NumElts; ++i)
8761     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8762   return V;
8763 }
8764
8765 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8766   Value *VecOp    = IE.getOperand(0);
8767   Value *ScalarOp = IE.getOperand(1);
8768   Value *IdxOp    = IE.getOperand(2);
8769   
8770   // If the inserted element was extracted from some other vector, and if the 
8771   // indexes are constant, try to turn this into a shufflevector operation.
8772   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8773     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8774         EI->getOperand(0)->getType() == IE.getType()) {
8775       unsigned NumVectorElts = IE.getType()->getNumElements();
8776       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8777       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8778       
8779       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8780         return ReplaceInstUsesWith(IE, VecOp);
8781       
8782       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8783         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8784       
8785       // If we are extracting a value from a vector, then inserting it right
8786       // back into the same place, just use the input vector.
8787       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8788         return ReplaceInstUsesWith(IE, VecOp);      
8789       
8790       // We could theoretically do this for ANY input.  However, doing so could
8791       // turn chains of insertelement instructions into a chain of shufflevector
8792       // instructions, and right now we do not merge shufflevectors.  As such,
8793       // only do this in a situation where it is clear that there is benefit.
8794       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8795         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8796         // the values of VecOp, except then one read from EIOp0.
8797         // Build a new shuffle mask.
8798         std::vector<Constant*> Mask;
8799         if (isa<UndefValue>(VecOp))
8800           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8801         else {
8802           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8803           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8804                                                        NumVectorElts));
8805         } 
8806         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8807         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8808                                      ConstantPacked::get(Mask));
8809       }
8810       
8811       // If this insertelement isn't used by some other insertelement, turn it
8812       // (and any insertelements it points to), into one big shuffle.
8813       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8814         std::vector<Constant*> Mask;
8815         Value *RHS = 0;
8816         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8817         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8818         // We now have a shuffle of LHS, RHS, Mask.
8819         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8820       }
8821     }
8822   }
8823
8824   return 0;
8825 }
8826
8827
8828 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8829   Value *LHS = SVI.getOperand(0);
8830   Value *RHS = SVI.getOperand(1);
8831   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8832
8833   bool MadeChange = false;
8834   
8835   // Undefined shuffle mask -> undefined value.
8836   if (isa<UndefValue>(SVI.getOperand(2)))
8837     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8838   
8839   // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8840   // the undef, change them to undefs.
8841   
8842   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8843   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8844   if (LHS == RHS || isa<UndefValue>(LHS)) {
8845     if (isa<UndefValue>(LHS) && LHS == RHS) {
8846       // shuffle(undef,undef,mask) -> undef.
8847       return ReplaceInstUsesWith(SVI, LHS);
8848     }
8849     
8850     // Remap any references to RHS to use LHS.
8851     std::vector<Constant*> Elts;
8852     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8853       if (Mask[i] >= 2*e)
8854         Elts.push_back(UndefValue::get(Type::Int32Ty));
8855       else {
8856         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8857             (Mask[i] <  e && isa<UndefValue>(LHS)))
8858           Mask[i] = 2*e;     // Turn into undef.
8859         else
8860           Mask[i] &= (e-1);  // Force to LHS.
8861         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8862       }
8863     }
8864     SVI.setOperand(0, SVI.getOperand(1));
8865     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8866     SVI.setOperand(2, ConstantPacked::get(Elts));
8867     LHS = SVI.getOperand(0);
8868     RHS = SVI.getOperand(1);
8869     MadeChange = true;
8870   }
8871   
8872   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8873   bool isLHSID = true, isRHSID = true;
8874     
8875   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8876     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8877     // Is this an identity shuffle of the LHS value?
8878     isLHSID &= (Mask[i] == i);
8879       
8880     // Is this an identity shuffle of the RHS value?
8881     isRHSID &= (Mask[i]-e == i);
8882   }
8883
8884   // Eliminate identity shuffles.
8885   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8886   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8887   
8888   // If the LHS is a shufflevector itself, see if we can combine it with this
8889   // one without producing an unusual shuffle.  Here we are really conservative:
8890   // we are absolutely afraid of producing a shuffle mask not in the input
8891   // program, because the code gen may not be smart enough to turn a merged
8892   // shuffle into two specific shuffles: it may produce worse code.  As such,
8893   // we only merge two shuffles if the result is one of the two input shuffle
8894   // masks.  In this case, merging the shuffles just removes one instruction,
8895   // which we know is safe.  This is good for things like turning:
8896   // (splat(splat)) -> splat.
8897   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8898     if (isa<UndefValue>(RHS)) {
8899       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8900
8901       std::vector<unsigned> NewMask;
8902       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8903         if (Mask[i] >= 2*e)
8904           NewMask.push_back(2*e);
8905         else
8906           NewMask.push_back(LHSMask[Mask[i]]);
8907       
8908       // If the result mask is equal to the src shuffle or this shuffle mask, do
8909       // the replacement.
8910       if (NewMask == LHSMask || NewMask == Mask) {
8911         std::vector<Constant*> Elts;
8912         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8913           if (NewMask[i] >= e*2) {
8914             Elts.push_back(UndefValue::get(Type::Int32Ty));
8915           } else {
8916             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8917           }
8918         }
8919         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8920                                      LHSSVI->getOperand(1),
8921                                      ConstantPacked::get(Elts));
8922       }
8923     }
8924   }
8925   
8926   return MadeChange ? &SVI : 0;
8927 }
8928
8929
8930
8931 void InstCombiner::removeFromWorkList(Instruction *I) {
8932   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8933                  WorkList.end());
8934 }
8935
8936
8937 /// TryToSinkInstruction - Try to move the specified instruction from its
8938 /// current block into the beginning of DestBlock, which can only happen if it's
8939 /// safe to move the instruction past all of the instructions between it and the
8940 /// end of its block.
8941 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8942   assert(I->hasOneUse() && "Invariants didn't hold!");
8943
8944   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8945   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8946
8947   // Do not sink alloca instructions out of the entry block.
8948   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8949     return false;
8950
8951   // We can only sink load instructions if there is nothing between the load and
8952   // the end of block that could change the value.
8953   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8954     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8955          Scan != E; ++Scan)
8956       if (Scan->mayWriteToMemory())
8957         return false;
8958   }
8959
8960   BasicBlock::iterator InsertPos = DestBlock->begin();
8961   while (isa<PHINode>(InsertPos)) ++InsertPos;
8962
8963   I->moveBefore(InsertPos);
8964   ++NumSunkInst;
8965   return true;
8966 }
8967
8968 /// OptimizeConstantExpr - Given a constant expression and target data layout
8969 /// information, symbolically evaluate the constant expr to something simpler
8970 /// if possible.
8971 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8972   if (!TD) return CE;
8973   
8974   Constant *Ptr = CE->getOperand(0);
8975   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8976       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8977     // If this is a constant expr gep that is effectively computing an
8978     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8979     bool isFoldableGEP = true;
8980     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8981       if (!isa<ConstantInt>(CE->getOperand(i)))
8982         isFoldableGEP = false;
8983     if (isFoldableGEP) {
8984       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8985       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8986       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
8987       return ConstantExpr::getIntToPtr(C, CE->getType());
8988     }
8989   }
8990   
8991   return CE;
8992 }
8993
8994
8995 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8996 /// all reachable code to the worklist.
8997 ///
8998 /// This has a couple of tricks to make the code faster and more powerful.  In
8999 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9000 /// them to the worklist (this significantly speeds up instcombine on code where
9001 /// many instructions are dead or constant).  Additionally, if we find a branch
9002 /// whose condition is a known constant, we only visit the reachable successors.
9003 ///
9004 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9005                                        std::set<BasicBlock*> &Visited,
9006                                        std::vector<Instruction*> &WorkList,
9007                                        const TargetData *TD) {
9008   // We have now visited this block!  If we've already been here, bail out.
9009   if (!Visited.insert(BB).second) return;
9010     
9011   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9012     Instruction *Inst = BBI++;
9013     
9014     // DCE instruction if trivially dead.
9015     if (isInstructionTriviallyDead(Inst)) {
9016       ++NumDeadInst;
9017       DOUT << "IC: DCE: " << *Inst;
9018       Inst->eraseFromParent();
9019       continue;
9020     }
9021     
9022     // ConstantProp instruction if trivially constant.
9023     if (Constant *C = ConstantFoldInstruction(Inst)) {
9024       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9025         C = OptimizeConstantExpr(CE, TD);
9026       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9027       Inst->replaceAllUsesWith(C);
9028       ++NumConstProp;
9029       Inst->eraseFromParent();
9030       continue;
9031     }
9032     
9033     WorkList.push_back(Inst);
9034   }
9035
9036   // Recursively visit successors.  If this is a branch or switch on a constant,
9037   // only visit the reachable successor.
9038   TerminatorInst *TI = BB->getTerminator();
9039   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9040     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9041       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
9042       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9043                                  TD);
9044       return;
9045     }
9046   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9047     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9048       // See if this is an explicit destination.
9049       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9050         if (SI->getCaseValue(i) == Cond) {
9051           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9052           return;
9053         }
9054       
9055       // Otherwise it is the default destination.
9056       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9057       return;
9058     }
9059   }
9060   
9061   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9062     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9063 }
9064
9065 bool InstCombiner::runOnFunction(Function &F) {
9066   bool Changed = false;
9067   TD = &getAnalysis<TargetData>();
9068
9069   {
9070     // Do a depth-first traversal of the function, populate the worklist with
9071     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9072     // track of which blocks we visit.
9073     std::set<BasicBlock*> Visited;
9074     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9075
9076     // Do a quick scan over the function.  If we find any blocks that are
9077     // unreachable, remove any instructions inside of them.  This prevents
9078     // the instcombine code from having to deal with some bad special cases.
9079     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9080       if (!Visited.count(BB)) {
9081         Instruction *Term = BB->getTerminator();
9082         while (Term != BB->begin()) {   // Remove instrs bottom-up
9083           BasicBlock::iterator I = Term; --I;
9084
9085           DOUT << "IC: DCE: " << *I;
9086           ++NumDeadInst;
9087
9088           if (!I->use_empty())
9089             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9090           I->eraseFromParent();
9091         }
9092       }
9093   }
9094
9095   while (!WorkList.empty()) {
9096     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9097     WorkList.pop_back();
9098
9099     // Check to see if we can DCE the instruction.
9100     if (isInstructionTriviallyDead(I)) {
9101       // Add operands to the worklist.
9102       if (I->getNumOperands() < 4)
9103         AddUsesToWorkList(*I);
9104       ++NumDeadInst;
9105
9106       DOUT << "IC: DCE: " << *I;
9107
9108       I->eraseFromParent();
9109       removeFromWorkList(I);
9110       continue;
9111     }
9112
9113     // Instruction isn't dead, see if we can constant propagate it.
9114     if (Constant *C = ConstantFoldInstruction(I)) {
9115       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9116         C = OptimizeConstantExpr(CE, TD);
9117       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9118
9119       // Add operands to the worklist.
9120       AddUsesToWorkList(*I);
9121       ReplaceInstUsesWith(*I, C);
9122
9123       ++NumConstProp;
9124       I->eraseFromParent();
9125       removeFromWorkList(I);
9126       continue;
9127     }
9128
9129     // See if we can trivially sink this instruction to a successor basic block.
9130     if (I->hasOneUse()) {
9131       BasicBlock *BB = I->getParent();
9132       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9133       if (UserParent != BB) {
9134         bool UserIsSuccessor = false;
9135         // See if the user is one of our successors.
9136         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9137           if (*SI == UserParent) {
9138             UserIsSuccessor = true;
9139             break;
9140           }
9141
9142         // If the user is one of our immediate successors, and if that successor
9143         // only has us as a predecessors (we'd have to split the critical edge
9144         // otherwise), we can keep going.
9145         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9146             next(pred_begin(UserParent)) == pred_end(UserParent))
9147           // Okay, the CFG is simple enough, try to sink this instruction.
9148           Changed |= TryToSinkInstruction(I, UserParent);
9149       }
9150     }
9151
9152     // Now that we have an instruction, try combining it to simplify it...
9153     if (Instruction *Result = visit(*I)) {
9154       ++NumCombined;
9155       // Should we replace the old instruction with a new one?
9156       if (Result != I) {
9157         DOUT << "IC: Old = " << *I
9158              << "    New = " << *Result;
9159
9160         // Everything uses the new instruction now.
9161         I->replaceAllUsesWith(Result);
9162
9163         // Push the new instruction and any users onto the worklist.
9164         WorkList.push_back(Result);
9165         AddUsersToWorkList(*Result);
9166
9167         // Move the name to the new instruction first...
9168         std::string OldName = I->getName(); I->setName("");
9169         Result->setName(OldName);
9170
9171         // Insert the new instruction into the basic block...
9172         BasicBlock *InstParent = I->getParent();
9173         BasicBlock::iterator InsertPos = I;
9174
9175         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9176           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9177             ++InsertPos;
9178
9179         InstParent->getInstList().insert(InsertPos, Result);
9180
9181         // Make sure that we reprocess all operands now that we reduced their
9182         // use counts.
9183         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9184           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9185             WorkList.push_back(OpI);
9186
9187         // Instructions can end up on the worklist more than once.  Make sure
9188         // we do not process an instruction that has been deleted.
9189         removeFromWorkList(I);
9190
9191         // Erase the old instruction.
9192         InstParent->getInstList().erase(I);
9193       } else {
9194         DOUT << "IC: MOD = " << *I;
9195
9196         // If the instruction was modified, it's possible that it is now dead.
9197         // if so, remove it.
9198         if (isInstructionTriviallyDead(I)) {
9199           // Make sure we process all operands now that we are reducing their
9200           // use counts.
9201           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9202             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9203               WorkList.push_back(OpI);
9204
9205           // Instructions may end up in the worklist more than once.  Erase all
9206           // occurrences of this instruction.
9207           removeFromWorkList(I);
9208           I->eraseFromParent();
9209         } else {
9210           WorkList.push_back(Result);
9211           AddUsersToWorkList(*Result);
9212         }
9213       }
9214       Changed = true;
9215     }
9216   }
9217
9218   return Changed;
9219 }
9220
9221 FunctionPass *llvm::createInstructionCombiningPass() {
9222   return new InstCombiner();
9223 }
9224