aba50dca3e70be8333b204d6c7a57778c350832d
[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   // X + ~X --> -1   since   ~X = -X-1
1875   if (dyn_castNotVal(LHS) == RHS ||
1876       dyn_castNotVal(RHS) == LHS)
1877     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1878   
1879
1880   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1881   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1882     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1883       return R;
1884
1885   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1886     Value *X = 0;
1887     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1888       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1889       return BinaryOperator::createSub(C, X);
1890     }
1891
1892     // (X & FF00) + xx00  -> (X+xx00) & FF00
1893     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1894       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1895       if (Anded == CRHS) {
1896         // See if all bits from the first bit set in the Add RHS up are included
1897         // in the mask.  First, get the rightmost bit.
1898         uint64_t AddRHSV = CRHS->getZExtValue();
1899
1900         // Form a mask of all bits from the lowest bit added through the top.
1901         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1902         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1903
1904         // See if the and mask includes all of these bits.
1905         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1906
1907         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1908           // Okay, the xform is safe.  Insert the new add pronto.
1909           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1910                                                             LHS->getName()), I);
1911           return BinaryOperator::createAnd(NewAdd, C2);
1912         }
1913       }
1914     }
1915
1916     // Try to fold constant add into select arguments.
1917     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1918       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1919         return R;
1920   }
1921
1922   // add (cast *A to intptrtype) B -> 
1923   //   cast (GEP (cast *A to sbyte*) B) -> 
1924   //     intptrtype
1925   {
1926     CastInst *CI = dyn_cast<CastInst>(LHS);
1927     Value *Other = RHS;
1928     if (!CI) {
1929       CI = dyn_cast<CastInst>(RHS);
1930       Other = LHS;
1931     }
1932     if (CI && CI->getType()->isSized() && 
1933         (CI->getType()->getPrimitiveSize() == 
1934          TD->getIntPtrType()->getPrimitiveSize()) 
1935         && isa<PointerType>(CI->getOperand(0)->getType())) {
1936       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1937                                    PointerType::get(Type::Int8Ty), I);
1938       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1939       return new PtrToIntInst(I2, CI->getType());
1940     }
1941   }
1942
1943   return Changed ? &I : 0;
1944 }
1945
1946 // isSignBit - Return true if the value represented by the constant only has the
1947 // highest order bit set.
1948 static bool isSignBit(ConstantInt *CI) {
1949   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1950   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1951 }
1952
1953 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1954 ///
1955 static Value *RemoveNoopCast(Value *V) {
1956   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1957     const Type *CTy = CI->getType();
1958     const Type *OpTy = CI->getOperand(0)->getType();
1959     if (CTy->isInteger() && OpTy->isInteger()) {
1960       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1961         return RemoveNoopCast(CI->getOperand(0));
1962     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1963       return RemoveNoopCast(CI->getOperand(0));
1964   }
1965   return V;
1966 }
1967
1968 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1969   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1970
1971   if (Op0 == Op1)         // sub X, X  -> 0
1972     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1973
1974   // If this is a 'B = x-(-A)', change to B = x+A...
1975   if (Value *V = dyn_castNegVal(Op1))
1976     return BinaryOperator::createAdd(Op0, V);
1977
1978   if (isa<UndefValue>(Op0))
1979     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1980   if (isa<UndefValue>(Op1))
1981     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1982
1983   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1984     // Replace (-1 - A) with (~A)...
1985     if (C->isAllOnesValue())
1986       return BinaryOperator::createNot(Op1);
1987
1988     // C - ~X == X + (1+C)
1989     Value *X = 0;
1990     if (match(Op1, m_Not(m_Value(X))))
1991       return BinaryOperator::createAdd(X,
1992                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1993     // -((uint)X >> 31) -> ((int)X >> 31)
1994     // -((int)X >> 31) -> ((uint)X >> 31)
1995     if (C->isNullValue()) {
1996       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1997       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1998         if (SI->getOpcode() == Instruction::LShr) {
1999           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2000             // Check to see if we are shifting out everything but the sign bit.
2001             if (CU->getZExtValue() == 
2002                 SI->getType()->getPrimitiveSizeInBits()-1) {
2003               // Ok, the transformation is safe.  Insert AShr.
2004               // FIXME: Once integer types are signless, this cast should be 
2005               // removed.  
2006               Value *ShiftOp = SI->getOperand(0); 
2007               return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2008                                    SI->getName());
2009             }
2010           }
2011         }
2012         else if (SI->getOpcode() == Instruction::AShr) {
2013           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2014             // Check to see if we are shifting out everything but the sign bit.
2015             if (CU->getZExtValue() == 
2016                 SI->getType()->getPrimitiveSizeInBits()-1) {
2017               
2018               // Ok, the transformation is safe.  Insert LShr. 
2019               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
2020                                    SI->getName());
2021             }
2022           }
2023         } 
2024     }
2025
2026     // Try to fold constant sub into select arguments.
2027     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2028       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2029         return R;
2030
2031     if (isa<PHINode>(Op0))
2032       if (Instruction *NV = FoldOpIntoPhi(I))
2033         return NV;
2034   }
2035
2036   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2037     if (Op1I->getOpcode() == Instruction::Add &&
2038         !Op0->getType()->isFPOrFPVector()) {
2039       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2040         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2041       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2042         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2043       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2044         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2045           // C1-(X+C2) --> (C1-C2)-X
2046           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2047                                            Op1I->getOperand(0));
2048       }
2049     }
2050
2051     if (Op1I->hasOneUse()) {
2052       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2053       // is not used by anyone else...
2054       //
2055       if (Op1I->getOpcode() == Instruction::Sub &&
2056           !Op1I->getType()->isFPOrFPVector()) {
2057         // Swap the two operands of the subexpr...
2058         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2059         Op1I->setOperand(0, IIOp1);
2060         Op1I->setOperand(1, IIOp0);
2061
2062         // Create the new top level add instruction...
2063         return BinaryOperator::createAdd(Op0, Op1);
2064       }
2065
2066       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2067       //
2068       if (Op1I->getOpcode() == Instruction::And &&
2069           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2070         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2071
2072         Value *NewNot =
2073           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2074         return BinaryOperator::createAnd(Op0, NewNot);
2075       }
2076
2077       // 0 - (X sdiv C)  -> (X sdiv -C)
2078       if (Op1I->getOpcode() == Instruction::SDiv)
2079         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2080           if (CSI->isNullValue())
2081             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2082               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2083                                                ConstantExpr::getNeg(DivRHS));
2084
2085       // X - X*C --> X * (1-C)
2086       ConstantInt *C2 = 0;
2087       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2088         Constant *CP1 =
2089           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2090         return BinaryOperator::createMul(Op0, CP1);
2091       }
2092     }
2093   }
2094
2095   if (!Op0->getType()->isFPOrFPVector())
2096     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2097       if (Op0I->getOpcode() == Instruction::Add) {
2098         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2099           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2100         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2101           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2102       } else if (Op0I->getOpcode() == Instruction::Sub) {
2103         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2104           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2105       }
2106
2107   ConstantInt *C1;
2108   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2109     if (X == Op1) { // X*C - X --> X * (C-1)
2110       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2111       return BinaryOperator::createMul(Op1, CP1);
2112     }
2113
2114     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2115     if (X == dyn_castFoldableMul(Op1, C2))
2116       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2117   }
2118   return 0;
2119 }
2120
2121 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2122 /// really just returns true if the most significant (sign) bit is set.
2123 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2124   switch (pred) {
2125     case ICmpInst::ICMP_SLT: 
2126       // True if LHS s< RHS and RHS == 0
2127       return RHS->isNullValue();
2128     case ICmpInst::ICMP_SLE: 
2129       // True if LHS s<= RHS and RHS == -1
2130       return RHS->isAllOnesValue();
2131     case ICmpInst::ICMP_UGE: 
2132       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2133       return RHS->getZExtValue() == (1ULL << 
2134         (RHS->getType()->getPrimitiveSizeInBits()-1));
2135     case ICmpInst::ICMP_UGT:
2136       // True if LHS u> RHS and RHS == high-bit-mask - 1
2137       return RHS->getZExtValue() ==
2138         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2139     default:
2140       return false;
2141   }
2142 }
2143
2144 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2145   bool Changed = SimplifyCommutative(I);
2146   Value *Op0 = I.getOperand(0);
2147
2148   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2149     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2150
2151   // Simplify mul instructions with a constant RHS...
2152   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2153     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2154
2155       // ((X << C1)*C2) == (X * (C2 << C1))
2156       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2157         if (SI->getOpcode() == Instruction::Shl)
2158           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2159             return BinaryOperator::createMul(SI->getOperand(0),
2160                                              ConstantExpr::getShl(CI, ShOp));
2161
2162       if (CI->isNullValue())
2163         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2164       if (CI->equalsInt(1))                  // X * 1  == X
2165         return ReplaceInstUsesWith(I, Op0);
2166       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2167         return BinaryOperator::createNeg(Op0, I.getName());
2168
2169       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2170       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2171         uint64_t C = Log2_64(Val);
2172         return new ShiftInst(Instruction::Shl, Op0,
2173                              ConstantInt::get(Type::Int8Ty, C));
2174       }
2175     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2176       if (Op1F->isNullValue())
2177         return ReplaceInstUsesWith(I, Op1);
2178
2179       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2180       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2181       if (Op1F->getValue() == 1.0)
2182         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2183     }
2184     
2185     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2186       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2187           isa<ConstantInt>(Op0I->getOperand(1))) {
2188         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2189         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2190                                                      Op1, "tmp");
2191         InsertNewInstBefore(Add, I);
2192         Value *C1C2 = ConstantExpr::getMul(Op1, 
2193                                            cast<Constant>(Op0I->getOperand(1)));
2194         return BinaryOperator::createAdd(Add, C1C2);
2195         
2196       }
2197
2198     // Try to fold constant mul into select arguments.
2199     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2200       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2201         return R;
2202
2203     if (isa<PHINode>(Op0))
2204       if (Instruction *NV = FoldOpIntoPhi(I))
2205         return NV;
2206   }
2207
2208   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2209     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2210       return BinaryOperator::createMul(Op0v, Op1v);
2211
2212   // If one of the operands of the multiply is a cast from a boolean value, then
2213   // we know the bool is either zero or one, so this is a 'masking' multiply.
2214   // See if we can simplify things based on how the boolean was originally
2215   // formed.
2216   CastInst *BoolCast = 0;
2217   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2218     if (CI->getOperand(0)->getType() == Type::BoolTy)
2219       BoolCast = CI;
2220   if (!BoolCast)
2221     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2222       if (CI->getOperand(0)->getType() == Type::BoolTy)
2223         BoolCast = CI;
2224   if (BoolCast) {
2225     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2226       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2227       const Type *SCOpTy = SCIOp0->getType();
2228
2229       // If the icmp is true iff the sign bit of X is set, then convert this
2230       // multiply into a shift/and combination.
2231       if (isa<ConstantInt>(SCIOp1) &&
2232           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2233         // Shift the X value right to turn it into "all signbits".
2234         Constant *Amt = ConstantInt::get(Type::Int8Ty,
2235                                           SCOpTy->getPrimitiveSizeInBits()-1);
2236         Value *V =
2237           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2238                                             BoolCast->getOperand(0)->getName()+
2239                                             ".mask"), I);
2240
2241         // If the multiply type is not the same as the source type, sign extend
2242         // or truncate to the multiply type.
2243         if (I.getType() != V->getType()) {
2244           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2245           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2246           Instruction::CastOps opcode = 
2247             (SrcBits == DstBits ? Instruction::BitCast : 
2248              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2249           V = InsertCastBefore(opcode, V, I.getType(), I);
2250         }
2251
2252         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2253         return BinaryOperator::createAnd(V, OtherOp);
2254       }
2255     }
2256   }
2257
2258   return Changed ? &I : 0;
2259 }
2260
2261 /// This function implements the transforms on div instructions that work
2262 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2263 /// used by the visitors to those instructions.
2264 /// @brief Transforms common to all three div instructions
2265 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2266   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2267
2268   // undef / X -> 0
2269   if (isa<UndefValue>(Op0))
2270     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2271
2272   // X / undef -> undef
2273   if (isa<UndefValue>(Op1))
2274     return ReplaceInstUsesWith(I, Op1);
2275
2276   // Handle cases involving: div X, (select Cond, Y, Z)
2277   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2278     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2279     // same basic block, then we replace the select with Y, and the condition 
2280     // of the select with false (if the cond value is in the same BB).  If the
2281     // select has uses other than the div, this allows them to be simplified
2282     // also. Note that div X, Y is just as good as div X, 0 (undef)
2283     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2284       if (ST->isNullValue()) {
2285         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2286         if (CondI && CondI->getParent() == I.getParent())
2287           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2288         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2289           I.setOperand(1, SI->getOperand(2));
2290         else
2291           UpdateValueUsesWith(SI, SI->getOperand(2));
2292         return &I;
2293       }
2294
2295     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2296     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2297       if (ST->isNullValue()) {
2298         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2299         if (CondI && CondI->getParent() == I.getParent())
2300           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2301         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2302           I.setOperand(1, SI->getOperand(1));
2303         else
2304           UpdateValueUsesWith(SI, SI->getOperand(1));
2305         return &I;
2306       }
2307   }
2308
2309   return 0;
2310 }
2311
2312 /// This function implements the transforms common to both integer division
2313 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2314 /// division instructions.
2315 /// @brief Common integer divide transforms
2316 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2317   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2318
2319   if (Instruction *Common = commonDivTransforms(I))
2320     return Common;
2321
2322   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2323     // div X, 1 == X
2324     if (RHS->equalsInt(1))
2325       return ReplaceInstUsesWith(I, Op0);
2326
2327     // (X / C1) / C2  -> X / (C1*C2)
2328     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2329       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2330         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2331           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2332                                         ConstantExpr::getMul(RHS, LHSRHS));
2333         }
2334
2335     if (!RHS->isNullValue()) { // avoid X udiv 0
2336       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2337         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2338           return R;
2339       if (isa<PHINode>(Op0))
2340         if (Instruction *NV = FoldOpIntoPhi(I))
2341           return NV;
2342     }
2343   }
2344
2345   // 0 / X == 0, we don't need to preserve faults!
2346   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2347     if (LHS->equalsInt(0))
2348       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2349
2350   return 0;
2351 }
2352
2353 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2354   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2355
2356   // Handle the integer div common cases
2357   if (Instruction *Common = commonIDivTransforms(I))
2358     return Common;
2359
2360   // X udiv C^2 -> X >> C
2361   // Check to see if this is an unsigned division with an exact power of 2,
2362   // if so, convert to a right shift.
2363   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2364     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2365       if (isPowerOf2_64(Val)) {
2366         uint64_t ShiftAmt = Log2_64(Val);
2367         return new ShiftInst(Instruction::LShr, Op0, 
2368                               ConstantInt::get(Type::Int8Ty, ShiftAmt));
2369       }
2370   }
2371
2372   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2373   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2374     if (RHSI->getOpcode() == Instruction::Shl &&
2375         isa<ConstantInt>(RHSI->getOperand(0))) {
2376       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2377       if (isPowerOf2_64(C1)) {
2378         Value *N = RHSI->getOperand(1);
2379         const Type *NTy = N->getType();
2380         if (uint64_t C2 = Log2_64(C1)) {
2381           Constant *C2V = ConstantInt::get(NTy, C2);
2382           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2383         }
2384         return new ShiftInst(Instruction::LShr, Op0, N);
2385       }
2386     }
2387   }
2388   
2389   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2390   // where C1&C2 are powers of two.
2391   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2392     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2393       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2394         if (!STO->isNullValue() && !STO->isNullValue()) {
2395           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2396           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2397             // Compute the shift amounts
2398             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2399             // Construct the "on true" case of the select
2400             Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2401             Instruction *TSI = 
2402               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2403             TSI = InsertNewInstBefore(TSI, I);
2404     
2405             // Construct the "on false" case of the select
2406             Constant *FC = ConstantInt::get(Type::Int8Ty, FSA); 
2407             Instruction *FSI = 
2408               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2409             FSI = InsertNewInstBefore(FSI, I);
2410
2411             // construct the select instruction and return it.
2412             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2413           }
2414         }
2415   }
2416   return 0;
2417 }
2418
2419 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2420   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2421
2422   // Handle the integer div common cases
2423   if (Instruction *Common = commonIDivTransforms(I))
2424     return Common;
2425
2426   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2427     // sdiv X, -1 == -X
2428     if (RHS->isAllOnesValue())
2429       return BinaryOperator::createNeg(Op0);
2430
2431     // -X/C -> X/-C
2432     if (Value *LHSNeg = dyn_castNegVal(Op0))
2433       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2434   }
2435
2436   // If the sign bits of both operands are zero (i.e. we can prove they are
2437   // unsigned inputs), turn this into a udiv.
2438   if (I.getType()->isInteger()) {
2439     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2440     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2441       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2442     }
2443   }      
2444   
2445   return 0;
2446 }
2447
2448 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2449   return commonDivTransforms(I);
2450 }
2451
2452 /// GetFactor - If we can prove that the specified value is at least a multiple
2453 /// of some factor, return that factor.
2454 static Constant *GetFactor(Value *V) {
2455   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2456     return CI;
2457   
2458   // Unless we can be tricky, we know this is a multiple of 1.
2459   Constant *Result = ConstantInt::get(V->getType(), 1);
2460   
2461   Instruction *I = dyn_cast<Instruction>(V);
2462   if (!I) return Result;
2463   
2464   if (I->getOpcode() == Instruction::Mul) {
2465     // Handle multiplies by a constant, etc.
2466     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2467                                 GetFactor(I->getOperand(1)));
2468   } else if (I->getOpcode() == Instruction::Shl) {
2469     // (X<<C) -> X * (1 << C)
2470     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2471       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2472       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2473     }
2474   } else if (I->getOpcode() == Instruction::And) {
2475     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2476       // X & 0xFFF0 is known to be a multiple of 16.
2477       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2478       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2479         return ConstantExpr::getShl(Result, 
2480                                     ConstantInt::get(Type::Int8Ty, Zeros));
2481     }
2482   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2483     // Only handle int->int casts.
2484     if (!CI->isIntegerCast())
2485       return Result;
2486     Value *Op = CI->getOperand(0);
2487     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2488   }    
2489   return Result;
2490 }
2491
2492 /// This function implements the transforms on rem instructions that work
2493 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2494 /// is used by the visitors to those instructions.
2495 /// @brief Transforms common to all three rem instructions
2496 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2497   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2498
2499   // 0 % X == 0, we don't need to preserve faults!
2500   if (Constant *LHS = dyn_cast<Constant>(Op0))
2501     if (LHS->isNullValue())
2502       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2503
2504   if (isa<UndefValue>(Op0))              // undef % X -> 0
2505     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2506   if (isa<UndefValue>(Op1))
2507     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2508
2509   // Handle cases involving: rem X, (select Cond, Y, Z)
2510   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2511     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2512     // the same basic block, then we replace the select with Y, and the
2513     // condition of the select with false (if the cond value is in the same
2514     // BB).  If the select has uses other than the div, this allows them to be
2515     // simplified also.
2516     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2517       if (ST->isNullValue()) {
2518         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2519         if (CondI && CondI->getParent() == I.getParent())
2520           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2521         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2522           I.setOperand(1, SI->getOperand(2));
2523         else
2524           UpdateValueUsesWith(SI, SI->getOperand(2));
2525         return &I;
2526       }
2527     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2528     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2529       if (ST->isNullValue()) {
2530         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2531         if (CondI && CondI->getParent() == I.getParent())
2532           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2533         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2534           I.setOperand(1, SI->getOperand(1));
2535         else
2536           UpdateValueUsesWith(SI, SI->getOperand(1));
2537         return &I;
2538       }
2539   }
2540
2541   return 0;
2542 }
2543
2544 /// This function implements the transforms common to both integer remainder
2545 /// instructions (urem and srem). It is called by the visitors to those integer
2546 /// remainder instructions.
2547 /// @brief Common integer remainder transforms
2548 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2549   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2550
2551   if (Instruction *common = commonRemTransforms(I))
2552     return common;
2553
2554   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2555     // X % 0 == undef, we don't need to preserve faults!
2556     if (RHS->equalsInt(0))
2557       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2558     
2559     if (RHS->equalsInt(1))  // X % 1 == 0
2560       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2561
2562     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2563       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2564         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2565           return R;
2566       } else if (isa<PHINode>(Op0I)) {
2567         if (Instruction *NV = FoldOpIntoPhi(I))
2568           return NV;
2569       }
2570       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2571       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2572         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2573     }
2574   }
2575
2576   return 0;
2577 }
2578
2579 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2580   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2581
2582   if (Instruction *common = commonIRemTransforms(I))
2583     return common;
2584   
2585   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2586     // X urem C^2 -> X and C
2587     // Check to see if this is an unsigned remainder with an exact power of 2,
2588     // if so, convert to a bitwise and.
2589     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2590       if (isPowerOf2_64(C->getZExtValue()))
2591         return BinaryOperator::createAnd(Op0, SubOne(C));
2592   }
2593
2594   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2595     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2596     if (RHSI->getOpcode() == Instruction::Shl &&
2597         isa<ConstantInt>(RHSI->getOperand(0))) {
2598       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2599       if (isPowerOf2_64(C1)) {
2600         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2601         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2602                                                                    "tmp"), I);
2603         return BinaryOperator::createAnd(Op0, Add);
2604       }
2605     }
2606   }
2607
2608   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2609   // where C1&C2 are powers of two.
2610   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2611     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2612       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2613         // STO == 0 and SFO == 0 handled above.
2614         if (isPowerOf2_64(STO->getZExtValue()) && 
2615             isPowerOf2_64(SFO->getZExtValue())) {
2616           Value *TrueAnd = InsertNewInstBefore(
2617             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2618           Value *FalseAnd = InsertNewInstBefore(
2619             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2620           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2621         }
2622       }
2623   }
2624   
2625   return 0;
2626 }
2627
2628 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2629   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2630
2631   if (Instruction *common = commonIRemTransforms(I))
2632     return common;
2633   
2634   if (Value *RHSNeg = dyn_castNegVal(Op1))
2635     if (!isa<ConstantInt>(RHSNeg) || 
2636         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2637       // X % -Y -> X % Y
2638       AddUsesToWorkList(I);
2639       I.setOperand(1, RHSNeg);
2640       return &I;
2641     }
2642  
2643   // If the top bits of both operands are zero (i.e. we can prove they are
2644   // unsigned inputs), turn this into a urem.
2645   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2646   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2647     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2648     return BinaryOperator::createURem(Op0, Op1, I.getName());
2649   }
2650
2651   return 0;
2652 }
2653
2654 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2655   return commonRemTransforms(I);
2656 }
2657
2658 // isMaxValueMinusOne - return true if this is Max-1
2659 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2660   if (isSigned) {
2661     // Calculate 0111111111..11111
2662     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2663     int64_t Val = INT64_MAX;             // All ones
2664     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2665     return C->getSExtValue() == Val-1;
2666   }
2667   return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2668 }
2669
2670 // isMinValuePlusOne - return true if this is Min+1
2671 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2672   if (isSigned) {
2673     // Calculate 1111111111000000000000
2674     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2675     int64_t Val = -1;                    // All ones
2676     Val <<= TypeBits-1;                  // Shift over to the right spot
2677     return C->getSExtValue() == Val+1;
2678   }
2679   return C->getZExtValue() == 1; // unsigned
2680 }
2681
2682 // isOneBitSet - Return true if there is exactly one bit set in the specified
2683 // constant.
2684 static bool isOneBitSet(const ConstantInt *CI) {
2685   uint64_t V = CI->getZExtValue();
2686   return V && (V & (V-1)) == 0;
2687 }
2688
2689 #if 0   // Currently unused
2690 // isLowOnes - Return true if the constant is of the form 0+1+.
2691 static bool isLowOnes(const ConstantInt *CI) {
2692   uint64_t V = CI->getZExtValue();
2693
2694   // There won't be bits set in parts that the type doesn't contain.
2695   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2696
2697   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2698   return U && V && (U & V) == 0;
2699 }
2700 #endif
2701
2702 // isHighOnes - Return true if the constant is of the form 1+0+.
2703 // This is the same as lowones(~X).
2704 static bool isHighOnes(const ConstantInt *CI) {
2705   uint64_t V = ~CI->getZExtValue();
2706   if (~V == 0) return false;  // 0's does not match "1+"
2707
2708   // There won't be bits set in parts that the type doesn't contain.
2709   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2710
2711   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2712   return U && V && (U & V) == 0;
2713 }
2714
2715 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2716 /// are carefully arranged to allow folding of expressions such as:
2717 ///
2718 ///      (A < B) | (A > B) --> (A != B)
2719 ///
2720 /// Note that this is only valid if the first and second predicates have the
2721 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2722 ///
2723 /// Three bits are used to represent the condition, as follows:
2724 ///   0  A > B
2725 ///   1  A == B
2726 ///   2  A < B
2727 ///
2728 /// <=>  Value  Definition
2729 /// 000     0   Always false
2730 /// 001     1   A >  B
2731 /// 010     2   A == B
2732 /// 011     3   A >= B
2733 /// 100     4   A <  B
2734 /// 101     5   A != B
2735 /// 110     6   A <= B
2736 /// 111     7   Always true
2737 ///  
2738 static unsigned getICmpCode(const ICmpInst *ICI) {
2739   switch (ICI->getPredicate()) {
2740     // False -> 0
2741   case ICmpInst::ICMP_UGT: return 1;  // 001
2742   case ICmpInst::ICMP_SGT: return 1;  // 001
2743   case ICmpInst::ICMP_EQ:  return 2;  // 010
2744   case ICmpInst::ICMP_UGE: return 3;  // 011
2745   case ICmpInst::ICMP_SGE: return 3;  // 011
2746   case ICmpInst::ICMP_ULT: return 4;  // 100
2747   case ICmpInst::ICMP_SLT: return 4;  // 100
2748   case ICmpInst::ICMP_NE:  return 5;  // 101
2749   case ICmpInst::ICMP_ULE: return 6;  // 110
2750   case ICmpInst::ICMP_SLE: return 6;  // 110
2751     // True -> 7
2752   default:
2753     assert(0 && "Invalid ICmp predicate!");
2754     return 0;
2755   }
2756 }
2757
2758 /// getICmpValue - This is the complement of getICmpCode, which turns an
2759 /// opcode and two operands into either a constant true or false, or a brand 
2760 /// new /// ICmp instruction. The sign is passed in to determine which kind
2761 /// of predicate to use in new icmp instructions.
2762 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2763   switch (code) {
2764   default: assert(0 && "Illegal ICmp code!");
2765   case  0: return ConstantBool::getFalse();
2766   case  1: 
2767     if (sign)
2768       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2769     else
2770       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2771   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2772   case  3: 
2773     if (sign)
2774       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2775     else
2776       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2777   case  4: 
2778     if (sign)
2779       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2780     else
2781       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2782   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2783   case  6: 
2784     if (sign)
2785       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2786     else
2787       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2788   case  7: return ConstantBool::getTrue();
2789   }
2790 }
2791
2792 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2793   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2794     (ICmpInst::isSignedPredicate(p1) && 
2795      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2796     (ICmpInst::isSignedPredicate(p2) && 
2797      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2798 }
2799
2800 namespace { 
2801 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2802 struct FoldICmpLogical {
2803   InstCombiner &IC;
2804   Value *LHS, *RHS;
2805   ICmpInst::Predicate pred;
2806   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2807     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2808       pred(ICI->getPredicate()) {}
2809   bool shouldApply(Value *V) const {
2810     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2811       if (PredicatesFoldable(pred, ICI->getPredicate()))
2812         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2813                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2814     return false;
2815   }
2816   Instruction *apply(Instruction &Log) const {
2817     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2818     if (ICI->getOperand(0) != LHS) {
2819       assert(ICI->getOperand(1) == LHS);
2820       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2821     }
2822
2823     unsigned LHSCode = getICmpCode(ICI);
2824     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2825     unsigned Code;
2826     switch (Log.getOpcode()) {
2827     case Instruction::And: Code = LHSCode & RHSCode; break;
2828     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2829     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2830     default: assert(0 && "Illegal logical opcode!"); return 0;
2831     }
2832
2833     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2834     if (Instruction *I = dyn_cast<Instruction>(RV))
2835       return I;
2836     // Otherwise, it's a constant boolean value...
2837     return IC.ReplaceInstUsesWith(Log, RV);
2838   }
2839 };
2840 } // end anonymous namespace
2841
2842 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2843 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2844 // guaranteed to be either a shift instruction or a binary operator.
2845 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2846                                     ConstantIntegral *OpRHS,
2847                                     ConstantIntegral *AndRHS,
2848                                     BinaryOperator &TheAnd) {
2849   Value *X = Op->getOperand(0);
2850   Constant *Together = 0;
2851   if (!isa<ShiftInst>(Op))
2852     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2853
2854   switch (Op->getOpcode()) {
2855   case Instruction::Xor:
2856     if (Op->hasOneUse()) {
2857       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2858       std::string OpName = Op->getName(); Op->setName("");
2859       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2860       InsertNewInstBefore(And, TheAnd);
2861       return BinaryOperator::createXor(And, Together);
2862     }
2863     break;
2864   case Instruction::Or:
2865     if (Together == AndRHS) // (X | C) & C --> C
2866       return ReplaceInstUsesWith(TheAnd, AndRHS);
2867
2868     if (Op->hasOneUse() && Together != OpRHS) {
2869       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2870       std::string Op0Name = Op->getName(); Op->setName("");
2871       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2872       InsertNewInstBefore(Or, TheAnd);
2873       return BinaryOperator::createAnd(Or, AndRHS);
2874     }
2875     break;
2876   case Instruction::Add:
2877     if (Op->hasOneUse()) {
2878       // Adding a one to a single bit bit-field should be turned into an XOR
2879       // of the bit.  First thing to check is to see if this AND is with a
2880       // single bit constant.
2881       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2882
2883       // Clear bits that are not part of the constant.
2884       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2885
2886       // If there is only one bit set...
2887       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2888         // Ok, at this point, we know that we are masking the result of the
2889         // ADD down to exactly one bit.  If the constant we are adding has
2890         // no bits set below this bit, then we can eliminate the ADD.
2891         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2892
2893         // Check to see if any bits below the one bit set in AndRHSV are set.
2894         if ((AddRHS & (AndRHSV-1)) == 0) {
2895           // If not, the only thing that can effect the output of the AND is
2896           // the bit specified by AndRHSV.  If that bit is set, the effect of
2897           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2898           // no effect.
2899           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2900             TheAnd.setOperand(0, X);
2901             return &TheAnd;
2902           } else {
2903             std::string Name = Op->getName(); Op->setName("");
2904             // Pull the XOR out of the AND.
2905             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2906             InsertNewInstBefore(NewAnd, TheAnd);
2907             return BinaryOperator::createXor(NewAnd, AndRHS);
2908           }
2909         }
2910       }
2911     }
2912     break;
2913
2914   case Instruction::Shl: {
2915     // We know that the AND will not produce any of the bits shifted in, so if
2916     // the anded constant includes them, clear them now!
2917     //
2918     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2919     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2920     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2921
2922     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2923       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2924     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2925       TheAnd.setOperand(1, CI);
2926       return &TheAnd;
2927     }
2928     break;
2929   }
2930   case Instruction::LShr:
2931   {
2932     // We know that the AND will not produce any of the bits shifted in, so if
2933     // the anded constant includes them, clear them now!  This only applies to
2934     // unsigned shifts, because a signed shr may bring in set bits!
2935     //
2936     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2937     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2938     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2939
2940     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2941       return ReplaceInstUsesWith(TheAnd, Op);
2942     } else if (CI != AndRHS) {
2943       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2944       return &TheAnd;
2945     }
2946     break;
2947   }
2948   case Instruction::AShr:
2949     // Signed shr.
2950     // See if this is shifting in some sign extension, then masking it out
2951     // with an and.
2952     if (Op->hasOneUse()) {
2953       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2954       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2955       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2956       if (C == AndRHS) {          // Masking out bits shifted in.
2957         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2958         // Make the argument unsigned.
2959         Value *ShVal = Op->getOperand(0);
2960         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2961                                     OpRHS, Op->getName()), TheAnd);
2962         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2963       }
2964     }
2965     break;
2966   }
2967   return 0;
2968 }
2969
2970
2971 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2972 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2973 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2974 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2975 /// insert new instructions.
2976 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2977                                            bool isSigned, bool Inside, 
2978                                            Instruction &IB) {
2979   assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ? 
2980             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
2981          "Lo is not <= Hi in range emission code!");
2982     
2983   if (Inside) {
2984     if (Lo == Hi)  // Trivially false.
2985       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2986
2987     // V >= Min && V < Hi --> V < Hi
2988     if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2989     ICmpInst::Predicate pred = (isSigned ? 
2990         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2991       return new ICmpInst(pred, V, Hi);
2992     }
2993
2994     // Emit V-Lo <u Hi-Lo
2995     Constant *NegLo = ConstantExpr::getNeg(Lo);
2996     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2997     InsertNewInstBefore(Add, IB);
2998     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2999     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3000   }
3001
3002   if (Lo == Hi)  // Trivially true.
3003     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3004
3005   // V < Min || V >= Hi ->'V > Hi-1'
3006   Hi = SubOne(cast<ConstantInt>(Hi));
3007   if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3008     ICmpInst::Predicate pred = (isSigned ? 
3009         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3010     return new ICmpInst(pred, V, Hi);
3011   }
3012
3013   // Emit V-Lo > Hi-1-Lo
3014   Constant *NegLo = ConstantExpr::getNeg(Lo);
3015   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3016   InsertNewInstBefore(Add, IB);
3017   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3018   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3019 }
3020
3021 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3022 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3023 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3024 // not, since all 1s are not contiguous.
3025 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
3026   uint64_t V = Val->getZExtValue();
3027   if (!isShiftedMask_64(V)) return false;
3028
3029   // look for the first zero bit after the run of ones
3030   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3031   // look for the first non-zero bit
3032   ME = 64-CountLeadingZeros_64(V);
3033   return true;
3034 }
3035
3036
3037
3038 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3039 /// where isSub determines whether the operator is a sub.  If we can fold one of
3040 /// the following xforms:
3041 /// 
3042 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3043 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3044 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3045 ///
3046 /// return (A +/- B).
3047 ///
3048 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3049                                         ConstantIntegral *Mask, bool isSub,
3050                                         Instruction &I) {
3051   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3052   if (!LHSI || LHSI->getNumOperands() != 2 ||
3053       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3054
3055   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3056
3057   switch (LHSI->getOpcode()) {
3058   default: return 0;
3059   case Instruction::And:
3060     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3061       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3062       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3063         break;
3064
3065       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3066       // part, we don't need any explicit masks to take them out of A.  If that
3067       // is all N is, ignore it.
3068       unsigned MB, ME;
3069       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3070         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3071         Mask >>= 64-MB+1;
3072         if (MaskedValueIsZero(RHS, Mask))
3073           break;
3074       }
3075     }
3076     return 0;
3077   case Instruction::Or:
3078   case Instruction::Xor:
3079     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3080     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3081         ConstantExpr::getAnd(N, Mask)->isNullValue())
3082       break;
3083     return 0;
3084   }
3085   
3086   Instruction *New;
3087   if (isSub)
3088     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3089   else
3090     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3091   return InsertNewInstBefore(New, I);
3092 }
3093
3094 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3095   bool Changed = SimplifyCommutative(I);
3096   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3097
3098   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3099     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3100
3101   // and X, X = X
3102   if (Op0 == Op1)
3103     return ReplaceInstUsesWith(I, Op1);
3104
3105   // See if we can simplify any instructions used by the instruction whose sole 
3106   // purpose is to compute bits we don't care about.
3107   uint64_t KnownZero, KnownOne;
3108   if (!isa<PackedType>(I.getType()) &&
3109       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3110                            KnownZero, KnownOne))
3111     return &I;
3112   
3113   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3114     uint64_t AndRHSMask = AndRHS->getZExtValue();
3115     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3116     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3117
3118     // Optimize a variety of ((val OP C1) & C2) combinations...
3119     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3120       Instruction *Op0I = cast<Instruction>(Op0);
3121       Value *Op0LHS = Op0I->getOperand(0);
3122       Value *Op0RHS = Op0I->getOperand(1);
3123       switch (Op0I->getOpcode()) {
3124       case Instruction::Xor:
3125       case Instruction::Or:
3126         // If the mask is only needed on one incoming arm, push it up.
3127         if (Op0I->hasOneUse()) {
3128           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3129             // Not masking anything out for the LHS, move to RHS.
3130             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3131                                                    Op0RHS->getName()+".masked");
3132             InsertNewInstBefore(NewRHS, I);
3133             return BinaryOperator::create(
3134                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3135           }
3136           if (!isa<Constant>(Op0RHS) &&
3137               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3138             // Not masking anything out for the RHS, move to LHS.
3139             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3140                                                    Op0LHS->getName()+".masked");
3141             InsertNewInstBefore(NewLHS, I);
3142             return BinaryOperator::create(
3143                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3144           }
3145         }
3146
3147         break;
3148       case Instruction::Add:
3149         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3150         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3151         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3152         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3153           return BinaryOperator::createAnd(V, AndRHS);
3154         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3155           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3156         break;
3157
3158       case Instruction::Sub:
3159         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3160         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3161         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3162         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3163           return BinaryOperator::createAnd(V, AndRHS);
3164         break;
3165       }
3166
3167       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3168         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3169           return Res;
3170     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3171       // If this is an integer truncation or change from signed-to-unsigned, and
3172       // if the source is an and/or with immediate, transform it.  This
3173       // frequently occurs for bitfield accesses.
3174       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3175         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3176             CastOp->getNumOperands() == 2)
3177           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3178             if (CastOp->getOpcode() == Instruction::And) {
3179               // Change: and (cast (and X, C1) to T), C2
3180               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3181               // This will fold the two constants together, which may allow 
3182               // other simplifications.
3183               Instruction *NewCast = CastInst::createTruncOrBitCast(
3184                 CastOp->getOperand(0), I.getType(), 
3185                 CastOp->getName()+".shrunk");
3186               NewCast = InsertNewInstBefore(NewCast, I);
3187               // trunc_or_bitcast(C1)&C2
3188               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3189               C3 = ConstantExpr::getAnd(C3, AndRHS);
3190               return BinaryOperator::createAnd(NewCast, C3);
3191             } else if (CastOp->getOpcode() == Instruction::Or) {
3192               // Change: and (cast (or X, C1) to T), C2
3193               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3194               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3195               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3196                 return ReplaceInstUsesWith(I, AndRHS);
3197             }
3198       }
3199     }
3200
3201     // Try to fold constant and into select arguments.
3202     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3203       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3204         return R;
3205     if (isa<PHINode>(Op0))
3206       if (Instruction *NV = FoldOpIntoPhi(I))
3207         return NV;
3208   }
3209
3210   Value *Op0NotVal = dyn_castNotVal(Op0);
3211   Value *Op1NotVal = dyn_castNotVal(Op1);
3212
3213   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3214     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3215
3216   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3217   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3218     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3219                                                I.getName()+".demorgan");
3220     InsertNewInstBefore(Or, I);
3221     return BinaryOperator::createNot(Or);
3222   }
3223   
3224   {
3225     Value *A = 0, *B = 0;
3226     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3227       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3228         return ReplaceInstUsesWith(I, Op1);
3229     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3230       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3231         return ReplaceInstUsesWith(I, Op0);
3232     
3233     if (Op0->hasOneUse() &&
3234         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3235       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3236         I.swapOperands();     // Simplify below
3237         std::swap(Op0, Op1);
3238       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3239         cast<BinaryOperator>(Op0)->swapOperands();
3240         I.swapOperands();     // Simplify below
3241         std::swap(Op0, Op1);
3242       }
3243     }
3244     if (Op1->hasOneUse() &&
3245         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3246       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3247         cast<BinaryOperator>(Op1)->swapOperands();
3248         std::swap(A, B);
3249       }
3250       if (A == Op0) {                                // A&(A^B) -> A & ~B
3251         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3252         InsertNewInstBefore(NotB, I);
3253         return BinaryOperator::createAnd(A, NotB);
3254       }
3255     }
3256   }
3257   
3258   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3259     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3260     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3261       return R;
3262
3263     Value *LHSVal, *RHSVal;
3264     ConstantInt *LHSCst, *RHSCst;
3265     ICmpInst::Predicate LHSCC, RHSCC;
3266     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3267       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3268         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3269             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3270             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3271             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3272             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3273             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3274           // Ensure that the larger constant is on the RHS.
3275           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3276             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3277           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3278           ICmpInst *LHS = cast<ICmpInst>(Op0);
3279           if (cast<ConstantBool>(Cmp)->getValue()) {
3280             std::swap(LHS, RHS);
3281             std::swap(LHSCst, RHSCst);
3282             std::swap(LHSCC, RHSCC);
3283           }
3284
3285           // At this point, we know we have have two icmp instructions
3286           // comparing a value against two constants and and'ing the result
3287           // together.  Because of the above check, we know that we only have
3288           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3289           // (from the FoldICmpLogical check above), that the two constants 
3290           // are not equal and that the larger constant is on the RHS
3291           assert(LHSCst != RHSCst && "Compares not folded above?");
3292
3293           switch (LHSCC) {
3294           default: assert(0 && "Unknown integer condition code!");
3295           case ICmpInst::ICMP_EQ:
3296             switch (RHSCC) {
3297             default: assert(0 && "Unknown integer condition code!");
3298             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3299             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3300             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3301               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3302             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3303             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3304             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3305               return ReplaceInstUsesWith(I, LHS);
3306             }
3307           case ICmpInst::ICMP_NE:
3308             switch (RHSCC) {
3309             default: assert(0 && "Unknown integer condition code!");
3310             case ICmpInst::ICMP_ULT:
3311               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3312                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3313               break;                        // (X != 13 & X u< 15) -> no change
3314             case ICmpInst::ICMP_SLT:
3315               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3316                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3317               break;                        // (X != 13 & X s< 15) -> no change
3318             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3319             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3320             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3321               return ReplaceInstUsesWith(I, RHS);
3322             case ICmpInst::ICMP_NE:
3323               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3324                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3325                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3326                                                       LHSVal->getName()+".off");
3327                 InsertNewInstBefore(Add, I);
3328                 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3329               }
3330               break;                        // (X != 13 & X != 15) -> no change
3331             }
3332             break;
3333           case ICmpInst::ICMP_ULT:
3334             switch (RHSCC) {
3335             default: assert(0 && "Unknown integer condition code!");
3336             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3337             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3338               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3339             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3340               break;
3341             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3342             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3343               return ReplaceInstUsesWith(I, LHS);
3344             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3345               break;
3346             }
3347             break;
3348           case ICmpInst::ICMP_SLT:
3349             switch (RHSCC) {
3350             default: assert(0 && "Unknown integer condition code!");
3351             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3352             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3353               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3354             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3355               break;
3356             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3357             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3358               return ReplaceInstUsesWith(I, LHS);
3359             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3360               break;
3361             }
3362             break;
3363           case ICmpInst::ICMP_UGT:
3364             switch (RHSCC) {
3365             default: assert(0 && "Unknown integer condition code!");
3366             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3367               return ReplaceInstUsesWith(I, LHS);
3368             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3369               return ReplaceInstUsesWith(I, RHS);
3370             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3371               break;
3372             case ICmpInst::ICMP_NE:
3373               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3374                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3375               break;                        // (X u> 13 & X != 15) -> no change
3376             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3377               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3378                                      true, I);
3379             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3380               break;
3381             }
3382             break;
3383           case ICmpInst::ICMP_SGT:
3384             switch (RHSCC) {
3385             default: assert(0 && "Unknown integer condition code!");
3386             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3387               return ReplaceInstUsesWith(I, LHS);
3388             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3389               return ReplaceInstUsesWith(I, RHS);
3390             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3391               break;
3392             case ICmpInst::ICMP_NE:
3393               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3394                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3395               break;                        // (X s> 13 & X != 15) -> no change
3396             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3397               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3398                                      true, I);
3399             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3400               break;
3401             }
3402             break;
3403           }
3404         }
3405   }
3406
3407   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3408   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3409     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3410       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3411         const Type *SrcTy = Op0C->getOperand(0)->getType();
3412         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3413             // Only do this if the casts both really cause code to be generated.
3414             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3415                               I.getType(), TD) &&
3416             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3417                               I.getType(), TD)) {
3418           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3419                                                          Op1C->getOperand(0),
3420                                                          I.getName());
3421           InsertNewInstBefore(NewOp, I);
3422           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3423         }
3424       }
3425     
3426   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3427   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3428     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3429       if (SI0->getOpcode() == SI1->getOpcode() && 
3430           SI0->getOperand(1) == SI1->getOperand(1) &&
3431           (SI0->hasOneUse() || SI1->hasOneUse())) {
3432         Instruction *NewOp =
3433           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3434                                                         SI1->getOperand(0),
3435                                                         SI0->getName()), I);
3436         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3437       }
3438   }
3439
3440   return Changed ? &I : 0;
3441 }
3442
3443 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3444 /// in the result.  If it does, and if the specified byte hasn't been filled in
3445 /// yet, fill it in and return false.
3446 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3447   Instruction *I = dyn_cast<Instruction>(V);
3448   if (I == 0) return true;
3449
3450   // If this is an or instruction, it is an inner node of the bswap.
3451   if (I->getOpcode() == Instruction::Or)
3452     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3453            CollectBSwapParts(I->getOperand(1), ByteValues);
3454   
3455   // If this is a shift by a constant int, and it is "24", then its operand
3456   // defines a byte.  We only handle unsigned types here.
3457   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3458     // Not shifting the entire input by N-1 bytes?
3459     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3460         8*(ByteValues.size()-1))
3461       return true;
3462     
3463     unsigned DestNo;
3464     if (I->getOpcode() == Instruction::Shl) {
3465       // X << 24 defines the top byte with the lowest of the input bytes.
3466       DestNo = ByteValues.size()-1;
3467     } else {
3468       // X >>u 24 defines the low byte with the highest of the input bytes.
3469       DestNo = 0;
3470     }
3471     
3472     // If the destination byte value is already defined, the values are or'd
3473     // together, which isn't a bswap (unless it's an or of the same bits).
3474     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3475       return true;
3476     ByteValues[DestNo] = I->getOperand(0);
3477     return false;
3478   }
3479   
3480   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3481   // don't have this.
3482   Value *Shift = 0, *ShiftLHS = 0;
3483   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3484   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3485       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3486     return true;
3487   Instruction *SI = cast<Instruction>(Shift);
3488
3489   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3490   if (ShiftAmt->getZExtValue() & 7 ||
3491       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3492     return true;
3493   
3494   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3495   unsigned DestByte;
3496   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3497     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3498       break;
3499   // Unknown mask for bswap.
3500   if (DestByte == ByteValues.size()) return true;
3501   
3502   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3503   unsigned SrcByte;
3504   if (SI->getOpcode() == Instruction::Shl)
3505     SrcByte = DestByte - ShiftBytes;
3506   else
3507     SrcByte = DestByte + ShiftBytes;
3508   
3509   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3510   if (SrcByte != ByteValues.size()-DestByte-1)
3511     return true;
3512   
3513   // If the destination byte value is already defined, the values are or'd
3514   // together, which isn't a bswap (unless it's an or of the same bits).
3515   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3516     return true;
3517   ByteValues[DestByte] = SI->getOperand(0);
3518   return false;
3519 }
3520
3521 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3522 /// If so, insert the new bswap intrinsic and return it.
3523 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3524   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3525   if (I.getType() == Type::Int8Ty)
3526     return 0;
3527   
3528   /// ByteValues - For each byte of the result, we keep track of which value
3529   /// defines each byte.
3530   std::vector<Value*> ByteValues;
3531   ByteValues.resize(I.getType()->getPrimitiveSize());
3532     
3533   // Try to find all the pieces corresponding to the bswap.
3534   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3535       CollectBSwapParts(I.getOperand(1), ByteValues))
3536     return 0;
3537   
3538   // Check to see if all of the bytes come from the same value.
3539   Value *V = ByteValues[0];
3540   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3541   
3542   // Check to make sure that all of the bytes come from the same value.
3543   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3544     if (ByteValues[i] != V)
3545       return 0;
3546     
3547   // If they do then *success* we can turn this into a bswap.  Figure out what
3548   // bswap to make it into.
3549   Module *M = I.getParent()->getParent()->getParent();
3550   const char *FnName = 0;
3551   if (I.getType() == Type::Int16Ty)
3552     FnName = "llvm.bswap.i16";
3553   else if (I.getType() == Type::Int32Ty)
3554     FnName = "llvm.bswap.i32";
3555   else if (I.getType() == Type::Int64Ty)
3556     FnName = "llvm.bswap.i64";
3557   else
3558     assert(0 && "Unknown integer type!");
3559   Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3560   
3561   return new CallInst(F, V);
3562 }
3563
3564
3565 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3566   bool Changed = SimplifyCommutative(I);
3567   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3568
3569   if (isa<UndefValue>(Op1))
3570     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3571                                ConstantIntegral::getAllOnesValue(I.getType()));
3572
3573   // or X, X = X
3574   if (Op0 == Op1)
3575     return ReplaceInstUsesWith(I, Op0);
3576
3577   // See if we can simplify any instructions used by the instruction whose sole 
3578   // purpose is to compute bits we don't care about.
3579   uint64_t KnownZero, KnownOne;
3580   if (!isa<PackedType>(I.getType()) &&
3581       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3582                            KnownZero, KnownOne))
3583     return &I;
3584   
3585   // or X, -1 == -1
3586   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3587     ConstantInt *C1 = 0; Value *X = 0;
3588     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3589     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3590       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3591       Op0->setName("");
3592       InsertNewInstBefore(Or, I);
3593       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3594     }
3595
3596     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3597     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3598       std::string Op0Name = Op0->getName(); Op0->setName("");
3599       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3600       InsertNewInstBefore(Or, I);
3601       return BinaryOperator::createXor(Or,
3602                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3603     }
3604
3605     // Try to fold constant and into select arguments.
3606     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3607       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3608         return R;
3609     if (isa<PHINode>(Op0))
3610       if (Instruction *NV = FoldOpIntoPhi(I))
3611         return NV;
3612   }
3613
3614   Value *A = 0, *B = 0;
3615   ConstantInt *C1 = 0, *C2 = 0;
3616
3617   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3618     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3619       return ReplaceInstUsesWith(I, Op1);
3620   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3621     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3622       return ReplaceInstUsesWith(I, Op0);
3623
3624   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3625   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3626   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3627       match(Op1, m_Or(m_Value(), m_Value())) ||
3628       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3629        match(Op1, m_Shift(m_Value(), m_Value())))) {
3630     if (Instruction *BSwap = MatchBSwap(I))
3631       return BSwap;
3632   }
3633   
3634   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3635   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3636       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3637     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3638     Op0->setName("");
3639     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3640   }
3641
3642   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3643   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3644       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3645     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3646     Op0->setName("");
3647     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3648   }
3649
3650   // (A & C1)|(B & C2)
3651   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3652       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3653
3654     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3655       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3656
3657
3658     // If we have: ((V + N) & C1) | (V & C2)
3659     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3660     // replace with V+N.
3661     if (C1 == ConstantExpr::getNot(C2)) {
3662       Value *V1 = 0, *V2 = 0;
3663       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3664           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3665         // Add commutes, try both ways.
3666         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3667           return ReplaceInstUsesWith(I, A);
3668         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3669           return ReplaceInstUsesWith(I, A);
3670       }
3671       // Or commutes, try both ways.
3672       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3673           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3674         // Add commutes, try both ways.
3675         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3676           return ReplaceInstUsesWith(I, B);
3677         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3678           return ReplaceInstUsesWith(I, B);
3679       }
3680     }
3681   }
3682   
3683   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3684   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3685     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3686       if (SI0->getOpcode() == SI1->getOpcode() && 
3687           SI0->getOperand(1) == SI1->getOperand(1) &&
3688           (SI0->hasOneUse() || SI1->hasOneUse())) {
3689         Instruction *NewOp =
3690         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3691                                                      SI1->getOperand(0),
3692                                                      SI0->getName()), I);
3693         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3694       }
3695   }
3696
3697   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3698     if (A == Op1)   // ~A | A == -1
3699       return ReplaceInstUsesWith(I,
3700                                 ConstantIntegral::getAllOnesValue(I.getType()));
3701   } else {
3702     A = 0;
3703   }
3704   // Note, A is still live here!
3705   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3706     if (Op0 == B)
3707       return ReplaceInstUsesWith(I,
3708                                 ConstantIntegral::getAllOnesValue(I.getType()));
3709
3710     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3711     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3712       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3713                                               I.getName()+".demorgan"), I);
3714       return BinaryOperator::createNot(And);
3715     }
3716   }
3717
3718   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3719   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3720     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3721       return R;
3722
3723     Value *LHSVal, *RHSVal;
3724     ConstantInt *LHSCst, *RHSCst;
3725     ICmpInst::Predicate LHSCC, RHSCC;
3726     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3727       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3728         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3729             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3730             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3731             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3732             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3733             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3734           // Ensure that the larger constant is on the RHS.
3735           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3736             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3737           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3738           ICmpInst *LHS = cast<ICmpInst>(Op0);
3739           if (cast<ConstantBool>(Cmp)->getValue()) {
3740             std::swap(LHS, RHS);
3741             std::swap(LHSCst, RHSCst);
3742             std::swap(LHSCC, RHSCC);
3743           }
3744
3745           // At this point, we know we have have two icmp instructions
3746           // comparing a value against two constants and or'ing the result
3747           // together.  Because of the above check, we know that we only have
3748           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3749           // FoldICmpLogical check above), that the two constants are not
3750           // equal.
3751           assert(LHSCst != RHSCst && "Compares not folded above?");
3752
3753           switch (LHSCC) {
3754           default: assert(0 && "Unknown integer condition code!");
3755           case ICmpInst::ICMP_EQ:
3756             switch (RHSCC) {
3757             default: assert(0 && "Unknown integer condition code!");
3758             case ICmpInst::ICMP_EQ:
3759               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3760                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3761                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3762                                                       LHSVal->getName()+".off");
3763                 InsertNewInstBefore(Add, I);
3764                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3765                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3766               }
3767               break;                         // (X == 13 | X == 15) -> no change
3768             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3769             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3770               break;
3771             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3772             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3773             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3774               return ReplaceInstUsesWith(I, RHS);
3775             }
3776             break;
3777           case ICmpInst::ICMP_NE:
3778             switch (RHSCC) {
3779             default: assert(0 && "Unknown integer condition code!");
3780             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3781             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3782             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3783               return ReplaceInstUsesWith(I, LHS);
3784             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3785             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3786             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3787               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3788             }
3789             break;
3790           case ICmpInst::ICMP_ULT:
3791             switch (RHSCC) {
3792             default: assert(0 && "Unknown integer condition code!");
3793             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3794               break;
3795             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3796               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3797                                      false, I);
3798             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3799               break;
3800             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3801             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3802               return ReplaceInstUsesWith(I, RHS);
3803             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3804               break;
3805             }
3806             break;
3807           case ICmpInst::ICMP_SLT:
3808             switch (RHSCC) {
3809             default: assert(0 && "Unknown integer condition code!");
3810             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3811               break;
3812             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3813               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3814                                      false, I);
3815             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3816               break;
3817             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3818             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3819               return ReplaceInstUsesWith(I, RHS);
3820             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3821               break;
3822             }
3823             break;
3824           case ICmpInst::ICMP_UGT:
3825             switch (RHSCC) {
3826             default: assert(0 && "Unknown integer condition code!");
3827             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3828             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3829               return ReplaceInstUsesWith(I, LHS);
3830             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3831               break;
3832             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3833             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3834               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3835             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3836               break;
3837             }
3838             break;
3839           case ICmpInst::ICMP_SGT:
3840             switch (RHSCC) {
3841             default: assert(0 && "Unknown integer condition code!");
3842             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3843             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3844               return ReplaceInstUsesWith(I, LHS);
3845             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3846               break;
3847             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3848             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3849               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3850             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3851               break;
3852             }
3853             break;
3854           }
3855         }
3856   }
3857     
3858   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3859   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3860     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3861       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3862         const Type *SrcTy = Op0C->getOperand(0)->getType();
3863         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3864             // Only do this if the casts both really cause code to be generated.
3865             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3866                               I.getType(), TD) &&
3867             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3868                               I.getType(), TD)) {
3869           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3870                                                         Op1C->getOperand(0),
3871                                                         I.getName());
3872           InsertNewInstBefore(NewOp, I);
3873           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3874         }
3875       }
3876       
3877
3878   return Changed ? &I : 0;
3879 }
3880
3881 // XorSelf - Implements: X ^ X --> 0
3882 struct XorSelf {
3883   Value *RHS;
3884   XorSelf(Value *rhs) : RHS(rhs) {}
3885   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3886   Instruction *apply(BinaryOperator &Xor) const {
3887     return &Xor;
3888   }
3889 };
3890
3891
3892 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3893   bool Changed = SimplifyCommutative(I);
3894   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3895
3896   if (isa<UndefValue>(Op1))
3897     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3898
3899   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3900   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3901     assert(Result == &I && "AssociativeOpt didn't work?");
3902     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3903   }
3904   
3905   // See if we can simplify any instructions used by the instruction whose sole 
3906   // purpose is to compute bits we don't care about.
3907   uint64_t KnownZero, KnownOne;
3908   if (!isa<PackedType>(I.getType()) &&
3909       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3910                            KnownZero, KnownOne))
3911     return &I;
3912
3913   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3914     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3915     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3916       if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3917         return new ICmpInst(ICI->getInversePredicate(),
3918                             ICI->getOperand(0), ICI->getOperand(1));
3919
3920     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3921       // ~(c-X) == X-c-1 == X+(-c-1)
3922       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3923         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3924           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3925           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3926                                               ConstantInt::get(I.getType(), 1));
3927           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3928         }
3929
3930       // ~(~X & Y) --> (X | ~Y)
3931       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3932         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3933         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3934           Instruction *NotY =
3935             BinaryOperator::createNot(Op0I->getOperand(1),
3936                                       Op0I->getOperand(1)->getName()+".not");
3937           InsertNewInstBefore(NotY, I);
3938           return BinaryOperator::createOr(Op0NotVal, NotY);
3939         }
3940       }
3941
3942       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3943         if (Op0I->getOpcode() == Instruction::Add) {
3944           // ~(X-c) --> (-c-1)-X
3945           if (RHS->isAllOnesValue()) {
3946             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3947             return BinaryOperator::createSub(
3948                            ConstantExpr::getSub(NegOp0CI,
3949                                              ConstantInt::get(I.getType(), 1)),
3950                                           Op0I->getOperand(0));
3951           }
3952         } else if (Op0I->getOpcode() == Instruction::Or) {
3953           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3954           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3955             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3956             // Anything in both C1 and C2 is known to be zero, remove it from
3957             // NewRHS.
3958             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3959             NewRHS = ConstantExpr::getAnd(NewRHS, 
3960                                           ConstantExpr::getNot(CommonBits));
3961             WorkList.push_back(Op0I);
3962             I.setOperand(0, Op0I->getOperand(0));
3963             I.setOperand(1, NewRHS);
3964             return &I;
3965           }
3966         }
3967     }
3968
3969     // Try to fold constant and into select arguments.
3970     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3971       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3972         return R;
3973     if (isa<PHINode>(Op0))
3974       if (Instruction *NV = FoldOpIntoPhi(I))
3975         return NV;
3976   }
3977
3978   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3979     if (X == Op1)
3980       return ReplaceInstUsesWith(I,
3981                                 ConstantIntegral::getAllOnesValue(I.getType()));
3982
3983   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3984     if (X == Op0)
3985       return ReplaceInstUsesWith(I,
3986                                 ConstantIntegral::getAllOnesValue(I.getType()));
3987
3988   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3989     if (Op1I->getOpcode() == Instruction::Or) {
3990       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3991         Op1I->swapOperands();
3992         I.swapOperands();
3993         std::swap(Op0, Op1);
3994       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3995         I.swapOperands();     // Simplified below.
3996         std::swap(Op0, Op1);
3997       }
3998     } else if (Op1I->getOpcode() == Instruction::Xor) {
3999       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
4000         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4001       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
4002         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
4003     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4004       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
4005         Op1I->swapOperands();
4006       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
4007         I.swapOperands();     // Simplified below.
4008         std::swap(Op0, Op1);
4009       }
4010     }
4011
4012   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4013     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4014       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4015         Op0I->swapOperands();
4016       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4017         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4018         InsertNewInstBefore(NotB, I);
4019         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4020       }
4021     } else if (Op0I->getOpcode() == Instruction::Xor) {
4022       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4023         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4024       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4025         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4026     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4027       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4028         Op0I->swapOperands();
4029       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4030           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4031         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4032         InsertNewInstBefore(N, I);
4033         return BinaryOperator::createAnd(N, Op1);
4034       }
4035     }
4036
4037   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4038   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4039     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4040       return R;
4041
4042   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4043   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4044     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4045       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4046         const Type *SrcTy = Op0C->getOperand(0)->getType();
4047         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4048             // Only do this if the casts both really cause code to be generated.
4049             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4050                               I.getType(), TD) &&
4051             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4052                               I.getType(), TD)) {
4053           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4054                                                          Op1C->getOperand(0),
4055                                                          I.getName());
4056           InsertNewInstBefore(NewOp, I);
4057           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4058         }
4059       }
4060
4061   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4062   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4063     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4064       if (SI0->getOpcode() == SI1->getOpcode() && 
4065           SI0->getOperand(1) == SI1->getOperand(1) &&
4066           (SI0->hasOneUse() || SI1->hasOneUse())) {
4067         Instruction *NewOp =
4068         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4069                                                       SI1->getOperand(0),
4070                                                       SI0->getName()), I);
4071         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4072       }
4073   }
4074     
4075   return Changed ? &I : 0;
4076 }
4077
4078 static bool isPositive(ConstantInt *C) {
4079   return C->getSExtValue() >= 0;
4080 }
4081
4082 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4083 /// overflowed for this type.
4084 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4085                             ConstantInt *In2) {
4086   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4087
4088   return cast<ConstantInt>(Result)->getZExtValue() <
4089          cast<ConstantInt>(In1)->getZExtValue();
4090 }
4091
4092 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4093 /// code necessary to compute the offset from the base pointer (without adding
4094 /// in the base pointer).  Return the result as a signed integer of intptr size.
4095 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4096   TargetData &TD = IC.getTargetData();
4097   gep_type_iterator GTI = gep_type_begin(GEP);
4098   const Type *IntPtrTy = TD.getIntPtrType();
4099   Value *Result = Constant::getNullValue(IntPtrTy);
4100
4101   // Build a mask for high order bits.
4102   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4103
4104   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4105     Value *Op = GEP->getOperand(i);
4106     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4107     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4108     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4109       if (!OpC->isNullValue()) {
4110         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4111         Scale = ConstantExpr::getMul(OpC, Scale);
4112         if (Constant *RC = dyn_cast<Constant>(Result))
4113           Result = ConstantExpr::getAdd(RC, Scale);
4114         else {
4115           // Emit an add instruction.
4116           Result = IC.InsertNewInstBefore(
4117              BinaryOperator::createAdd(Result, Scale,
4118                                        GEP->getName()+".offs"), I);
4119         }
4120       }
4121     } else {
4122       // Convert to correct type.
4123       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4124                                                Op->getName()+".c"), I);
4125       if (Size != 1)
4126         // We'll let instcombine(mul) convert this to a shl if possible.
4127         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4128                                                     GEP->getName()+".idx"), I);
4129
4130       // Emit an add instruction.
4131       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4132                                                     GEP->getName()+".offs"), I);
4133     }
4134   }
4135   return Result;
4136 }
4137
4138 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4139 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4140 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4141                                        ICmpInst::Predicate Cond,
4142                                        Instruction &I) {
4143   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4144
4145   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4146     if (isa<PointerType>(CI->getOperand(0)->getType()))
4147       RHS = CI->getOperand(0);
4148
4149   Value *PtrBase = GEPLHS->getOperand(0);
4150   if (PtrBase == RHS) {
4151     // As an optimization, we don't actually have to compute the actual value of
4152     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4153     // each index is zero or not.
4154     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4155       Instruction *InVal = 0;
4156       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4157       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4158         bool EmitIt = true;
4159         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4160           if (isa<UndefValue>(C))  // undef index -> undef.
4161             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4162           if (C->isNullValue())
4163             EmitIt = false;
4164           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4165             EmitIt = false;  // This is indexing into a zero sized array?
4166           } else if (isa<ConstantInt>(C))
4167             return ReplaceInstUsesWith(I, // No comparison is needed here.
4168                                  ConstantBool::get(Cond == ICmpInst::ICMP_NE));
4169         }
4170
4171         if (EmitIt) {
4172           Instruction *Comp =
4173             new ICmpInst(Cond, GEPLHS->getOperand(i),
4174                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4175           if (InVal == 0)
4176             InVal = Comp;
4177           else {
4178             InVal = InsertNewInstBefore(InVal, I);
4179             InsertNewInstBefore(Comp, I);
4180             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4181               InVal = BinaryOperator::createOr(InVal, Comp);
4182             else                              // True if all are equal
4183               InVal = BinaryOperator::createAnd(InVal, Comp);
4184           }
4185         }
4186       }
4187
4188       if (InVal)
4189         return InVal;
4190       else
4191         // No comparison is needed here, all indexes = 0
4192         ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4193     }
4194
4195     // Only lower this if the icmp is the only user of the GEP or if we expect
4196     // the result to fold to a constant!
4197     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4198       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4199       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4200       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4201                           Constant::getNullValue(Offset->getType()));
4202     }
4203   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4204     // If the base pointers are different, but the indices are the same, just
4205     // compare the base pointer.
4206     if (PtrBase != GEPRHS->getOperand(0)) {
4207       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4208       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4209                         GEPRHS->getOperand(0)->getType();
4210       if (IndicesTheSame)
4211         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4212           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4213             IndicesTheSame = false;
4214             break;
4215           }
4216
4217       // If all indices are the same, just compare the base pointers.
4218       if (IndicesTheSame)
4219         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4220                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4221
4222       // Otherwise, the base pointers are different and the indices are
4223       // different, bail out.
4224       return 0;
4225     }
4226
4227     // If one of the GEPs has all zero indices, recurse.
4228     bool AllZeros = true;
4229     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4230       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4231           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4232         AllZeros = false;
4233         break;
4234       }
4235     if (AllZeros)
4236       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4237                           ICmpInst::getSwappedPredicate(Cond), I);
4238
4239     // If the other GEP has all zero indices, recurse.
4240     AllZeros = true;
4241     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4242       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4243           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4244         AllZeros = false;
4245         break;
4246       }
4247     if (AllZeros)
4248       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4249
4250     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4251       // If the GEPs only differ by one index, compare it.
4252       unsigned NumDifferences = 0;  // Keep track of # differences.
4253       unsigned DiffOperand = 0;     // The operand that differs.
4254       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4255         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4256           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4257                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4258             // Irreconcilable differences.
4259             NumDifferences = 2;
4260             break;
4261           } else {
4262             if (NumDifferences++) break;
4263             DiffOperand = i;
4264           }
4265         }
4266
4267       if (NumDifferences == 0)   // SAME GEP?
4268         return ReplaceInstUsesWith(I, // No comparison is needed here.
4269                                  ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4270       else if (NumDifferences == 1) {
4271         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4272         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4273         // Make sure we do a signed comparison here.
4274         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4275       }
4276     }
4277
4278     // Only lower this if the icmp is the only user of the GEP or if we expect
4279     // the result to fold to a constant!
4280     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4281         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4282       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4283       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4284       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4285       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4286     }
4287   }
4288   return 0;
4289 }
4290
4291 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4292   bool Changed = SimplifyCompare(I);
4293   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4294
4295   // fcmp pred X, X
4296   if (Op0 == Op1)
4297     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4298
4299   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4300     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4301
4302   // Handle fcmp with constant RHS
4303   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4304     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4305       switch (LHSI->getOpcode()) {
4306       case Instruction::PHI:
4307         if (Instruction *NV = FoldOpIntoPhi(I))
4308           return NV;
4309         break;
4310       case Instruction::Select:
4311         // If either operand of the select is a constant, we can fold the
4312         // comparison into the select arms, which will cause one to be
4313         // constant folded and the select turned into a bitwise or.
4314         Value *Op1 = 0, *Op2 = 0;
4315         if (LHSI->hasOneUse()) {
4316           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4317             // Fold the known value into the constant operand.
4318             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4319             // Insert a new FCmp of the other select operand.
4320             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4321                                                       LHSI->getOperand(2), RHSC,
4322                                                       I.getName()), I);
4323           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4324             // Fold the known value into the constant operand.
4325             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4326             // Insert a new FCmp of the other select operand.
4327             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4328                                                       LHSI->getOperand(1), RHSC,
4329                                                       I.getName()), I);
4330           }
4331         }
4332
4333         if (Op1)
4334           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4335         break;
4336       }
4337   }
4338
4339   return Changed ? &I : 0;
4340 }
4341
4342 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4343   bool Changed = SimplifyCompare(I);
4344   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4345   const Type *Ty = Op0->getType();
4346
4347   // icmp X, X
4348   if (Op0 == Op1)
4349     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4350
4351   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4352     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4353
4354   // icmp of GlobalValues can never equal each other as long as they aren't
4355   // external weak linkage type.
4356   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4357     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4358       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4359         return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4360
4361   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4362   // addresses never equal each other!  We already know that Op0 != Op1.
4363   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4364        isa<ConstantPointerNull>(Op0)) &&
4365       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4366        isa<ConstantPointerNull>(Op1)))
4367     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4368
4369   // icmp's with boolean values can always be turned into bitwise operations
4370   if (Ty == Type::BoolTy) {
4371     switch (I.getPredicate()) {
4372     default: assert(0 && "Invalid icmp instruction!");
4373     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4374       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4375       InsertNewInstBefore(Xor, I);
4376       return BinaryOperator::createNot(Xor);
4377     }
4378     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4379       return BinaryOperator::createXor(Op0, Op1);
4380
4381     case ICmpInst::ICMP_UGT:
4382     case ICmpInst::ICMP_SGT:
4383       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4384       // FALL THROUGH
4385     case ICmpInst::ICMP_ULT:
4386     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4387       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4388       InsertNewInstBefore(Not, I);
4389       return BinaryOperator::createAnd(Not, Op1);
4390     }
4391     case ICmpInst::ICMP_UGE:
4392     case ICmpInst::ICMP_SGE:
4393       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4394       // FALL THROUGH
4395     case ICmpInst::ICMP_ULE:
4396     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4397       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4398       InsertNewInstBefore(Not, I);
4399       return BinaryOperator::createOr(Not, Op1);
4400     }
4401     }
4402   }
4403
4404   // See if we are doing a comparison between a constant and an instruction that
4405   // can be folded into the comparison.
4406   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4407     switch (I.getPredicate()) {
4408     default: break;
4409     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4410       if (CI->isMinValue(false))
4411         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4412       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4413         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4414       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4415         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4416       break;
4417
4418     case ICmpInst::ICMP_SLT:
4419       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4420         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4421       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4422         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4423       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4424         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4425       break;
4426
4427     case ICmpInst::ICMP_UGT:
4428       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4429         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4430       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4431         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4432       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4433         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4434       break;
4435
4436     case ICmpInst::ICMP_SGT:
4437       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4438         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4439       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4440         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4441       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4442         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4443       break;
4444
4445     case ICmpInst::ICMP_ULE:
4446       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4447         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4448       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4449         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4450       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4451         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4452       break;
4453
4454     case ICmpInst::ICMP_SLE:
4455       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4456         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4457       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4458         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4459       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4460         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4461       break;
4462
4463     case ICmpInst::ICMP_UGE:
4464       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4465         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4466       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4467         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4468       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4469         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4470       break;
4471
4472     case ICmpInst::ICMP_SGE:
4473       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4474         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4475       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4476         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4477       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4478         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4479       break;
4480     }
4481
4482     // If we still have a icmp le or icmp ge instruction, turn it into the
4483     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4484     // already been handled above, this requires little checking.
4485     //
4486     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4487       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4488     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4489       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4490     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4491       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4492     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4493       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4494     
4495     // See if we can fold the comparison based on bits known to be zero or one
4496     // in the input.
4497     uint64_t KnownZero, KnownOne;
4498     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4499                              KnownZero, KnownOne, 0))
4500       return &I;
4501         
4502     // Given the known and unknown bits, compute a range that the LHS could be
4503     // in.
4504     if (KnownOne | KnownZero) {
4505       // Compute the Min, Max and RHS values based on the known bits. For the
4506       // EQ and NE we use unsigned values.
4507       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4508       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4509       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4510         SRHSVal = CI->getSExtValue();
4511         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4512                                                SMax);
4513       } else {
4514         URHSVal = CI->getZExtValue();
4515         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4516                                                  UMax);
4517       }
4518       switch (I.getPredicate()) {  // LE/GE have been folded already.
4519       default: assert(0 && "Unknown icmp opcode!");
4520       case ICmpInst::ICMP_EQ:
4521         if (UMax < URHSVal || UMin > URHSVal)
4522           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4523         break;
4524       case ICmpInst::ICMP_NE:
4525         if (UMax < URHSVal || UMin > URHSVal)
4526           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4527         break;
4528       case ICmpInst::ICMP_ULT:
4529         if (UMax < URHSVal)
4530           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4531         if (UMin > URHSVal)
4532           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4533         break;
4534       case ICmpInst::ICMP_UGT:
4535         if (UMin > URHSVal)
4536           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4537         if (UMax < URHSVal)
4538           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4539         break;
4540       case ICmpInst::ICMP_SLT:
4541         if (SMax < SRHSVal)
4542           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4543         if (SMin > SRHSVal)
4544           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4545         break;
4546       case ICmpInst::ICMP_SGT: 
4547         if (SMin > SRHSVal)
4548           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4549         if (SMax < SRHSVal)
4550           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4551         break;
4552       }
4553     }
4554           
4555     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4556     // instruction, see if that instruction also has constants so that the 
4557     // instruction can be folded into the icmp 
4558     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4559       switch (LHSI->getOpcode()) {
4560       case Instruction::And:
4561         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4562             LHSI->getOperand(0)->hasOneUse()) {
4563           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4564
4565           // If the LHS is an AND of a truncating cast, we can widen the
4566           // and/compare to be the input width without changing the value
4567           // produced, eliminating a cast.
4568           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4569             // We can do this transformation if either the AND constant does not
4570             // have its sign bit set or if it is an equality comparison. 
4571             // Extending a relational comparison when we're checking the sign
4572             // bit would not work.
4573             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4574                 (I.isEquality() ||
4575                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4576                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4577               ConstantInt *NewCST;
4578               ConstantInt *NewCI;
4579               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4580                                          AndCST->getZExtValue());
4581               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4582                                         CI->getZExtValue());
4583               Instruction *NewAnd = 
4584                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4585                                           LHSI->getName());
4586               InsertNewInstBefore(NewAnd, I);
4587               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4588             }
4589           }
4590           
4591           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4592           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4593           // happens a LOT in code produced by the C front-end, for bitfield
4594           // access.
4595           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4596
4597           // Check to see if there is a noop-cast between the shift and the and.
4598           if (!Shift) {
4599             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4600               if (CI->getOpcode() == Instruction::BitCast)
4601                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4602           }
4603
4604           ConstantInt *ShAmt;
4605           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4606           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4607           const Type *AndTy = AndCST->getType();          // Type of the and.
4608
4609           // We can fold this as long as we can't shift unknown bits
4610           // into the mask.  This can only happen with signed shift
4611           // rights, as they sign-extend.
4612           if (ShAmt) {
4613             bool CanFold = Shift->isLogicalShift();
4614             if (!CanFold) {
4615               // To test for the bad case of the signed shr, see if any
4616               // of the bits shifted in could be tested after the mask.
4617               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4618               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4619
4620               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4621               Constant *ShVal =
4622                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4623                                      OShAmt);
4624               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4625                 CanFold = true;
4626             }
4627
4628             if (CanFold) {
4629               Constant *NewCst;
4630               if (Shift->getOpcode() == Instruction::Shl)
4631                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4632               else
4633                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4634
4635               // Check to see if we are shifting out any of the bits being
4636               // compared.
4637               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4638                 // If we shifted bits out, the fold is not going to work out.
4639                 // As a special case, check to see if this means that the
4640                 // result is always true or false now.
4641                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4642                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4643                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4644                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4645               } else {
4646                 I.setOperand(1, NewCst);
4647                 Constant *NewAndCST;
4648                 if (Shift->getOpcode() == Instruction::Shl)
4649                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4650                 else
4651                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4652                 LHSI->setOperand(1, NewAndCST);
4653                 LHSI->setOperand(0, Shift->getOperand(0));
4654                 WorkList.push_back(Shift); // Shift is dead.
4655                 AddUsesToWorkList(I);
4656                 return &I;
4657               }
4658             }
4659           }
4660           
4661           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4662           // preferable because it allows the C<<Y expression to be hoisted out
4663           // of a loop if Y is invariant and X is not.
4664           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4665               I.isEquality() && !Shift->isArithmeticShift() &&
4666               isa<Instruction>(Shift->getOperand(0))) {
4667             // Compute C << Y.
4668             Value *NS;
4669             if (Shift->getOpcode() == Instruction::LShr) {
4670               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4671                                  "tmp");
4672             } else {
4673               // Insert a logical shift.
4674               NS = new ShiftInst(Instruction::LShr, AndCST,
4675                                  Shift->getOperand(1), "tmp");
4676             }
4677             InsertNewInstBefore(cast<Instruction>(NS), I);
4678
4679             // Compute X & (C << Y).
4680             Instruction *NewAnd = BinaryOperator::createAnd(
4681                 Shift->getOperand(0), NS, LHSI->getName());
4682             InsertNewInstBefore(NewAnd, I);
4683             
4684             I.setOperand(0, NewAnd);
4685             return &I;
4686           }
4687         }
4688         break;
4689
4690       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4691         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4692           if (I.isEquality()) {
4693             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4694
4695             // Check that the shift amount is in range.  If not, don't perform
4696             // undefined shifts.  When the shift is visited it will be
4697             // simplified.
4698             if (ShAmt->getZExtValue() >= TypeBits)
4699               break;
4700
4701             // If we are comparing against bits always shifted out, the
4702             // comparison cannot succeed.
4703             Constant *Comp =
4704               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4705             if (Comp != CI) {// Comparing against a bit that we know is zero.
4706               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4707               Constant *Cst = ConstantBool::get(IsICMP_NE);
4708               return ReplaceInstUsesWith(I, Cst);
4709             }
4710
4711             if (LHSI->hasOneUse()) {
4712               // Otherwise strength reduce the shift into an and.
4713               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4714               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4715               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4716
4717               Instruction *AndI =
4718                 BinaryOperator::createAnd(LHSI->getOperand(0),
4719                                           Mask, LHSI->getName()+".mask");
4720               Value *And = InsertNewInstBefore(AndI, I);
4721               return new ICmpInst(I.getPredicate(), And,
4722                                      ConstantExpr::getLShr(CI, ShAmt));
4723             }
4724           }
4725         }
4726         break;
4727
4728       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4729       case Instruction::AShr:
4730         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4731           if (I.isEquality()) {
4732             // Check that the shift amount is in range.  If not, don't perform
4733             // undefined shifts.  When the shift is visited it will be
4734             // simplified.
4735             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4736             if (ShAmt->getZExtValue() >= TypeBits)
4737               break;
4738
4739             // If we are comparing against bits always shifted out, the
4740             // comparison cannot succeed.
4741             Constant *Comp;
4742             if (LHSI->getOpcode() == Instruction::LShr) 
4743               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4744                                            ShAmt);
4745             else
4746               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4747                                            ShAmt);
4748
4749             if (Comp != CI) {// Comparing against a bit that we know is zero.
4750               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4751               Constant *Cst = ConstantBool::get(IsICMP_NE);
4752               return ReplaceInstUsesWith(I, Cst);
4753             }
4754
4755             if (LHSI->hasOneUse() || CI->isNullValue()) {
4756               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4757
4758               // Otherwise strength reduce the shift into an and.
4759               uint64_t Val = ~0ULL;          // All ones.
4760               Val <<= ShAmtVal;              // Shift over to the right spot.
4761               Val &= ~0ULL >> (64-TypeBits);
4762               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4763
4764               Instruction *AndI =
4765                 BinaryOperator::createAnd(LHSI->getOperand(0),
4766                                           Mask, LHSI->getName()+".mask");
4767               Value *And = InsertNewInstBefore(AndI, I);
4768               return new ICmpInst(I.getPredicate(), And,
4769                                      ConstantExpr::getShl(CI, ShAmt));
4770             }
4771           }
4772         }
4773         break;
4774
4775       case Instruction::SDiv:
4776       case Instruction::UDiv:
4777         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4778         // Fold this div into the comparison, producing a range check. 
4779         // Determine, based on the divide type, what the range is being 
4780         // checked.  If there is an overflow on the low or high side, remember 
4781         // it, otherwise compute the range [low, hi) bounding the new value.
4782         // See: InsertRangeTest above for the kinds of replacements possible.
4783         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4784           // FIXME: If the operand types don't match the type of the divide 
4785           // then don't attempt this transform. The code below doesn't have the
4786           // logic to deal with a signed divide and an unsigned compare (and
4787           // vice versa). This is because (x /s C1) <s C2  produces different 
4788           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4789           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4790           // work. :(  The if statement below tests that condition and bails 
4791           // if it finds it. 
4792           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4793           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4794             break;
4795
4796           // Initialize the variables that will indicate the nature of the
4797           // range check.
4798           bool LoOverflow = false, HiOverflow = false;
4799           ConstantInt *LoBound = 0, *HiBound = 0;
4800
4801           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4802           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4803           // C2 (CI). By solving for X we can turn this into a range check 
4804           // instead of computing a divide. 
4805           ConstantInt *Prod = 
4806             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4807
4808           // Determine if the product overflows by seeing if the product is
4809           // not equal to the divide. Make sure we do the same kind of divide
4810           // as in the LHS instruction that we're folding. 
4811           bool ProdOV = !DivRHS->isNullValue() && 
4812             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4813               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4814
4815           // Get the ICmp opcode
4816           ICmpInst::Predicate predicate = I.getPredicate();
4817
4818           if (DivRHS->isNullValue()) {  
4819             // Don't hack on divide by zeros!
4820           } else if (!DivIsSigned) {  // udiv
4821             LoBound = Prod;
4822             LoOverflow = ProdOV;
4823             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4824           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4825             if (CI->isNullValue()) {       // (X / pos) op 0
4826               // Can't overflow.
4827               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4828               HiBound = DivRHS;
4829             } else if (isPositive(CI)) {   // (X / pos) op pos
4830               LoBound = Prod;
4831               LoOverflow = ProdOV;
4832               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4833             } else {                       // (X / pos) op neg
4834               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4835               LoOverflow = AddWithOverflow(LoBound, Prod,
4836                                            cast<ConstantInt>(DivRHSH));
4837               HiBound = Prod;
4838               HiOverflow = ProdOV;
4839             }
4840           } else {                         // Divisor is < 0.
4841             if (CI->isNullValue()) {       // (X / neg) op 0
4842               LoBound = AddOne(DivRHS);
4843               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4844               if (HiBound == DivRHS)
4845                 LoBound = 0;               // - INTMIN = INTMIN
4846             } else if (isPositive(CI)) {   // (X / neg) op pos
4847               HiOverflow = LoOverflow = ProdOV;
4848               if (!LoOverflow)
4849                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4850               HiBound = AddOne(Prod);
4851             } else {                       // (X / neg) op neg
4852               LoBound = Prod;
4853               LoOverflow = HiOverflow = ProdOV;
4854               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4855             }
4856
4857             // Dividing by a negate swaps the condition.
4858             predicate = ICmpInst::getSwappedPredicate(predicate);
4859           }
4860
4861           if (LoBound) {
4862             Value *X = LHSI->getOperand(0);
4863             switch (predicate) {
4864             default: assert(0 && "Unhandled icmp opcode!");
4865             case ICmpInst::ICMP_EQ:
4866               if (LoOverflow && HiOverflow)
4867                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4868               else if (HiOverflow)
4869                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4870                                     ICmpInst::ICMP_UGE, X, LoBound);
4871               else if (LoOverflow)
4872                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4873                                     ICmpInst::ICMP_ULT, X, HiBound);
4874               else
4875                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4876                                        true, I);
4877             case ICmpInst::ICMP_NE:
4878               if (LoOverflow && HiOverflow)
4879                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4880               else if (HiOverflow)
4881                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4882                                     ICmpInst::ICMP_ULT, X, LoBound);
4883               else if (LoOverflow)
4884                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4885                                     ICmpInst::ICMP_UGE, X, HiBound);
4886               else
4887                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4888                                        false, I);
4889             case ICmpInst::ICMP_ULT:
4890             case ICmpInst::ICMP_SLT:
4891               if (LoOverflow)
4892                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4893               return new ICmpInst(predicate, X, LoBound);
4894             case ICmpInst::ICMP_UGT:
4895             case ICmpInst::ICMP_SGT:
4896               if (HiOverflow)
4897                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4898               if (predicate == ICmpInst::ICMP_UGT)
4899                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4900               else
4901                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4902             }
4903           }
4904         }
4905         break;
4906       }
4907
4908     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4909     if (I.isEquality()) {
4910       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4911
4912       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4913       // the second operand is a constant, simplify a bit.
4914       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4915         switch (BO->getOpcode()) {
4916         case Instruction::SRem:
4917           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4918           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4919               BO->hasOneUse()) {
4920             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4921             if (V > 1 && isPowerOf2_64(V)) {
4922               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4923                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4924               return new ICmpInst(I.getPredicate(), NewRem, 
4925                                   Constant::getNullValue(BO->getType()));
4926             }
4927           }
4928           break;
4929         case Instruction::Add:
4930           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4931           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4932             if (BO->hasOneUse())
4933               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4934                                   ConstantExpr::getSub(CI, BOp1C));
4935           } else if (CI->isNullValue()) {
4936             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4937             // efficiently invertible, or if the add has just this one use.
4938             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4939
4940             if (Value *NegVal = dyn_castNegVal(BOp1))
4941               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4942             else if (Value *NegVal = dyn_castNegVal(BOp0))
4943               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4944             else if (BO->hasOneUse()) {
4945               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4946               BO->setName("");
4947               InsertNewInstBefore(Neg, I);
4948               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4949             }
4950           }
4951           break;
4952         case Instruction::Xor:
4953           // For the xor case, we can xor two constants together, eliminating
4954           // the explicit xor.
4955           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4956             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4957                                 ConstantExpr::getXor(CI, BOC));
4958
4959           // FALLTHROUGH
4960         case Instruction::Sub:
4961           // Replace (([sub|xor] A, B) != 0) with (A != B)
4962           if (CI->isNullValue())
4963             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4964                                 BO->getOperand(1));
4965           break;
4966
4967         case Instruction::Or:
4968           // If bits are being or'd in that are not present in the constant we
4969           // are comparing against, then the comparison could never succeed!
4970           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4971             Constant *NotCI = ConstantExpr::getNot(CI);
4972             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4973               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
4974           }
4975           break;
4976
4977         case Instruction::And:
4978           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4979             // If bits are being compared against that are and'd out, then the
4980             // comparison can never succeed!
4981             if (!ConstantExpr::getAnd(CI,
4982                                       ConstantExpr::getNot(BOC))->isNullValue())
4983               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
4984
4985             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4986             if (CI == BOC && isOneBitSet(CI))
4987               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4988                                   ICmpInst::ICMP_NE, Op0,
4989                                   Constant::getNullValue(CI->getType()));
4990
4991             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
4992             if (isSignBit(BOC)) {
4993               Value *X = BO->getOperand(0);
4994               Constant *Zero = Constant::getNullValue(X->getType());
4995               ICmpInst::Predicate pred = isICMP_NE ? 
4996                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4997               return new ICmpInst(pred, X, Zero);
4998             }
4999
5000             // ((X & ~7) == 0) --> X < 8
5001             if (CI->isNullValue() && isHighOnes(BOC)) {
5002               Value *X = BO->getOperand(0);
5003               Constant *NegX = ConstantExpr::getNeg(BOC);
5004               ICmpInst::Predicate pred = isICMP_NE ? 
5005                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5006               return new ICmpInst(pred, X, NegX);
5007             }
5008
5009           }
5010         default: break;
5011         }
5012       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5013         // Handle set{eq|ne} <intrinsic>, intcst.
5014         switch (II->getIntrinsicID()) {
5015         default: break;
5016         case Intrinsic::bswap_i16: 
5017           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5018           WorkList.push_back(II);  // Dead?
5019           I.setOperand(0, II->getOperand(1));
5020           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5021                                            ByteSwap_16(CI->getZExtValue())));
5022           return &I;
5023         case Intrinsic::bswap_i32:   
5024           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5025           WorkList.push_back(II);  // Dead?
5026           I.setOperand(0, II->getOperand(1));
5027           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5028                                            ByteSwap_32(CI->getZExtValue())));
5029           return &I;
5030         case Intrinsic::bswap_i64:   
5031           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5032           WorkList.push_back(II);  // Dead?
5033           I.setOperand(0, II->getOperand(1));
5034           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5035                                            ByteSwap_64(CI->getZExtValue())));
5036           return &I;
5037         }
5038       }
5039     } else {  // Not a ICMP_EQ/ICMP_NE
5040       // If the LHS is a cast from an integral value of the same size, then 
5041       // since we know the RHS is a constant, try to simlify.
5042       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5043         Value *CastOp = Cast->getOperand(0);
5044         const Type *SrcTy = CastOp->getType();
5045         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5046         if (SrcTy->isInteger() && 
5047             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5048           // If this is an unsigned comparison, try to make the comparison use
5049           // smaller constant values.
5050           switch (I.getPredicate()) {
5051             default: break;
5052             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5053               ConstantInt *CUI = cast<ConstantInt>(CI);
5054               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5055                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5056                                     ConstantInt::get(SrcTy, -1));
5057               break;
5058             }
5059             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5060               ConstantInt *CUI = cast<ConstantInt>(CI);
5061               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5062                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5063                                     Constant::getNullValue(SrcTy));
5064               break;
5065             }
5066           }
5067
5068         }
5069       }
5070     }
5071   }
5072
5073   // Handle icmp with constant RHS
5074   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5075     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5076       switch (LHSI->getOpcode()) {
5077       case Instruction::GetElementPtr:
5078         if (RHSC->isNullValue()) {
5079           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5080           bool isAllZeros = true;
5081           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5082             if (!isa<Constant>(LHSI->getOperand(i)) ||
5083                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5084               isAllZeros = false;
5085               break;
5086             }
5087           if (isAllZeros)
5088             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5089                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5090         }
5091         break;
5092
5093       case Instruction::PHI:
5094         if (Instruction *NV = FoldOpIntoPhi(I))
5095           return NV;
5096         break;
5097       case Instruction::Select:
5098         // If either operand of the select is a constant, we can fold the
5099         // comparison into the select arms, which will cause one to be
5100         // constant folded and the select turned into a bitwise or.
5101         Value *Op1 = 0, *Op2 = 0;
5102         if (LHSI->hasOneUse()) {
5103           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5104             // Fold the known value into the constant operand.
5105             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5106             // Insert a new ICmp of the other select operand.
5107             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5108                                                    LHSI->getOperand(2), RHSC,
5109                                                    I.getName()), I);
5110           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5111             // Fold the known value into the constant operand.
5112             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5113             // Insert a new ICmp of the other select operand.
5114             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5115                                                    LHSI->getOperand(1), RHSC,
5116                                                    I.getName()), I);
5117           }
5118         }
5119
5120         if (Op1)
5121           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5122         break;
5123       }
5124   }
5125
5126   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5127   if (User *GEP = dyn_castGetElementPtr(Op0))
5128     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5129       return NI;
5130   if (User *GEP = dyn_castGetElementPtr(Op1))
5131     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5132                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5133       return NI;
5134
5135   // Test to see if the operands of the icmp are casted versions of other
5136   // values.  If the cast can be stripped off both arguments, we do so now.
5137   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5138     Value *CastOp0 = CI->getOperand(0);
5139     if (CI->isLosslessCast() && I.isEquality() && 
5140         (isa<Constant>(Op1) || isa<CastInst>(Op1))) { 
5141       // We keep moving the cast from the left operand over to the right
5142       // operand, where it can often be eliminated completely.
5143       Op0 = CastOp0;
5144
5145       // If operand #1 is a cast instruction, see if we can eliminate it as
5146       // well.
5147       if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) { 
5148         Value *CI2Op0 = CI2->getOperand(0);
5149         if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5150           Op1 = CI2Op0;
5151       }
5152
5153       // If Op1 is a constant, we can fold the cast into the constant.
5154       if (Op1->getType() != Op0->getType())
5155         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5156           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5157         } else {
5158           // Otherwise, cast the RHS right before the icmp
5159           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5160         }
5161       return new ICmpInst(I.getPredicate(), Op0, Op1);
5162     }
5163
5164     // Handle the special case of: icmp (cast bool to X), <cst>
5165     // This comes up when you have code like
5166     //   int X = A < B;
5167     //   if (X) ...
5168     // For generality, we handle any zero-extension of any operand comparison
5169     // with a constant or another cast from the same type.
5170     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5171       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5172         return R;
5173   }
5174   
5175   if (I.isEquality()) {
5176     Value *A, *B;
5177     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
5178         (A == Op1 || B == Op1)) {
5179       // (A^B) == A  ->  B == 0
5180       Value *OtherVal = A == Op1 ? B : A;
5181       return new ICmpInst(I.getPredicate(), OtherVal,
5182                           Constant::getNullValue(A->getType()));
5183     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5184                (A == Op0 || B == Op0)) {
5185       // A == (A^B)  ->  B == 0
5186       Value *OtherVal = A == Op0 ? B : A;
5187       return new ICmpInst(I.getPredicate(), OtherVal,
5188                           Constant::getNullValue(A->getType()));
5189     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5190       // (A-B) == A  ->  B == 0
5191       return new ICmpInst(I.getPredicate(), B,
5192                           Constant::getNullValue(B->getType()));
5193     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5194       // A == (A-B)  ->  B == 0
5195       return new ICmpInst(I.getPredicate(), B,
5196                           Constant::getNullValue(B->getType()));
5197     }
5198     
5199     Value *C, *D;
5200     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5201     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5202         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5203         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5204       Value *X = 0, *Y = 0, *Z = 0;
5205       
5206       if (A == C) {
5207         X = B; Y = D; Z = A;
5208       } else if (A == D) {
5209         X = B; Y = C; Z = A;
5210       } else if (B == C) {
5211         X = A; Y = D; Z = B;
5212       } else if (B == D) {
5213         X = A; Y = C; Z = B;
5214       }
5215       
5216       if (X) {   // Build (X^Y) & Z
5217         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5218         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5219         I.setOperand(0, Op1);
5220         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5221         return &I;
5222       }
5223     }
5224   }
5225   return Changed ? &I : 0;
5226 }
5227
5228 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5229 // We only handle extending casts so far.
5230 //
5231 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5232   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5233   Value *LHSCIOp        = LHSCI->getOperand(0);
5234   const Type *SrcTy     = LHSCIOp->getType();
5235   const Type *DestTy    = LHSCI->getType();
5236   Value *RHSCIOp;
5237
5238   // We only handle extension cast instructions, so far. Enforce this.
5239   if (LHSCI->getOpcode() != Instruction::ZExt &&
5240       LHSCI->getOpcode() != Instruction::SExt)
5241     return 0;
5242
5243   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5244   bool isSignedCmp = ICI.isSignedPredicate();
5245
5246   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5247     // Not an extension from the same type?
5248     RHSCIOp = CI->getOperand(0);
5249     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5250       return 0;
5251     else
5252       // Okay, just insert a compare of the reduced operands now!
5253       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5254   }
5255
5256   // If we aren't dealing with a constant on the RHS, exit early
5257   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5258   if (!CI)
5259     return 0;
5260
5261   // Compute the constant that would happen if we truncated to SrcTy then
5262   // reextended to DestTy.
5263   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5264   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5265
5266   // If the re-extended constant didn't change...
5267   if (Res2 == CI) {
5268     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5269     // For example, we might have:
5270     //    %A = sext short %X to uint
5271     //    %B = icmp ugt uint %A, 1330
5272     // It is incorrect to transform this into 
5273     //    %B = icmp ugt short %X, 1330 
5274     // because %A may have negative value. 
5275     //
5276     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5277     // OR operation is EQ/NE.
5278     if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5279       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5280     else
5281       return 0;
5282   }
5283
5284   // The re-extended constant changed so the constant cannot be represented 
5285   // in the shorter type. Consequently, we cannot emit a simple comparison.
5286
5287   // First, handle some easy cases. We know the result cannot be equal at this
5288   // point so handle the ICI.isEquality() cases
5289   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5290     return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5291   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5292     return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5293
5294   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5295   // should have been folded away previously and not enter in here.
5296   Value *Result;
5297   if (isSignedCmp) {
5298     // We're performing a signed comparison.
5299     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5300       Result = ConstantBool::getFalse();          // X < (small) --> false
5301     else
5302       Result = ConstantBool::getTrue();           // X < (large) --> true
5303   } else {
5304     // We're performing an unsigned comparison.
5305     if (isSignedExt) {
5306       // We're performing an unsigned comp with a sign extended value.
5307       // This is true if the input is >= 0. [aka >s -1]
5308       Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5309       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5310                                    NegOne, ICI.getName()), ICI);
5311     } else {
5312       // Unsigned extend & unsigned compare -> always true.
5313       Result = ConstantBool::getTrue();
5314     }
5315   }
5316
5317   // Finally, return the value computed.
5318   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5319       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5320     return ReplaceInstUsesWith(ICI, Result);
5321   } else {
5322     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5323             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5324            "ICmp should be folded!");
5325     if (Constant *CI = dyn_cast<Constant>(Result))
5326       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5327     else
5328       return BinaryOperator::createNot(Result);
5329   }
5330 }
5331
5332 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5333   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5334   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5335
5336   // shl X, 0 == X and shr X, 0 == X
5337   // shl 0, X == 0 and shr 0, X == 0
5338   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5339       Op0 == Constant::getNullValue(Op0->getType()))
5340     return ReplaceInstUsesWith(I, Op0);
5341   
5342   if (isa<UndefValue>(Op0)) {            
5343     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5344       return ReplaceInstUsesWith(I, Op0);
5345     else                                    // undef << X -> 0, undef >>u X -> 0
5346       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5347   }
5348   if (isa<UndefValue>(Op1)) {
5349     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5350       return ReplaceInstUsesWith(I, Op0);          
5351     else                                     // X << undef, X >>u undef -> 0
5352       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5353   }
5354
5355   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5356   if (I.getOpcode() == Instruction::AShr)
5357     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5358       if (CSI->isAllOnesValue())
5359         return ReplaceInstUsesWith(I, CSI);
5360
5361   // Try to fold constant and into select arguments.
5362   if (isa<Constant>(Op0))
5363     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5364       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5365         return R;
5366
5367   // See if we can turn a signed shr into an unsigned shr.
5368   if (I.isArithmeticShift()) {
5369     if (MaskedValueIsZero(Op0,
5370                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5371       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5372     }
5373   }
5374
5375   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5376     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5377       return Res;
5378   return 0;
5379 }
5380
5381 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5382                                                ShiftInst &I) {
5383   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5384   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5385   bool isUnsignedShift = !isSignedShift;
5386
5387   // See if we can simplify any instructions used by the instruction whose sole 
5388   // purpose is to compute bits we don't care about.
5389   uint64_t KnownZero, KnownOne;
5390   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5391                            KnownZero, KnownOne))
5392     return &I;
5393   
5394   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5395   // of a signed value.
5396   //
5397   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5398   if (Op1->getZExtValue() >= TypeBits) {
5399     if (isUnsignedShift || isLeftShift)
5400       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5401     else {
5402       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5403       return &I;
5404     }
5405   }
5406   
5407   // ((X*C1) << C2) == (X * (C1 << C2))
5408   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5409     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5410       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5411         return BinaryOperator::createMul(BO->getOperand(0),
5412                                          ConstantExpr::getShl(BOOp, Op1));
5413   
5414   // Try to fold constant and into select arguments.
5415   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5416     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5417       return R;
5418   if (isa<PHINode>(Op0))
5419     if (Instruction *NV = FoldOpIntoPhi(I))
5420       return NV;
5421   
5422   if (Op0->hasOneUse()) {
5423     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5424       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5425       Value *V1, *V2;
5426       ConstantInt *CC;
5427       switch (Op0BO->getOpcode()) {
5428         default: break;
5429         case Instruction::Add:
5430         case Instruction::And:
5431         case Instruction::Or:
5432         case Instruction::Xor:
5433           // These operators commute.
5434           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5435           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5436               match(Op0BO->getOperand(1),
5437                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5438             Instruction *YS = new ShiftInst(Instruction::Shl, 
5439                                             Op0BO->getOperand(0), Op1,
5440                                             Op0BO->getName());
5441             InsertNewInstBefore(YS, I); // (Y << C)
5442             Instruction *X = 
5443               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5444                                      Op0BO->getOperand(1)->getName());
5445             InsertNewInstBefore(X, I);  // (X + (Y << C))
5446             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5447             C2 = ConstantExpr::getShl(C2, Op1);
5448             return BinaryOperator::createAnd(X, C2);
5449           }
5450           
5451           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5452           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5453               match(Op0BO->getOperand(1),
5454                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5455                           m_ConstantInt(CC))) && V2 == Op1 &&
5456       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5457             Instruction *YS = new ShiftInst(Instruction::Shl, 
5458                                             Op0BO->getOperand(0), Op1,
5459                                             Op0BO->getName());
5460             InsertNewInstBefore(YS, I); // (Y << C)
5461             Instruction *XM =
5462               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5463                                         V1->getName()+".mask");
5464             InsertNewInstBefore(XM, I); // X & (CC << C)
5465             
5466             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5467           }
5468           
5469           // FALL THROUGH.
5470         case Instruction::Sub:
5471           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5472           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5473               match(Op0BO->getOperand(0),
5474                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5475             Instruction *YS = new ShiftInst(Instruction::Shl, 
5476                                             Op0BO->getOperand(1), Op1,
5477                                             Op0BO->getName());
5478             InsertNewInstBefore(YS, I); // (Y << C)
5479             Instruction *X =
5480               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5481                                      Op0BO->getOperand(0)->getName());
5482             InsertNewInstBefore(X, I);  // (X + (Y << C))
5483             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5484             C2 = ConstantExpr::getShl(C2, Op1);
5485             return BinaryOperator::createAnd(X, C2);
5486           }
5487           
5488           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5489           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5490               match(Op0BO->getOperand(0),
5491                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5492                           m_ConstantInt(CC))) && V2 == Op1 &&
5493               cast<BinaryOperator>(Op0BO->getOperand(0))
5494                   ->getOperand(0)->hasOneUse()) {
5495             Instruction *YS = new ShiftInst(Instruction::Shl, 
5496                                             Op0BO->getOperand(1), Op1,
5497                                             Op0BO->getName());
5498             InsertNewInstBefore(YS, I); // (Y << C)
5499             Instruction *XM =
5500               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5501                                         V1->getName()+".mask");
5502             InsertNewInstBefore(XM, I); // X & (CC << C)
5503             
5504             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5505           }
5506           
5507           break;
5508       }
5509       
5510       
5511       // If the operand is an bitwise operator with a constant RHS, and the
5512       // shift is the only use, we can pull it out of the shift.
5513       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5514         bool isValid = true;     // Valid only for And, Or, Xor
5515         bool highBitSet = false; // Transform if high bit of constant set?
5516         
5517         switch (Op0BO->getOpcode()) {
5518           default: isValid = false; break;   // Do not perform transform!
5519           case Instruction::Add:
5520             isValid = isLeftShift;
5521             break;
5522           case Instruction::Or:
5523           case Instruction::Xor:
5524             highBitSet = false;
5525             break;
5526           case Instruction::And:
5527             highBitSet = true;
5528             break;
5529         }
5530         
5531         // If this is a signed shift right, and the high bit is modified
5532         // by the logical operation, do not perform the transformation.
5533         // The highBitSet boolean indicates the value of the high bit of
5534         // the constant which would cause it to be modified for this
5535         // operation.
5536         //
5537         if (isValid && !isLeftShift && isSignedShift) {
5538           uint64_t Val = Op0C->getZExtValue();
5539           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5540         }
5541         
5542         if (isValid) {
5543           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5544           
5545           Instruction *NewShift =
5546             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5547                           Op0BO->getName());
5548           Op0BO->setName("");
5549           InsertNewInstBefore(NewShift, I);
5550           
5551           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5552                                         NewRHS);
5553         }
5554       }
5555     }
5556   }
5557   
5558   // Find out if this is a shift of a shift by a constant.
5559   ShiftInst *ShiftOp = 0;
5560   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5561     ShiftOp = Op0SI;
5562   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5563     // If this is a noop-integer cast of a shift instruction, use the shift.
5564     if (isa<ShiftInst>(CI->getOperand(0))) {
5565       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5566     }
5567   }
5568   
5569   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5570     // Find the operands and properties of the input shift.  Note that the
5571     // signedness of the input shift may differ from the current shift if there
5572     // is a noop cast between the two.
5573     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5574     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5575     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5576     
5577     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5578
5579     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5580     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5581     
5582     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5583     if (isLeftShift == isShiftOfLeftShift) {
5584       // Do not fold these shifts if the first one is signed and the second one
5585       // is unsigned and this is a right shift.  Further, don't do any folding
5586       // on them.
5587       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5588         return 0;
5589       
5590       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5591       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5592         Amt = Op0->getType()->getPrimitiveSizeInBits();
5593       
5594       Value *Op = ShiftOp->getOperand(0);
5595       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5596                                           ConstantInt::get(Type::Int8Ty, Amt));
5597       if (I.getType() == ShiftResult->getType())
5598         return ShiftResult;
5599       InsertNewInstBefore(ShiftResult, I);
5600       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5601     }
5602     
5603     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5604     // signed types, we can only support the (A >> c1) << c2 configuration,
5605     // because it can not turn an arbitrary bit of A into a sign bit.
5606     if (isUnsignedShift || isLeftShift) {
5607       // Calculate bitmask for what gets shifted off the edge.
5608       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5609       if (isLeftShift)
5610         C = ConstantExpr::getShl(C, ShiftAmt1C);
5611       else
5612         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5613       
5614       Value *Op = ShiftOp->getOperand(0);
5615       
5616       Instruction *Mask =
5617         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5618       InsertNewInstBefore(Mask, I);
5619       
5620       // Figure out what flavor of shift we should use...
5621       if (ShiftAmt1 == ShiftAmt2) {
5622         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5623       } else if (ShiftAmt1 < ShiftAmt2) {
5624         return new ShiftInst(I.getOpcode(), Mask,
5625                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5626       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5627         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5628           return new ShiftInst(Instruction::LShr, Mask, 
5629             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5630         } else {
5631           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5632                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5633         }
5634       } else {
5635         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5636         Instruction *Shift =
5637           new ShiftInst(ShiftOp->getOpcode(), Mask,
5638                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5639         InsertNewInstBefore(Shift, I);
5640         
5641         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5642         C = ConstantExpr::getShl(C, Op1);
5643         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5644       }
5645     } else {
5646       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5647       // this case, C1 == C2 and C1 is 8, 16, or 32.
5648       if (ShiftAmt1 == ShiftAmt2) {
5649         const Type *SExtType = 0;
5650         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5651         case 8 : SExtType = Type::Int8Ty; break;
5652         case 16: SExtType = Type::Int16Ty; break;
5653         case 32: SExtType = Type::Int32Ty; break;
5654         }
5655         
5656         if (SExtType) {
5657           Instruction *NewTrunc = 
5658             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5659           InsertNewInstBefore(NewTrunc, I);
5660           return new SExtInst(NewTrunc, I.getType());
5661         }
5662       }
5663     }
5664   }
5665   return 0;
5666 }
5667
5668
5669 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5670 /// expression.  If so, decompose it, returning some value X, such that Val is
5671 /// X*Scale+Offset.
5672 ///
5673 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5674                                         unsigned &Offset) {
5675   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5676   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5677     Offset = CI->getZExtValue();
5678     Scale  = 1;
5679     return ConstantInt::get(Type::Int32Ty, 0);
5680   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5681     if (I->getNumOperands() == 2) {
5682       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5683         if (I->getOpcode() == Instruction::Shl) {
5684           // This is a value scaled by '1 << the shift amt'.
5685           Scale = 1U << CUI->getZExtValue();
5686           Offset = 0;
5687           return I->getOperand(0);
5688         } else if (I->getOpcode() == Instruction::Mul) {
5689           // This value is scaled by 'CUI'.
5690           Scale = CUI->getZExtValue();
5691           Offset = 0;
5692           return I->getOperand(0);
5693         } else if (I->getOpcode() == Instruction::Add) {
5694           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5695           // where C1 is divisible by C2.
5696           unsigned SubScale;
5697           Value *SubVal = 
5698             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5699           Offset += CUI->getZExtValue();
5700           if (SubScale > 1 && (Offset % SubScale == 0)) {
5701             Scale = SubScale;
5702             return SubVal;
5703           }
5704         }
5705       }
5706     }
5707   }
5708
5709   // Otherwise, we can't look past this.
5710   Scale = 1;
5711   Offset = 0;
5712   return Val;
5713 }
5714
5715
5716 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5717 /// try to eliminate the cast by moving the type information into the alloc.
5718 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5719                                                    AllocationInst &AI) {
5720   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5721   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5722   
5723   // Remove any uses of AI that are dead.
5724   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5725   std::vector<Instruction*> DeadUsers;
5726   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5727     Instruction *User = cast<Instruction>(*UI++);
5728     if (isInstructionTriviallyDead(User)) {
5729       while (UI != E && *UI == User)
5730         ++UI; // If this instruction uses AI more than once, don't break UI.
5731       
5732       // Add operands to the worklist.
5733       AddUsesToWorkList(*User);
5734       ++NumDeadInst;
5735       DOUT << "IC: DCE: " << *User;
5736       
5737       User->eraseFromParent();
5738       removeFromWorkList(User);
5739     }
5740   }
5741   
5742   // Get the type really allocated and the type casted to.
5743   const Type *AllocElTy = AI.getAllocatedType();
5744   const Type *CastElTy = PTy->getElementType();
5745   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5746
5747   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5748   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5749   if (CastElTyAlign < AllocElTyAlign) return 0;
5750
5751   // If the allocation has multiple uses, only promote it if we are strictly
5752   // increasing the alignment of the resultant allocation.  If we keep it the
5753   // same, we open the door to infinite loops of various kinds.
5754   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5755
5756   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5757   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5758   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5759
5760   // See if we can satisfy the modulus by pulling a scale out of the array
5761   // size argument.
5762   unsigned ArraySizeScale, ArrayOffset;
5763   Value *NumElements = // See if the array size is a decomposable linear expr.
5764     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5765  
5766   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5767   // do the xform.
5768   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5769       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5770
5771   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5772   Value *Amt = 0;
5773   if (Scale == 1) {
5774     Amt = NumElements;
5775   } else {
5776     // If the allocation size is constant, form a constant mul expression
5777     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5778     if (isa<ConstantInt>(NumElements))
5779       Amt = ConstantExpr::getMul(
5780               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5781     // otherwise multiply the amount and the number of elements
5782     else if (Scale != 1) {
5783       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5784       Amt = InsertNewInstBefore(Tmp, AI);
5785     }
5786   }
5787   
5788   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5789     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5790     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5791     Amt = InsertNewInstBefore(Tmp, AI);
5792   }
5793   
5794   std::string Name = AI.getName(); AI.setName("");
5795   AllocationInst *New;
5796   if (isa<MallocInst>(AI))
5797     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5798   else
5799     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5800   InsertNewInstBefore(New, AI);
5801   
5802   // If the allocation has multiple uses, insert a cast and change all things
5803   // that used it to use the new cast.  This will also hack on CI, but it will
5804   // die soon.
5805   if (!AI.hasOneUse()) {
5806     AddUsesToWorkList(AI);
5807     // New is the allocation instruction, pointer typed. AI is the original
5808     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5809     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5810     InsertNewInstBefore(NewCast, AI);
5811     AI.replaceAllUsesWith(NewCast);
5812   }
5813   return ReplaceInstUsesWith(CI, New);
5814 }
5815
5816 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5817 /// and return it without inserting any new casts.  This is used by code that
5818 /// tries to decide whether promoting or shrinking integer operations to wider
5819 /// or smaller types will allow us to eliminate a truncate or extend.
5820 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5821                                        int &NumCastsRemoved) {
5822   if (isa<Constant>(V)) return true;
5823   
5824   Instruction *I = dyn_cast<Instruction>(V);
5825   if (!I || !I->hasOneUse()) return false;
5826   
5827   switch (I->getOpcode()) {
5828   case Instruction::And:
5829   case Instruction::Or:
5830   case Instruction::Xor:
5831     // These operators can all arbitrarily be extended or truncated.
5832     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5833            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5834   case Instruction::AShr:
5835   case Instruction::LShr:
5836   case Instruction::Shl:
5837     // If this is just a bitcast changing the sign of the operation, we can
5838     // convert if the operand can be converted.
5839     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5840       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5841     break;
5842   case Instruction::Trunc:
5843   case Instruction::ZExt:
5844   case Instruction::SExt:
5845   case Instruction::BitCast:
5846     // If this is a cast from the destination type, we can trivially eliminate
5847     // it, and this will remove a cast overall.
5848     if (I->getOperand(0)->getType() == Ty) {
5849       // If the first operand is itself a cast, and is eliminable, do not count
5850       // this as an eliminable cast.  We would prefer to eliminate those two
5851       // casts first.
5852       if (isa<CastInst>(I->getOperand(0)))
5853         return true;
5854       
5855       ++NumCastsRemoved;
5856       return true;
5857     }
5858     break;
5859   default:
5860     // TODO: Can handle more cases here.
5861     break;
5862   }
5863   
5864   return false;
5865 }
5866
5867 /// EvaluateInDifferentType - Given an expression that 
5868 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5869 /// evaluate the expression.
5870 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5871                                              bool isSigned ) {
5872   if (Constant *C = dyn_cast<Constant>(V))
5873     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5874
5875   // Otherwise, it must be an instruction.
5876   Instruction *I = cast<Instruction>(V);
5877   Instruction *Res = 0;
5878   switch (I->getOpcode()) {
5879   case Instruction::And:
5880   case Instruction::Or:
5881   case Instruction::Xor: {
5882     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5883     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5884     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5885                                  LHS, RHS, I->getName());
5886     break;
5887   }
5888   case Instruction::AShr:
5889   case Instruction::LShr:
5890   case Instruction::Shl: {
5891     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5892     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5893                         I->getOperand(1), I->getName());
5894     break;
5895   }    
5896   case Instruction::Trunc:
5897   case Instruction::ZExt:
5898   case Instruction::SExt:
5899   case Instruction::BitCast:
5900     // If the source type of the cast is the type we're trying for then we can
5901     // just return the source. There's no need to insert it because its not new.
5902     if (I->getOperand(0)->getType() == Ty)
5903       return I->getOperand(0);
5904     
5905     // Some other kind of cast, which shouldn't happen, so just ..
5906     // FALL THROUGH
5907   default: 
5908     // TODO: Can handle more cases here.
5909     assert(0 && "Unreachable!");
5910     break;
5911   }
5912   
5913   return InsertNewInstBefore(Res, *I);
5914 }
5915
5916 /// @brief Implement the transforms common to all CastInst visitors.
5917 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5918   Value *Src = CI.getOperand(0);
5919
5920   // Casting undef to anything results in undef so might as just replace it and
5921   // get rid of the cast.
5922   if (isa<UndefValue>(Src))   // cast undef -> undef
5923     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5924
5925   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5926   // eliminate it now.
5927   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5928     if (Instruction::CastOps opc = 
5929         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5930       // The first cast (CSrc) is eliminable so we need to fix up or replace
5931       // the second cast (CI). CSrc will then have a good chance of being dead.
5932       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5933     }
5934   }
5935
5936   // If casting the result of a getelementptr instruction with no offset, turn
5937   // this into a cast of the original pointer!
5938   //
5939   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5940     bool AllZeroOperands = true;
5941     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5942       if (!isa<Constant>(GEP->getOperand(i)) ||
5943           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5944         AllZeroOperands = false;
5945         break;
5946       }
5947     if (AllZeroOperands) {
5948       // Changing the cast operand is usually not a good idea but it is safe
5949       // here because the pointer operand is being replaced with another 
5950       // pointer operand so the opcode doesn't need to change.
5951       CI.setOperand(0, GEP->getOperand(0));
5952       return &CI;
5953     }
5954   }
5955     
5956   // If we are casting a malloc or alloca to a pointer to a type of the same
5957   // size, rewrite the allocation instruction to allocate the "right" type.
5958   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5959     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5960       return V;
5961
5962   // If we are casting a select then fold the cast into the select
5963   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5964     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5965       return NV;
5966
5967   // If we are casting a PHI then fold the cast into the PHI
5968   if (isa<PHINode>(Src))
5969     if (Instruction *NV = FoldOpIntoPhi(CI))
5970       return NV;
5971   
5972   return 0;
5973 }
5974
5975 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5976 /// integers. This function implements the common transforms for all those
5977 /// cases.
5978 /// @brief Implement the transforms common to CastInst with integer operands
5979 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5980   if (Instruction *Result = commonCastTransforms(CI))
5981     return Result;
5982
5983   Value *Src = CI.getOperand(0);
5984   const Type *SrcTy = Src->getType();
5985   const Type *DestTy = CI.getType();
5986   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5987   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5988
5989   // See if we can simplify any instructions used by the LHS whose sole 
5990   // purpose is to compute bits we don't care about.
5991   uint64_t KnownZero = 0, KnownOne = 0;
5992   if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5993                            KnownZero, KnownOne))
5994     return &CI;
5995
5996   // If the source isn't an instruction or has more than one use then we
5997   // can't do anything more. 
5998   Instruction *SrcI = dyn_cast<Instruction>(Src);
5999   if (!SrcI || !Src->hasOneUse())
6000     return 0;
6001
6002   // Attempt to propagate the cast into the instruction.
6003   int NumCastsRemoved = 0;
6004   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6005     // If this cast is a truncate, evaluting in a different type always
6006     // eliminates the cast, so it is always a win.  If this is a noop-cast
6007     // this just removes a noop cast which isn't pointful, but simplifies
6008     // the code.  If this is a zero-extension, we need to do an AND to
6009     // maintain the clear top-part of the computation, so we require that
6010     // the input have eliminated at least one cast.  If this is a sign
6011     // extension, we insert two new casts (to do the extension) so we
6012     // require that two casts have been eliminated.
6013     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6014     if (!DoXForm) {
6015       switch (CI.getOpcode()) {
6016         case Instruction::Trunc:
6017           DoXForm = true;
6018           break;
6019         case Instruction::ZExt:
6020           DoXForm = NumCastsRemoved >= 1;
6021           break;
6022         case Instruction::SExt:
6023           DoXForm = NumCastsRemoved >= 2;
6024           break;
6025         case Instruction::BitCast:
6026           DoXForm = false;
6027           break;
6028         default:
6029           // All the others use floating point so we shouldn't actually 
6030           // get here because of the check above.
6031           assert(!"Unknown cast type .. unreachable");
6032           break;
6033       }
6034     }
6035     
6036     if (DoXForm) {
6037       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6038                                            CI.getOpcode() == Instruction::SExt);
6039       assert(Res->getType() == DestTy);
6040       switch (CI.getOpcode()) {
6041       default: assert(0 && "Unknown cast type!");
6042       case Instruction::Trunc:
6043       case Instruction::BitCast:
6044         // Just replace this cast with the result.
6045         return ReplaceInstUsesWith(CI, Res);
6046       case Instruction::ZExt: {
6047         // We need to emit an AND to clear the high bits.
6048         assert(SrcBitSize < DestBitSize && "Not a zext?");
6049         Constant *C = 
6050           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6051         if (DestBitSize < 64)
6052           C = ConstantExpr::getTrunc(C, DestTy);
6053         return BinaryOperator::createAnd(Res, C);
6054       }
6055       case Instruction::SExt:
6056         // We need to emit a cast to truncate, then a cast to sext.
6057         return CastInst::create(Instruction::SExt,
6058             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6059                              CI), DestTy);
6060       }
6061     }
6062   }
6063   
6064   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6065   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6066
6067   switch (SrcI->getOpcode()) {
6068   case Instruction::Add:
6069   case Instruction::Mul:
6070   case Instruction::And:
6071   case Instruction::Or:
6072   case Instruction::Xor:
6073     // If we are discarding information, or just changing the sign, 
6074     // rewrite.
6075     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6076       // Don't insert two casts if they cannot be eliminated.  We allow 
6077       // two casts to be inserted if the sizes are the same.  This could 
6078       // only be converting signedness, which is a noop.
6079       if (DestBitSize == SrcBitSize || 
6080           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6081           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6082         Instruction::CastOps opcode = CI.getOpcode();
6083         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6084         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6085         return BinaryOperator::create(
6086             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6087       }
6088     }
6089
6090     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6091     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6092         SrcI->getOpcode() == Instruction::Xor &&
6093         Op1 == ConstantBool::getTrue() &&
6094         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6095       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6096       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6097     }
6098     break;
6099   case Instruction::SDiv:
6100   case Instruction::UDiv:
6101   case Instruction::SRem:
6102   case Instruction::URem:
6103     // If we are just changing the sign, rewrite.
6104     if (DestBitSize == SrcBitSize) {
6105       // Don't insert two casts if they cannot be eliminated.  We allow 
6106       // two casts to be inserted if the sizes are the same.  This could 
6107       // only be converting signedness, which is a noop.
6108       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6109           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6110         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6111                                               Op0, DestTy, SrcI);
6112         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6113                                               Op1, DestTy, SrcI);
6114         return BinaryOperator::create(
6115           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6116       }
6117     }
6118     break;
6119
6120   case Instruction::Shl:
6121     // Allow changing the sign of the source operand.  Do not allow 
6122     // changing the size of the shift, UNLESS the shift amount is a 
6123     // constant.  We must not change variable sized shifts to a smaller 
6124     // size, because it is undefined to shift more bits out than exist 
6125     // in the value.
6126     if (DestBitSize == SrcBitSize ||
6127         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6128       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6129           Instruction::BitCast : Instruction::Trunc);
6130       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6131       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6132     }
6133     break;
6134   case Instruction::AShr:
6135     // If this is a signed shr, and if all bits shifted in are about to be
6136     // truncated off, turn it into an unsigned shr to allow greater
6137     // simplifications.
6138     if (DestBitSize < SrcBitSize &&
6139         isa<ConstantInt>(Op1)) {
6140       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6141       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6142         // Insert the new logical shift right.
6143         return new ShiftInst(Instruction::LShr, Op0, Op1);
6144       }
6145     }
6146     break;
6147
6148   case Instruction::ICmp:
6149     // If we are just checking for a icmp eq of a single bit and casting it
6150     // to an integer, then shift the bit to the appropriate place and then
6151     // cast to integer to avoid the comparison.
6152     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6153       uint64_t Op1CV = Op1C->getZExtValue();
6154       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6155       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6156       // cast (X == 1) to int --> X        iff X has only the low bit set.
6157       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6158       // cast (X != 0) to int --> X        iff X has only the low bit set.
6159       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6160       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6161       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6162       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6163         // If Op1C some other power of two, convert:
6164         uint64_t KnownZero, KnownOne;
6165         uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6166         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6167
6168         // This only works for EQ and NE
6169         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6170         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6171           break;
6172         
6173         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6174           bool isNE = pred == ICmpInst::ICMP_NE;
6175           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6176             // (X&4) == 2 --> false
6177             // (X&4) != 2 --> true
6178             Constant *Res = ConstantBool::get(isNE);
6179             Res = ConstantExpr::getZExt(Res, CI.getType());
6180             return ReplaceInstUsesWith(CI, Res);
6181           }
6182           
6183           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6184           Value *In = Op0;
6185           if (ShiftAmt) {
6186             // Perform a logical shr by shiftamt.
6187             // Insert the shift to put the result in the low bit.
6188             In = InsertNewInstBefore(
6189               new ShiftInst(Instruction::LShr, In,
6190                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6191                             In->getName()+".lobit"), CI);
6192           }
6193           
6194           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6195             Constant *One = ConstantInt::get(In->getType(), 1);
6196             In = BinaryOperator::createXor(In, One, "tmp");
6197             InsertNewInstBefore(cast<Instruction>(In), CI);
6198           }
6199           
6200           if (CI.getType() == In->getType())
6201             return ReplaceInstUsesWith(CI, In);
6202           else
6203             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6204         }
6205       }
6206     }
6207     break;
6208   }
6209   return 0;
6210 }
6211
6212 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6213   if (Instruction *Result = commonIntCastTransforms(CI))
6214     return Result;
6215   
6216   Value *Src = CI.getOperand(0);
6217   const Type *Ty = CI.getType();
6218   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6219   
6220   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6221     switch (SrcI->getOpcode()) {
6222     default: break;
6223     case Instruction::LShr:
6224       // We can shrink lshr to something smaller if we know the bits shifted in
6225       // are already zeros.
6226       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6227         unsigned ShAmt = ShAmtV->getZExtValue();
6228         
6229         // Get a mask for the bits shifting in.
6230         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6231         Value* SrcIOp0 = SrcI->getOperand(0);
6232         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6233           if (ShAmt >= DestBitWidth)        // All zeros.
6234             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6235
6236           // Okay, we can shrink this.  Truncate the input, then return a new
6237           // shift.
6238           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6239           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6240         }
6241       } else {     // This is a variable shr.
6242         
6243         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6244         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6245         // loop-invariant and CSE'd.
6246         if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6247           Value *One = ConstantInt::get(SrcI->getType(), 1);
6248
6249           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6250                                                        SrcI->getOperand(1),
6251                                                        "tmp"), CI);
6252           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6253                                                             SrcI->getOperand(0),
6254                                                             "tmp"), CI);
6255           Value *Zero = Constant::getNullValue(V->getType());
6256           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6257         }
6258       }
6259       break;
6260     }
6261   }
6262   
6263   return 0;
6264 }
6265
6266 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6267   // If one of the common conversion will work ..
6268   if (Instruction *Result = commonIntCastTransforms(CI))
6269     return Result;
6270
6271   Value *Src = CI.getOperand(0);
6272
6273   // If this is a cast of a cast
6274   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6275     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6276     // types and if the sizes are just right we can convert this into a logical
6277     // 'and' which will be much cheaper than the pair of casts.
6278     if (isa<TruncInst>(CSrc)) {
6279       // Get the sizes of the types involved
6280       Value *A = CSrc->getOperand(0);
6281       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6282       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6283       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6284       // If we're actually extending zero bits and the trunc is a no-op
6285       if (MidSize < DstSize && SrcSize == DstSize) {
6286         // Replace both of the casts with an And of the type mask.
6287         uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6288         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6289         Instruction *And = 
6290           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6291         // Unfortunately, if the type changed, we need to cast it back.
6292         if (And->getType() != CI.getType()) {
6293           And->setName(CSrc->getName()+".mask");
6294           InsertNewInstBefore(And, CI);
6295           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6296         }
6297         return And;
6298       }
6299     }
6300   }
6301
6302   return 0;
6303 }
6304
6305 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6306   return commonIntCastTransforms(CI);
6307 }
6308
6309 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6310   return commonCastTransforms(CI);
6311 }
6312
6313 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6314   return commonCastTransforms(CI);
6315 }
6316
6317 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6318   return commonCastTransforms(CI);
6319 }
6320
6321 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6322   return commonCastTransforms(CI);
6323 }
6324
6325 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6326   return commonCastTransforms(CI);
6327 }
6328
6329 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6330   return commonCastTransforms(CI);
6331 }
6332
6333 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6334   return commonCastTransforms(CI);
6335 }
6336
6337 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6338   return commonCastTransforms(CI);
6339 }
6340
6341 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6342
6343   // If the operands are integer typed then apply the integer transforms,
6344   // otherwise just apply the common ones.
6345   Value *Src = CI.getOperand(0);
6346   const Type *SrcTy = Src->getType();
6347   const Type *DestTy = CI.getType();
6348
6349   if (SrcTy->isInteger() && DestTy->isInteger()) {
6350     if (Instruction *Result = commonIntCastTransforms(CI))
6351       return Result;
6352   } else {
6353     if (Instruction *Result = commonCastTransforms(CI))
6354       return Result;
6355   }
6356
6357
6358   // Get rid of casts from one type to the same type. These are useless and can
6359   // be replaced by the operand.
6360   if (DestTy == Src->getType())
6361     return ReplaceInstUsesWith(CI, Src);
6362
6363   // If the source and destination are pointers, and this cast is equivalent to
6364   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6365   // This can enhance SROA and other transforms that want type-safe pointers.
6366   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6367     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6368       const Type *DstElTy = DstPTy->getElementType();
6369       const Type *SrcElTy = SrcPTy->getElementType();
6370       
6371       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6372       unsigned NumZeros = 0;
6373       while (SrcElTy != DstElTy && 
6374              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6375              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6376         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6377         ++NumZeros;
6378       }
6379
6380       // If we found a path from the src to dest, create the getelementptr now.
6381       if (SrcElTy == DstElTy) {
6382         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6383         return new GetElementPtrInst(Src, Idxs);
6384       }
6385     }
6386   }
6387
6388   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6389     if (SVI->hasOneUse()) {
6390       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6391       // a bitconvert to a vector with the same # elts.
6392       if (isa<PackedType>(DestTy) && 
6393           cast<PackedType>(DestTy)->getNumElements() == 
6394                 SVI->getType()->getNumElements()) {
6395         CastInst *Tmp;
6396         // If either of the operands is a cast from CI.getType(), then
6397         // evaluating the shuffle in the casted destination's type will allow
6398         // us to eliminate at least one cast.
6399         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6400              Tmp->getOperand(0)->getType() == DestTy) ||
6401             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6402              Tmp->getOperand(0)->getType() == DestTy)) {
6403           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6404                                                SVI->getOperand(0), DestTy, &CI);
6405           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6406                                                SVI->getOperand(1), DestTy, &CI);
6407           // Return a new shuffle vector.  Use the same element ID's, as we
6408           // know the vector types match #elts.
6409           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6410         }
6411       }
6412     }
6413   }
6414   return 0;
6415 }
6416
6417 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6418 ///   %C = or %A, %B
6419 ///   %D = select %cond, %C, %A
6420 /// into:
6421 ///   %C = select %cond, %B, 0
6422 ///   %D = or %A, %C
6423 ///
6424 /// Assuming that the specified instruction is an operand to the select, return
6425 /// a bitmask indicating which operands of this instruction are foldable if they
6426 /// equal the other incoming value of the select.
6427 ///
6428 static unsigned GetSelectFoldableOperands(Instruction *I) {
6429   switch (I->getOpcode()) {
6430   case Instruction::Add:
6431   case Instruction::Mul:
6432   case Instruction::And:
6433   case Instruction::Or:
6434   case Instruction::Xor:
6435     return 3;              // Can fold through either operand.
6436   case Instruction::Sub:   // Can only fold on the amount subtracted.
6437   case Instruction::Shl:   // Can only fold on the shift amount.
6438   case Instruction::LShr:
6439   case Instruction::AShr:
6440     return 1;
6441   default:
6442     return 0;              // Cannot fold
6443   }
6444 }
6445
6446 /// GetSelectFoldableConstant - For the same transformation as the previous
6447 /// function, return the identity constant that goes into the select.
6448 static Constant *GetSelectFoldableConstant(Instruction *I) {
6449   switch (I->getOpcode()) {
6450   default: assert(0 && "This cannot happen!"); abort();
6451   case Instruction::Add:
6452   case Instruction::Sub:
6453   case Instruction::Or:
6454   case Instruction::Xor:
6455     return Constant::getNullValue(I->getType());
6456   case Instruction::Shl:
6457   case Instruction::LShr:
6458   case Instruction::AShr:
6459     return Constant::getNullValue(Type::Int8Ty);
6460   case Instruction::And:
6461     return ConstantInt::getAllOnesValue(I->getType());
6462   case Instruction::Mul:
6463     return ConstantInt::get(I->getType(), 1);
6464   }
6465 }
6466
6467 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6468 /// have the same opcode and only one use each.  Try to simplify this.
6469 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6470                                           Instruction *FI) {
6471   if (TI->getNumOperands() == 1) {
6472     // If this is a non-volatile load or a cast from the same type,
6473     // merge.
6474     if (TI->isCast()) {
6475       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6476         return 0;
6477     } else {
6478       return 0;  // unknown unary op.
6479     }
6480
6481     // Fold this by inserting a select from the input values.
6482     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6483                                        FI->getOperand(0), SI.getName()+".v");
6484     InsertNewInstBefore(NewSI, SI);
6485     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6486                             TI->getType());
6487   }
6488
6489   // Only handle binary, compare and shift operators here.
6490   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6491     return 0;
6492
6493   // Figure out if the operations have any operands in common.
6494   Value *MatchOp, *OtherOpT, *OtherOpF;
6495   bool MatchIsOpZero;
6496   if (TI->getOperand(0) == FI->getOperand(0)) {
6497     MatchOp  = TI->getOperand(0);
6498     OtherOpT = TI->getOperand(1);
6499     OtherOpF = FI->getOperand(1);
6500     MatchIsOpZero = true;
6501   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6502     MatchOp  = TI->getOperand(1);
6503     OtherOpT = TI->getOperand(0);
6504     OtherOpF = FI->getOperand(0);
6505     MatchIsOpZero = false;
6506   } else if (!TI->isCommutative()) {
6507     return 0;
6508   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6509     MatchOp  = TI->getOperand(0);
6510     OtherOpT = TI->getOperand(1);
6511     OtherOpF = FI->getOperand(0);
6512     MatchIsOpZero = true;
6513   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6514     MatchOp  = TI->getOperand(1);
6515     OtherOpT = TI->getOperand(0);
6516     OtherOpF = FI->getOperand(1);
6517     MatchIsOpZero = true;
6518   } else {
6519     return 0;
6520   }
6521
6522   // If we reach here, they do have operations in common.
6523   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6524                                      OtherOpF, SI.getName()+".v");
6525   InsertNewInstBefore(NewSI, SI);
6526
6527   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6528     if (MatchIsOpZero)
6529       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6530     else
6531       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6532   }
6533
6534   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6535   if (MatchIsOpZero)
6536     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6537   else
6538     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6539 }
6540
6541 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6542   Value *CondVal = SI.getCondition();
6543   Value *TrueVal = SI.getTrueValue();
6544   Value *FalseVal = SI.getFalseValue();
6545
6546   // select true, X, Y  -> X
6547   // select false, X, Y -> Y
6548   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6549     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6550
6551   // select C, X, X -> X
6552   if (TrueVal == FalseVal)
6553     return ReplaceInstUsesWith(SI, TrueVal);
6554
6555   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6556     return ReplaceInstUsesWith(SI, FalseVal);
6557   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6558     return ReplaceInstUsesWith(SI, TrueVal);
6559   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6560     if (isa<Constant>(TrueVal))
6561       return ReplaceInstUsesWith(SI, TrueVal);
6562     else
6563       return ReplaceInstUsesWith(SI, FalseVal);
6564   }
6565
6566   if (SI.getType() == Type::BoolTy)
6567     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6568       if (C->getValue()) {
6569         // Change: A = select B, true, C --> A = or B, C
6570         return BinaryOperator::createOr(CondVal, FalseVal);
6571       } else {
6572         // Change: A = select B, false, C --> A = and !B, C
6573         Value *NotCond =
6574           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6575                                              "not."+CondVal->getName()), SI);
6576         return BinaryOperator::createAnd(NotCond, FalseVal);
6577       }
6578     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6579       if (C->getValue() == false) {
6580         // Change: A = select B, C, false --> A = and B, C
6581         return BinaryOperator::createAnd(CondVal, TrueVal);
6582       } else {
6583         // Change: A = select B, C, true --> A = or !B, C
6584         Value *NotCond =
6585           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6586                                              "not."+CondVal->getName()), SI);
6587         return BinaryOperator::createOr(NotCond, TrueVal);
6588       }
6589     }
6590
6591   // Selecting between two integer constants?
6592   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6593     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6594       // select C, 1, 0 -> cast C to int
6595       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6596         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6597       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6598         // select C, 0, 1 -> cast !C to int
6599         Value *NotCond =
6600           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6601                                                "not."+CondVal->getName()), SI);
6602         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6603       }
6604
6605       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6606
6607         // (x <s 0) ? -1 : 0 -> ashr x, 31
6608         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6609         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6610           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6611             bool CanXForm = false;
6612             if (IC->isSignedPredicate())
6613               CanXForm = CmpCst->isNullValue() && 
6614                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6615             else {
6616               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6617               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6618                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6619             }
6620             
6621             if (CanXForm) {
6622               // The comparison constant and the result are not neccessarily the
6623               // same width. Make an all-ones value by inserting a AShr.
6624               Value *X = IC->getOperand(0);
6625               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6626               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6627               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6628                                                ShAmt, "ones");
6629               InsertNewInstBefore(SRA, SI);
6630               
6631               // Finally, convert to the type of the select RHS.  We figure out
6632               // if this requires a SExt, Trunc or BitCast based on the sizes.
6633               Instruction::CastOps opc = Instruction::BitCast;
6634               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6635               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6636               if (SRASize < SISize)
6637                 opc = Instruction::SExt;
6638               else if (SRASize > SISize)
6639                 opc = Instruction::Trunc;
6640               return CastInst::create(opc, SRA, SI.getType());
6641             }
6642           }
6643
6644
6645         // If one of the constants is zero (we know they can't both be) and we
6646         // have a fcmp instruction with zero, and we have an 'and' with the
6647         // non-constant value, eliminate this whole mess.  This corresponds to
6648         // cases like this: ((X & 27) ? 27 : 0)
6649         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6650           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6651               cast<Constant>(IC->getOperand(1))->isNullValue())
6652             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6653               if (ICA->getOpcode() == Instruction::And &&
6654                   isa<ConstantInt>(ICA->getOperand(1)) &&
6655                   (ICA->getOperand(1) == TrueValC ||
6656                    ICA->getOperand(1) == FalseValC) &&
6657                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6658                 // Okay, now we know that everything is set up, we just don't
6659                 // know whether we have a icmp_ne or icmp_eq and whether the 
6660                 // true or false val is the zero.
6661                 bool ShouldNotVal = !TrueValC->isNullValue();
6662                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6663                 Value *V = ICA;
6664                 if (ShouldNotVal)
6665                   V = InsertNewInstBefore(BinaryOperator::create(
6666                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6667                 return ReplaceInstUsesWith(SI, V);
6668               }
6669       }
6670     }
6671
6672   // See if we are selecting two values based on a comparison of the two values.
6673   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6674     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6675       // Transform (X == Y) ? X : Y  -> Y
6676       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6677         return ReplaceInstUsesWith(SI, FalseVal);
6678       // Transform (X != Y) ? X : Y  -> X
6679       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6680         return ReplaceInstUsesWith(SI, TrueVal);
6681       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6682
6683     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6684       // Transform (X == Y) ? Y : X  -> X
6685       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6686         return ReplaceInstUsesWith(SI, FalseVal);
6687       // Transform (X != Y) ? Y : X  -> Y
6688       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6689         return ReplaceInstUsesWith(SI, TrueVal);
6690       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6691     }
6692   }
6693
6694   // See if we are selecting two values based on a comparison of the two values.
6695   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6696     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6697       // Transform (X == Y) ? X : Y  -> Y
6698       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6699         return ReplaceInstUsesWith(SI, FalseVal);
6700       // Transform (X != Y) ? X : Y  -> X
6701       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6702         return ReplaceInstUsesWith(SI, TrueVal);
6703       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6704
6705     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6706       // Transform (X == Y) ? Y : X  -> X
6707       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6708         return ReplaceInstUsesWith(SI, FalseVal);
6709       // Transform (X != Y) ? Y : X  -> Y
6710       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6711         return ReplaceInstUsesWith(SI, TrueVal);
6712       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6713     }
6714   }
6715
6716   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6717     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6718       if (TI->hasOneUse() && FI->hasOneUse()) {
6719         Instruction *AddOp = 0, *SubOp = 0;
6720
6721         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6722         if (TI->getOpcode() == FI->getOpcode())
6723           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6724             return IV;
6725
6726         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6727         // even legal for FP.
6728         if (TI->getOpcode() == Instruction::Sub &&
6729             FI->getOpcode() == Instruction::Add) {
6730           AddOp = FI; SubOp = TI;
6731         } else if (FI->getOpcode() == Instruction::Sub &&
6732                    TI->getOpcode() == Instruction::Add) {
6733           AddOp = TI; SubOp = FI;
6734         }
6735
6736         if (AddOp) {
6737           Value *OtherAddOp = 0;
6738           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6739             OtherAddOp = AddOp->getOperand(1);
6740           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6741             OtherAddOp = AddOp->getOperand(0);
6742           }
6743
6744           if (OtherAddOp) {
6745             // So at this point we know we have (Y -> OtherAddOp):
6746             //        select C, (add X, Y), (sub X, Z)
6747             Value *NegVal;  // Compute -Z
6748             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6749               NegVal = ConstantExpr::getNeg(C);
6750             } else {
6751               NegVal = InsertNewInstBefore(
6752                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6753             }
6754
6755             Value *NewTrueOp = OtherAddOp;
6756             Value *NewFalseOp = NegVal;
6757             if (AddOp != TI)
6758               std::swap(NewTrueOp, NewFalseOp);
6759             Instruction *NewSel =
6760               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6761
6762             NewSel = InsertNewInstBefore(NewSel, SI);
6763             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6764           }
6765         }
6766       }
6767
6768   // See if we can fold the select into one of our operands.
6769   if (SI.getType()->isInteger()) {
6770     // See the comment above GetSelectFoldableOperands for a description of the
6771     // transformation we are doing here.
6772     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6773       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6774           !isa<Constant>(FalseVal))
6775         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6776           unsigned OpToFold = 0;
6777           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6778             OpToFold = 1;
6779           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6780             OpToFold = 2;
6781           }
6782
6783           if (OpToFold) {
6784             Constant *C = GetSelectFoldableConstant(TVI);
6785             std::string Name = TVI->getName(); TVI->setName("");
6786             Instruction *NewSel =
6787               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6788                              Name);
6789             InsertNewInstBefore(NewSel, SI);
6790             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6791               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6792             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6793               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6794             else {
6795               assert(0 && "Unknown instruction!!");
6796             }
6797           }
6798         }
6799
6800     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6801       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6802           !isa<Constant>(TrueVal))
6803         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6804           unsigned OpToFold = 0;
6805           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6806             OpToFold = 1;
6807           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6808             OpToFold = 2;
6809           }
6810
6811           if (OpToFold) {
6812             Constant *C = GetSelectFoldableConstant(FVI);
6813             std::string Name = FVI->getName(); FVI->setName("");
6814             Instruction *NewSel =
6815               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6816                              Name);
6817             InsertNewInstBefore(NewSel, SI);
6818             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6819               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6820             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6821               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6822             else {
6823               assert(0 && "Unknown instruction!!");
6824             }
6825           }
6826         }
6827   }
6828
6829   if (BinaryOperator::isNot(CondVal)) {
6830     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6831     SI.setOperand(1, FalseVal);
6832     SI.setOperand(2, TrueVal);
6833     return &SI;
6834   }
6835
6836   return 0;
6837 }
6838
6839 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6840 /// determine, return it, otherwise return 0.
6841 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6842   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6843     unsigned Align = GV->getAlignment();
6844     if (Align == 0 && TD) 
6845       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6846     return Align;
6847   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6848     unsigned Align = AI->getAlignment();
6849     if (Align == 0 && TD) {
6850       if (isa<AllocaInst>(AI))
6851         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6852       else if (isa<MallocInst>(AI)) {
6853         // Malloc returns maximally aligned memory.
6854         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6855         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6856         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6857       }
6858     }
6859     return Align;
6860   } else if (isa<BitCastInst>(V) ||
6861              (isa<ConstantExpr>(V) && 
6862               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6863     User *CI = cast<User>(V);
6864     if (isa<PointerType>(CI->getOperand(0)->getType()))
6865       return GetKnownAlignment(CI->getOperand(0), TD);
6866     return 0;
6867   } else if (isa<GetElementPtrInst>(V) ||
6868              (isa<ConstantExpr>(V) && 
6869               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6870     User *GEPI = cast<User>(V);
6871     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6872     if (BaseAlignment == 0) return 0;
6873     
6874     // If all indexes are zero, it is just the alignment of the base pointer.
6875     bool AllZeroOperands = true;
6876     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6877       if (!isa<Constant>(GEPI->getOperand(i)) ||
6878           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6879         AllZeroOperands = false;
6880         break;
6881       }
6882     if (AllZeroOperands)
6883       return BaseAlignment;
6884     
6885     // Otherwise, if the base alignment is >= the alignment we expect for the
6886     // base pointer type, then we know that the resultant pointer is aligned at
6887     // least as much as its type requires.
6888     if (!TD) return 0;
6889
6890     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6891     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6892         <= BaseAlignment) {
6893       const Type *GEPTy = GEPI->getType();
6894       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6895     }
6896     return 0;
6897   }
6898   return 0;
6899 }
6900
6901
6902 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6903 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6904 /// the heavy lifting.
6905 ///
6906 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6907   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6908   if (!II) return visitCallSite(&CI);
6909   
6910   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6911   // visitCallSite.
6912   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6913     bool Changed = false;
6914
6915     // memmove/cpy/set of zero bytes is a noop.
6916     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6917       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6918
6919       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6920         if (CI->getZExtValue() == 1) {
6921           // Replace the instruction with just byte operations.  We would
6922           // transform other cases to loads/stores, but we don't know if
6923           // alignment is sufficient.
6924         }
6925     }
6926
6927     // If we have a memmove and the source operation is a constant global,
6928     // then the source and dest pointers can't alias, so we can change this
6929     // into a call to memcpy.
6930     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6931       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6932         if (GVSrc->isConstant()) {
6933           Module *M = CI.getParent()->getParent()->getParent();
6934           const char *Name;
6935           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6936               Type::Int32Ty)
6937             Name = "llvm.memcpy.i32";
6938           else
6939             Name = "llvm.memcpy.i64";
6940           Function *MemCpy = M->getOrInsertFunction(Name,
6941                                      CI.getCalledFunction()->getFunctionType());
6942           CI.setOperand(0, MemCpy);
6943           Changed = true;
6944         }
6945     }
6946
6947     // If we can determine a pointer alignment that is bigger than currently
6948     // set, update the alignment.
6949     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6950       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6951       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6952       unsigned Align = std::min(Alignment1, Alignment2);
6953       if (MI->getAlignment()->getZExtValue() < Align) {
6954         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
6955         Changed = true;
6956       }
6957     } else if (isa<MemSetInst>(MI)) {
6958       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6959       if (MI->getAlignment()->getZExtValue() < Alignment) {
6960         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
6961         Changed = true;
6962       }
6963     }
6964           
6965     if (Changed) return II;
6966   } else {
6967     switch (II->getIntrinsicID()) {
6968     default: break;
6969     case Intrinsic::ppc_altivec_lvx:
6970     case Intrinsic::ppc_altivec_lvxl:
6971     case Intrinsic::x86_sse_loadu_ps:
6972     case Intrinsic::x86_sse2_loadu_pd:
6973     case Intrinsic::x86_sse2_loadu_dq:
6974       // Turn PPC lvx     -> load if the pointer is known aligned.
6975       // Turn X86 loadups -> load if the pointer is known aligned.
6976       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6977         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6978                                       PointerType::get(II->getType()), CI);
6979         return new LoadInst(Ptr);
6980       }
6981       break;
6982     case Intrinsic::ppc_altivec_stvx:
6983     case Intrinsic::ppc_altivec_stvxl:
6984       // Turn stvx -> store if the pointer is known aligned.
6985       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6986         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6987         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
6988                                       OpPtrTy, CI);
6989         return new StoreInst(II->getOperand(1), Ptr);
6990       }
6991       break;
6992     case Intrinsic::x86_sse_storeu_ps:
6993     case Intrinsic::x86_sse2_storeu_pd:
6994     case Intrinsic::x86_sse2_storeu_dq:
6995     case Intrinsic::x86_sse2_storel_dq:
6996       // Turn X86 storeu -> store if the pointer is known aligned.
6997       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6998         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6999         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7000                                       OpPtrTy, CI);
7001         return new StoreInst(II->getOperand(2), Ptr);
7002       }
7003       break;
7004       
7005     case Intrinsic::x86_sse_cvttss2si: {
7006       // These intrinsics only demands the 0th element of its input vector.  If
7007       // we can simplify the input based on that, do so now.
7008       uint64_t UndefElts;
7009       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7010                                                 UndefElts)) {
7011         II->setOperand(1, V);
7012         return II;
7013       }
7014       break;
7015     }
7016       
7017     case Intrinsic::ppc_altivec_vperm:
7018       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7019       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7020         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7021         
7022         // Check that all of the elements are integer constants or undefs.
7023         bool AllEltsOk = true;
7024         for (unsigned i = 0; i != 16; ++i) {
7025           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7026               !isa<UndefValue>(Mask->getOperand(i))) {
7027             AllEltsOk = false;
7028             break;
7029           }
7030         }
7031         
7032         if (AllEltsOk) {
7033           // Cast the input vectors to byte vectors.
7034           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7035                                         II->getOperand(1), Mask->getType(), CI);
7036           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7037                                         II->getOperand(2), Mask->getType(), CI);
7038           Value *Result = UndefValue::get(Op0->getType());
7039           
7040           // Only extract each element once.
7041           Value *ExtractedElts[32];
7042           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7043           
7044           for (unsigned i = 0; i != 16; ++i) {
7045             if (isa<UndefValue>(Mask->getOperand(i)))
7046               continue;
7047             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7048             Idx &= 31;  // Match the hardware behavior.
7049             
7050             if (ExtractedElts[Idx] == 0) {
7051               Instruction *Elt = 
7052                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7053               InsertNewInstBefore(Elt, CI);
7054               ExtractedElts[Idx] = Elt;
7055             }
7056           
7057             // Insert this value into the result vector.
7058             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7059             InsertNewInstBefore(cast<Instruction>(Result), CI);
7060           }
7061           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7062         }
7063       }
7064       break;
7065
7066     case Intrinsic::stackrestore: {
7067       // If the save is right next to the restore, remove the restore.  This can
7068       // happen when variable allocas are DCE'd.
7069       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7070         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7071           BasicBlock::iterator BI = SS;
7072           if (&*++BI == II)
7073             return EraseInstFromFunction(CI);
7074         }
7075       }
7076       
7077       // If the stack restore is in a return/unwind block and if there are no
7078       // allocas or calls between the restore and the return, nuke the restore.
7079       TerminatorInst *TI = II->getParent()->getTerminator();
7080       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7081         BasicBlock::iterator BI = II;
7082         bool CannotRemove = false;
7083         for (++BI; &*BI != TI; ++BI) {
7084           if (isa<AllocaInst>(BI) ||
7085               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7086             CannotRemove = true;
7087             break;
7088           }
7089         }
7090         if (!CannotRemove)
7091           return EraseInstFromFunction(CI);
7092       }
7093       break;
7094     }
7095     }
7096   }
7097
7098   return visitCallSite(II);
7099 }
7100
7101 // InvokeInst simplification
7102 //
7103 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7104   return visitCallSite(&II);
7105 }
7106
7107 // visitCallSite - Improvements for call and invoke instructions.
7108 //
7109 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7110   bool Changed = false;
7111
7112   // If the callee is a constexpr cast of a function, attempt to move the cast
7113   // to the arguments of the call/invoke.
7114   if (transformConstExprCastCall(CS)) return 0;
7115
7116   Value *Callee = CS.getCalledValue();
7117
7118   if (Function *CalleeF = dyn_cast<Function>(Callee))
7119     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7120       Instruction *OldCall = CS.getInstruction();
7121       // If the call and callee calling conventions don't match, this call must
7122       // be unreachable, as the call is undefined.
7123       new StoreInst(ConstantBool::getTrue(),
7124                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7125       if (!OldCall->use_empty())
7126         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7127       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7128         return EraseInstFromFunction(*OldCall);
7129       return 0;
7130     }
7131
7132   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7133     // This instruction is not reachable, just remove it.  We insert a store to
7134     // undef so that we know that this code is not reachable, despite the fact
7135     // that we can't modify the CFG here.
7136     new StoreInst(ConstantBool::getTrue(),
7137                   UndefValue::get(PointerType::get(Type::BoolTy)),
7138                   CS.getInstruction());
7139
7140     if (!CS.getInstruction()->use_empty())
7141       CS.getInstruction()->
7142         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7143
7144     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7145       // Don't break the CFG, insert a dummy cond branch.
7146       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7147                      ConstantBool::getTrue(), II);
7148     }
7149     return EraseInstFromFunction(*CS.getInstruction());
7150   }
7151
7152   const PointerType *PTy = cast<PointerType>(Callee->getType());
7153   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7154   if (FTy->isVarArg()) {
7155     // See if we can optimize any arguments passed through the varargs area of
7156     // the call.
7157     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7158            E = CS.arg_end(); I != E; ++I)
7159       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7160         // If this cast does not effect the value passed through the varargs
7161         // area, we can eliminate the use of the cast.
7162         Value *Op = CI->getOperand(0);
7163         if (CI->isLosslessCast()) {
7164           *I = Op;
7165           Changed = true;
7166         }
7167       }
7168   }
7169
7170   return Changed ? CS.getInstruction() : 0;
7171 }
7172
7173 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7174 // attempt to move the cast to the arguments of the call/invoke.
7175 //
7176 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7177   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7178   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7179   if (CE->getOpcode() != Instruction::BitCast || 
7180       !isa<Function>(CE->getOperand(0)))
7181     return false;
7182   Function *Callee = cast<Function>(CE->getOperand(0));
7183   Instruction *Caller = CS.getInstruction();
7184
7185   // Okay, this is a cast from a function to a different type.  Unless doing so
7186   // would cause a type conversion of one of our arguments, change this call to
7187   // be a direct call with arguments casted to the appropriate types.
7188   //
7189   const FunctionType *FT = Callee->getFunctionType();
7190   const Type *OldRetTy = Caller->getType();
7191
7192   // Check to see if we are changing the return type...
7193   if (OldRetTy != FT->getReturnType()) {
7194     if (Callee->isExternal() &&
7195         !Caller->use_empty() && 
7196         !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
7197           (isa<PointerType>(FT->getReturnType()) && 
7198            TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7199         )
7200       return false;   // Cannot transform this return value...
7201
7202     // If the callsite is an invoke instruction, and the return value is used by
7203     // a PHI node in a successor, we cannot change the return type of the call
7204     // because there is no place to put the cast instruction (without breaking
7205     // the critical edge).  Bail out in this case.
7206     if (!Caller->use_empty())
7207       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7208         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7209              UI != E; ++UI)
7210           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7211             if (PN->getParent() == II->getNormalDest() ||
7212                 PN->getParent() == II->getUnwindDest())
7213               return false;
7214   }
7215
7216   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7217   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7218
7219   CallSite::arg_iterator AI = CS.arg_begin();
7220   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7221     const Type *ParamTy = FT->getParamType(i);
7222     const Type *ActTy = (*AI)->getType();
7223     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7224     //Either we can cast directly, or we can upconvert the argument
7225     bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
7226       (ParamTy->isIntegral() && ActTy->isIntegral() &&
7227        ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7228       (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
7229        c->getSExtValue() > 0);
7230     if (Callee->isExternal() && !isConvertible) return false;
7231   }
7232
7233   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7234       Callee->isExternal())
7235     return false;   // Do not delete arguments unless we have a function body...
7236
7237   // Okay, we decided that this is a safe thing to do: go ahead and start
7238   // inserting cast instructions as necessary...
7239   std::vector<Value*> Args;
7240   Args.reserve(NumActualArgs);
7241
7242   AI = CS.arg_begin();
7243   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7244     const Type *ParamTy = FT->getParamType(i);
7245     if ((*AI)->getType() == ParamTy) {
7246       Args.push_back(*AI);
7247     } else {
7248       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7249           false, ParamTy, false);
7250       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7251       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7252     }
7253   }
7254
7255   // If the function takes more arguments than the call was taking, add them
7256   // now...
7257   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7258     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7259
7260   // If we are removing arguments to the function, emit an obnoxious warning...
7261   if (FT->getNumParams() < NumActualArgs)
7262     if (!FT->isVarArg()) {
7263       cerr << "WARNING: While resolving call to function '"
7264            << Callee->getName() << "' arguments were dropped!\n";
7265     } else {
7266       // Add all of the arguments in their promoted form to the arg list...
7267       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7268         const Type *PTy = getPromotedType((*AI)->getType());
7269         if (PTy != (*AI)->getType()) {
7270           // Must promote to pass through va_arg area!
7271           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7272                                                                 PTy, false);
7273           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7274           InsertNewInstBefore(Cast, *Caller);
7275           Args.push_back(Cast);
7276         } else {
7277           Args.push_back(*AI);
7278         }
7279       }
7280     }
7281
7282   if (FT->getReturnType() == Type::VoidTy)
7283     Caller->setName("");   // Void type should not have a name...
7284
7285   Instruction *NC;
7286   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7287     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7288                         Args, Caller->getName(), Caller);
7289     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7290   } else {
7291     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7292     if (cast<CallInst>(Caller)->isTailCall())
7293       cast<CallInst>(NC)->setTailCall();
7294    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7295   }
7296
7297   // Insert a cast of the return type as necessary...
7298   Value *NV = NC;
7299   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7300     if (NV->getType() != Type::VoidTy) {
7301       const Type *CallerTy = Caller->getType();
7302       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7303                                                             CallerTy, false);
7304       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7305
7306       // If this is an invoke instruction, we should insert it after the first
7307       // non-phi, instruction in the normal successor block.
7308       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7309         BasicBlock::iterator I = II->getNormalDest()->begin();
7310         while (isa<PHINode>(I)) ++I;
7311         InsertNewInstBefore(NC, *I);
7312       } else {
7313         // Otherwise, it's a call, just insert cast right after the call instr
7314         InsertNewInstBefore(NC, *Caller);
7315       }
7316       AddUsersToWorkList(*Caller);
7317     } else {
7318       NV = UndefValue::get(Caller->getType());
7319     }
7320   }
7321
7322   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7323     Caller->replaceAllUsesWith(NV);
7324   Caller->getParent()->getInstList().erase(Caller);
7325   removeFromWorkList(Caller);
7326   return true;
7327 }
7328
7329 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7330 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7331 /// and a single binop.
7332 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7333   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7334   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7335          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7336   unsigned Opc = FirstInst->getOpcode();
7337   Value *LHSVal = FirstInst->getOperand(0);
7338   Value *RHSVal = FirstInst->getOperand(1);
7339     
7340   const Type *LHSType = LHSVal->getType();
7341   const Type *RHSType = RHSVal->getType();
7342   
7343   // Scan to see if all operands are the same opcode, all have one use, and all
7344   // kill their operands (i.e. the operands have one use).
7345   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7346     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7347     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7348         // Verify type of the LHS matches so we don't fold cmp's of different
7349         // types or GEP's with different index types.
7350         I->getOperand(0)->getType() != LHSType ||
7351         I->getOperand(1)->getType() != RHSType)
7352       return 0;
7353
7354     // If they are CmpInst instructions, check their predicates
7355     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7356       if (cast<CmpInst>(I)->getPredicate() !=
7357           cast<CmpInst>(FirstInst)->getPredicate())
7358         return 0;
7359     
7360     // Keep track of which operand needs a phi node.
7361     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7362     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7363   }
7364   
7365   // Otherwise, this is safe to transform, determine if it is profitable.
7366
7367   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7368   // Indexes are often folded into load/store instructions, so we don't want to
7369   // hide them behind a phi.
7370   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7371     return 0;
7372   
7373   Value *InLHS = FirstInst->getOperand(0);
7374   Value *InRHS = FirstInst->getOperand(1);
7375   PHINode *NewLHS = 0, *NewRHS = 0;
7376   if (LHSVal == 0) {
7377     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7378     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7379     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7380     InsertNewInstBefore(NewLHS, PN);
7381     LHSVal = NewLHS;
7382   }
7383   
7384   if (RHSVal == 0) {
7385     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7386     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7387     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7388     InsertNewInstBefore(NewRHS, PN);
7389     RHSVal = NewRHS;
7390   }
7391   
7392   // Add all operands to the new PHIs.
7393   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7394     if (NewLHS) {
7395       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7396       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7397     }
7398     if (NewRHS) {
7399       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7400       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7401     }
7402   }
7403     
7404   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7405     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7406   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7407     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7408                            RHSVal);
7409   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7410     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7411   else {
7412     assert(isa<GetElementPtrInst>(FirstInst));
7413     return new GetElementPtrInst(LHSVal, RHSVal);
7414   }
7415 }
7416
7417 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7418 /// of the block that defines it.  This means that it must be obvious the value
7419 /// of the load is not changed from the point of the load to the end of the
7420 /// block it is in.
7421 static bool isSafeToSinkLoad(LoadInst *L) {
7422   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7423   
7424   for (++BBI; BBI != E; ++BBI)
7425     if (BBI->mayWriteToMemory())
7426       return false;
7427   return true;
7428 }
7429
7430
7431 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7432 // operator and they all are only used by the PHI, PHI together their
7433 // inputs, and do the operation once, to the result of the PHI.
7434 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7435   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7436
7437   // Scan the instruction, looking for input operations that can be folded away.
7438   // If all input operands to the phi are the same instruction (e.g. a cast from
7439   // the same type or "+42") we can pull the operation through the PHI, reducing
7440   // code size and simplifying code.
7441   Constant *ConstantOp = 0;
7442   const Type *CastSrcTy = 0;
7443   bool isVolatile = false;
7444   if (isa<CastInst>(FirstInst)) {
7445     CastSrcTy = FirstInst->getOperand(0)->getType();
7446   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7447              isa<CmpInst>(FirstInst)) {
7448     // Can fold binop, compare or shift here if the RHS is a constant, 
7449     // otherwise call FoldPHIArgBinOpIntoPHI.
7450     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7451     if (ConstantOp == 0)
7452       return FoldPHIArgBinOpIntoPHI(PN);
7453   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7454     isVolatile = LI->isVolatile();
7455     // We can't sink the load if the loaded value could be modified between the
7456     // load and the PHI.
7457     if (LI->getParent() != PN.getIncomingBlock(0) ||
7458         !isSafeToSinkLoad(LI))
7459       return 0;
7460   } else if (isa<GetElementPtrInst>(FirstInst)) {
7461     if (FirstInst->getNumOperands() == 2)
7462       return FoldPHIArgBinOpIntoPHI(PN);
7463     // Can't handle general GEPs yet.
7464     return 0;
7465   } else {
7466     return 0;  // Cannot fold this operation.
7467   }
7468
7469   // Check to see if all arguments are the same operation.
7470   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7471     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7472     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7473     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7474       return 0;
7475     if (CastSrcTy) {
7476       if (I->getOperand(0)->getType() != CastSrcTy)
7477         return 0;  // Cast operation must match.
7478     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7479       // We can't sink the load if the loaded value could be modified between 
7480       // the load and the PHI.
7481       if (LI->isVolatile() != isVolatile ||
7482           LI->getParent() != PN.getIncomingBlock(i) ||
7483           !isSafeToSinkLoad(LI))
7484         return 0;
7485     } else if (I->getOperand(1) != ConstantOp) {
7486       return 0;
7487     }
7488   }
7489
7490   // Okay, they are all the same operation.  Create a new PHI node of the
7491   // correct type, and PHI together all of the LHS's of the instructions.
7492   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7493                                PN.getName()+".in");
7494   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7495
7496   Value *InVal = FirstInst->getOperand(0);
7497   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7498
7499   // Add all operands to the new PHI.
7500   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7501     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7502     if (NewInVal != InVal)
7503       InVal = 0;
7504     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7505   }
7506
7507   Value *PhiVal;
7508   if (InVal) {
7509     // The new PHI unions all of the same values together.  This is really
7510     // common, so we handle it intelligently here for compile-time speed.
7511     PhiVal = InVal;
7512     delete NewPN;
7513   } else {
7514     InsertNewInstBefore(NewPN, PN);
7515     PhiVal = NewPN;
7516   }
7517
7518   // Insert and return the new operation.
7519   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7520     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7521   else if (isa<LoadInst>(FirstInst))
7522     return new LoadInst(PhiVal, "", isVolatile);
7523   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7524     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7525   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7526     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7527                            PhiVal, ConstantOp);
7528   else
7529     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7530                          PhiVal, ConstantOp);
7531 }
7532
7533 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7534 /// that is dead.
7535 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7536   if (PN->use_empty()) return true;
7537   if (!PN->hasOneUse()) return false;
7538
7539   // Remember this node, and if we find the cycle, return.
7540   if (!PotentiallyDeadPHIs.insert(PN).second)
7541     return true;
7542
7543   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7544     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7545
7546   return false;
7547 }
7548
7549 // PHINode simplification
7550 //
7551 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7552   // If LCSSA is around, don't mess with Phi nodes
7553   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7554   
7555   if (Value *V = PN.hasConstantValue())
7556     return ReplaceInstUsesWith(PN, V);
7557
7558   // If all PHI operands are the same operation, pull them through the PHI,
7559   // reducing code size.
7560   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7561       PN.getIncomingValue(0)->hasOneUse())
7562     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7563       return Result;
7564
7565   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7566   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7567   // PHI)... break the cycle.
7568   if (PN.hasOneUse())
7569     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7570       std::set<PHINode*> PotentiallyDeadPHIs;
7571       PotentiallyDeadPHIs.insert(&PN);
7572       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7573         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7574     }
7575
7576   return 0;
7577 }
7578
7579 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7580                                    Instruction *InsertPoint,
7581                                    InstCombiner *IC) {
7582   unsigned PtrSize = DTy->getPrimitiveSize();
7583   unsigned VTySize = V->getType()->getPrimitiveSize();
7584   // We must cast correctly to the pointer type. Ensure that we
7585   // sign extend the integer value if it is smaller as this is
7586   // used for address computation.
7587   Instruction::CastOps opcode = 
7588      (VTySize < PtrSize ? Instruction::SExt :
7589       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7590   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7591 }
7592
7593
7594 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7595   Value *PtrOp = GEP.getOperand(0);
7596   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7597   // If so, eliminate the noop.
7598   if (GEP.getNumOperands() == 1)
7599     return ReplaceInstUsesWith(GEP, PtrOp);
7600
7601   if (isa<UndefValue>(GEP.getOperand(0)))
7602     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7603
7604   bool HasZeroPointerIndex = false;
7605   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7606     HasZeroPointerIndex = C->isNullValue();
7607
7608   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7609     return ReplaceInstUsesWith(GEP, PtrOp);
7610
7611   // Eliminate unneeded casts for indices.
7612   bool MadeChange = false;
7613   gep_type_iterator GTI = gep_type_begin(GEP);
7614   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7615     if (isa<SequentialType>(*GTI)) {
7616       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7617         Value *Src = CI->getOperand(0);
7618         const Type *SrcTy = Src->getType();
7619         const Type *DestTy = CI->getType();
7620         if (Src->getType()->isInteger()) {
7621           if (SrcTy->getPrimitiveSizeInBits() ==
7622                        DestTy->getPrimitiveSizeInBits()) {
7623             // We can always eliminate a cast from ulong or long to the other.
7624             // We can always eliminate a cast from uint to int or the other on
7625             // 32-bit pointer platforms.
7626             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7627               MadeChange = true;
7628               GEP.setOperand(i, Src);
7629             }
7630           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7631                      SrcTy->getPrimitiveSize() == 4) {
7632             // We can eliminate a cast from [u]int to [u]long iff the target 
7633             // is a 32-bit pointer target.
7634             if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7635               MadeChange = true;
7636               GEP.setOperand(i, Src);
7637             }
7638           }
7639         }
7640       }
7641       // If we are using a wider index than needed for this platform, shrink it
7642       // to what we need.  If the incoming value needs a cast instruction,
7643       // insert it.  This explicit cast can make subsequent optimizations more
7644       // obvious.
7645       Value *Op = GEP.getOperand(i);
7646       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7647         if (Constant *C = dyn_cast<Constant>(Op)) {
7648           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7649           MadeChange = true;
7650         } else {
7651           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7652                                 GEP);
7653           GEP.setOperand(i, Op);
7654           MadeChange = true;
7655         }
7656     }
7657   if (MadeChange) return &GEP;
7658
7659   // Combine Indices - If the source pointer to this getelementptr instruction
7660   // is a getelementptr instruction, combine the indices of the two
7661   // getelementptr instructions into a single instruction.
7662   //
7663   std::vector<Value*> SrcGEPOperands;
7664   if (User *Src = dyn_castGetElementPtr(PtrOp))
7665     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7666
7667   if (!SrcGEPOperands.empty()) {
7668     // Note that if our source is a gep chain itself that we wait for that
7669     // chain to be resolved before we perform this transformation.  This
7670     // avoids us creating a TON of code in some cases.
7671     //
7672     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7673         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7674       return 0;   // Wait until our source is folded to completion.
7675
7676     std::vector<Value *> Indices;
7677
7678     // Find out whether the last index in the source GEP is a sequential idx.
7679     bool EndsWithSequential = false;
7680     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7681            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7682       EndsWithSequential = !isa<StructType>(*I);
7683
7684     // Can we combine the two pointer arithmetics offsets?
7685     if (EndsWithSequential) {
7686       // Replace: gep (gep %P, long B), long A, ...
7687       // With:    T = long A+B; gep %P, T, ...
7688       //
7689       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7690       if (SO1 == Constant::getNullValue(SO1->getType())) {
7691         Sum = GO1;
7692       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7693         Sum = SO1;
7694       } else {
7695         // If they aren't the same type, convert both to an integer of the
7696         // target's pointer size.
7697         if (SO1->getType() != GO1->getType()) {
7698           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7699             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7700           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7701             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7702           } else {
7703             unsigned PS = TD->getPointerSize();
7704             if (SO1->getType()->getPrimitiveSize() == PS) {
7705               // Convert GO1 to SO1's type.
7706               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7707
7708             } else if (GO1->getType()->getPrimitiveSize() == PS) {
7709               // Convert SO1 to GO1's type.
7710               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7711             } else {
7712               const Type *PT = TD->getIntPtrType();
7713               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7714               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7715             }
7716           }
7717         }
7718         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7719           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7720         else {
7721           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7722           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7723         }
7724       }
7725
7726       // Recycle the GEP we already have if possible.
7727       if (SrcGEPOperands.size() == 2) {
7728         GEP.setOperand(0, SrcGEPOperands[0]);
7729         GEP.setOperand(1, Sum);
7730         return &GEP;
7731       } else {
7732         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7733                        SrcGEPOperands.end()-1);
7734         Indices.push_back(Sum);
7735         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7736       }
7737     } else if (isa<Constant>(*GEP.idx_begin()) &&
7738                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7739                SrcGEPOperands.size() != 1) {
7740       // Otherwise we can do the fold if the first index of the GEP is a zero
7741       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7742                      SrcGEPOperands.end());
7743       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7744     }
7745
7746     if (!Indices.empty())
7747       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7748
7749   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7750     // GEP of global variable.  If all of the indices for this GEP are
7751     // constants, we can promote this to a constexpr instead of an instruction.
7752
7753     // Scan for nonconstants...
7754     std::vector<Constant*> Indices;
7755     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7756     for (; I != E && isa<Constant>(*I); ++I)
7757       Indices.push_back(cast<Constant>(*I));
7758
7759     if (I == E) {  // If they are all constants...
7760       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7761
7762       // Replace all uses of the GEP with the new constexpr...
7763       return ReplaceInstUsesWith(GEP, CE);
7764     }
7765   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7766     if (!isa<PointerType>(X->getType())) {
7767       // Not interesting.  Source pointer must be a cast from pointer.
7768     } else if (HasZeroPointerIndex) {
7769       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7770       // into     : GEP [10 x ubyte]* X, long 0, ...
7771       //
7772       // This occurs when the program declares an array extern like "int X[];"
7773       //
7774       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7775       const PointerType *XTy = cast<PointerType>(X->getType());
7776       if (const ArrayType *XATy =
7777           dyn_cast<ArrayType>(XTy->getElementType()))
7778         if (const ArrayType *CATy =
7779             dyn_cast<ArrayType>(CPTy->getElementType()))
7780           if (CATy->getElementType() == XATy->getElementType()) {
7781             // At this point, we know that the cast source type is a pointer
7782             // to an array of the same type as the destination pointer
7783             // array.  Because the array type is never stepped over (there
7784             // is a leading zero) we can fold the cast into this GEP.
7785             GEP.setOperand(0, X);
7786             return &GEP;
7787           }
7788     } else if (GEP.getNumOperands() == 2) {
7789       // Transform things like:
7790       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7791       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7792       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7793       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7794       if (isa<ArrayType>(SrcElTy) &&
7795           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7796           TD->getTypeSize(ResElTy)) {
7797         Value *V = InsertNewInstBefore(
7798                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7799                                      GEP.getOperand(1), GEP.getName()), GEP);
7800         // V and GEP are both pointer types --> BitCast
7801         return new BitCastInst(V, GEP.getType());
7802       }
7803       
7804       // Transform things like:
7805       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7806       //   (where tmp = 8*tmp2) into:
7807       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7808       
7809       if (isa<ArrayType>(SrcElTy) &&
7810           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7811         uint64_t ArrayEltSize =
7812             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7813         
7814         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7815         // allow either a mul, shift, or constant here.
7816         Value *NewIdx = 0;
7817         ConstantInt *Scale = 0;
7818         if (ArrayEltSize == 1) {
7819           NewIdx = GEP.getOperand(1);
7820           Scale = ConstantInt::get(NewIdx->getType(), 1);
7821         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7822           NewIdx = ConstantInt::get(CI->getType(), 1);
7823           Scale = CI;
7824         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7825           if (Inst->getOpcode() == Instruction::Shl &&
7826               isa<ConstantInt>(Inst->getOperand(1))) {
7827             unsigned ShAmt =
7828               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7829             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7830             NewIdx = Inst->getOperand(0);
7831           } else if (Inst->getOpcode() == Instruction::Mul &&
7832                      isa<ConstantInt>(Inst->getOperand(1))) {
7833             Scale = cast<ConstantInt>(Inst->getOperand(1));
7834             NewIdx = Inst->getOperand(0);
7835           }
7836         }
7837
7838         // If the index will be to exactly the right offset with the scale taken
7839         // out, perform the transformation.
7840         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7841           if (isa<ConstantInt>(Scale))
7842             Scale = ConstantInt::get(Scale->getType(),
7843                                       Scale->getZExtValue() / ArrayEltSize);
7844           if (Scale->getZExtValue() != 1) {
7845             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7846                                                        true /*SExt*/);
7847             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7848             NewIdx = InsertNewInstBefore(Sc, GEP);
7849           }
7850
7851           // Insert the new GEP instruction.
7852           Instruction *NewGEP =
7853             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7854                                   NewIdx, GEP.getName());
7855           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7856           // The NewGEP must be pointer typed, so must the old one -> BitCast
7857           return new BitCastInst(NewGEP, GEP.getType());
7858         }
7859       }
7860     }
7861   }
7862
7863   return 0;
7864 }
7865
7866 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7867   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7868   if (AI.isArrayAllocation())    // Check C != 1
7869     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7870       const Type *NewTy = 
7871         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7872       AllocationInst *New = 0;
7873
7874       // Create and insert the replacement instruction...
7875       if (isa<MallocInst>(AI))
7876         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7877       else {
7878         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7879         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7880       }
7881
7882       InsertNewInstBefore(New, AI);
7883
7884       // Scan to the end of the allocation instructions, to skip over a block of
7885       // allocas if possible...
7886       //
7887       BasicBlock::iterator It = New;
7888       while (isa<AllocationInst>(*It)) ++It;
7889
7890       // Now that I is pointing to the first non-allocation-inst in the block,
7891       // insert our getelementptr instruction...
7892       //
7893       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7894       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7895                                        New->getName()+".sub", It);
7896
7897       // Now make everything use the getelementptr instead of the original
7898       // allocation.
7899       return ReplaceInstUsesWith(AI, V);
7900     } else if (isa<UndefValue>(AI.getArraySize())) {
7901       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7902     }
7903
7904   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7905   // Note that we only do this for alloca's, because malloc should allocate and
7906   // return a unique pointer, even for a zero byte allocation.
7907   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7908       TD->getTypeSize(AI.getAllocatedType()) == 0)
7909     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7910
7911   return 0;
7912 }
7913
7914 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7915   Value *Op = FI.getOperand(0);
7916
7917   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7918   if (CastInst *CI = dyn_cast<CastInst>(Op))
7919     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7920       FI.setOperand(0, CI->getOperand(0));
7921       return &FI;
7922     }
7923
7924   // free undef -> unreachable.
7925   if (isa<UndefValue>(Op)) {
7926     // Insert a new store to null because we cannot modify the CFG here.
7927     new StoreInst(ConstantBool::getTrue(),
7928                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7929     return EraseInstFromFunction(FI);
7930   }
7931
7932   // If we have 'free null' delete the instruction.  This can happen in stl code
7933   // when lots of inlining happens.
7934   if (isa<ConstantPointerNull>(Op))
7935     return EraseInstFromFunction(FI);
7936
7937   return 0;
7938 }
7939
7940
7941 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7942 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7943   User *CI = cast<User>(LI.getOperand(0));
7944   Value *CastOp = CI->getOperand(0);
7945
7946   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7947   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7948     const Type *SrcPTy = SrcTy->getElementType();
7949
7950     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7951         isa<PackedType>(DestPTy)) {
7952       // If the source is an array, the code below will not succeed.  Check to
7953       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7954       // constants.
7955       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7956         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7957           if (ASrcTy->getNumElements() != 0) {
7958             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
7959             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7960             SrcTy = cast<PointerType>(CastOp->getType());
7961             SrcPTy = SrcTy->getElementType();
7962           }
7963
7964       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7965            isa<PackedType>(SrcPTy)) &&
7966           // Do not allow turning this into a load of an integer, which is then
7967           // casted to a pointer, this pessimizes pointer analysis a lot.
7968           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7969           IC.getTargetData().getTypeSize(SrcPTy) ==
7970                IC.getTargetData().getTypeSize(DestPTy)) {
7971
7972         // Okay, we are casting from one integer or pointer type to another of
7973         // the same size.  Instead of casting the pointer before the load, cast
7974         // the result of the loaded value.
7975         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7976                                                              CI->getName(),
7977                                                          LI.isVolatile()),LI);
7978         // Now cast the result of the load.
7979         return new BitCastInst(NewLoad, LI.getType());
7980       }
7981     }
7982   }
7983   return 0;
7984 }
7985
7986 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7987 /// from this value cannot trap.  If it is not obviously safe to load from the
7988 /// specified pointer, we do a quick local scan of the basic block containing
7989 /// ScanFrom, to determine if the address is already accessed.
7990 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7991   // If it is an alloca or global variable, it is always safe to load from.
7992   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7993
7994   // Otherwise, be a little bit agressive by scanning the local block where we
7995   // want to check to see if the pointer is already being loaded or stored
7996   // from/to.  If so, the previous load or store would have already trapped,
7997   // so there is no harm doing an extra load (also, CSE will later eliminate
7998   // the load entirely).
7999   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8000
8001   while (BBI != E) {
8002     --BBI;
8003
8004     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8005       if (LI->getOperand(0) == V) return true;
8006     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8007       if (SI->getOperand(1) == V) return true;
8008
8009   }
8010   return false;
8011 }
8012
8013 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8014   Value *Op = LI.getOperand(0);
8015
8016   // load (cast X) --> cast (load X) iff safe
8017   if (isa<CastInst>(Op))
8018     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8019       return Res;
8020
8021   // None of the following transforms are legal for volatile loads.
8022   if (LI.isVolatile()) return 0;
8023   
8024   if (&LI.getParent()->front() != &LI) {
8025     BasicBlock::iterator BBI = &LI; --BBI;
8026     // If the instruction immediately before this is a store to the same
8027     // address, do a simple form of store->load forwarding.
8028     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8029       if (SI->getOperand(1) == LI.getOperand(0))
8030         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8031     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8032       if (LIB->getOperand(0) == LI.getOperand(0))
8033         return ReplaceInstUsesWith(LI, LIB);
8034   }
8035
8036   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8037     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8038         isa<UndefValue>(GEPI->getOperand(0))) {
8039       // Insert a new store to null instruction before the load to indicate
8040       // that this code is not reachable.  We do this instead of inserting
8041       // an unreachable instruction directly because we cannot modify the
8042       // CFG.
8043       new StoreInst(UndefValue::get(LI.getType()),
8044                     Constant::getNullValue(Op->getType()), &LI);
8045       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8046     }
8047
8048   if (Constant *C = dyn_cast<Constant>(Op)) {
8049     // load null/undef -> undef
8050     if ((C->isNullValue() || isa<UndefValue>(C))) {
8051       // Insert a new store to null instruction before the load to indicate that
8052       // this code is not reachable.  We do this instead of inserting an
8053       // unreachable instruction directly because we cannot modify the CFG.
8054       new StoreInst(UndefValue::get(LI.getType()),
8055                     Constant::getNullValue(Op->getType()), &LI);
8056       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8057     }
8058
8059     // Instcombine load (constant global) into the value loaded.
8060     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8061       if (GV->isConstant() && !GV->isExternal())
8062         return ReplaceInstUsesWith(LI, GV->getInitializer());
8063
8064     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8065     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8066       if (CE->getOpcode() == Instruction::GetElementPtr) {
8067         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8068           if (GV->isConstant() && !GV->isExternal())
8069             if (Constant *V = 
8070                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8071               return ReplaceInstUsesWith(LI, V);
8072         if (CE->getOperand(0)->isNullValue()) {
8073           // Insert a new store to null instruction before the load to indicate
8074           // that this code is not reachable.  We do this instead of inserting
8075           // an unreachable instruction directly because we cannot modify the
8076           // CFG.
8077           new StoreInst(UndefValue::get(LI.getType()),
8078                         Constant::getNullValue(Op->getType()), &LI);
8079           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8080         }
8081
8082       } else if (CE->isCast()) {
8083         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8084           return Res;
8085       }
8086   }
8087
8088   if (Op->hasOneUse()) {
8089     // Change select and PHI nodes to select values instead of addresses: this
8090     // helps alias analysis out a lot, allows many others simplifications, and
8091     // exposes redundancy in the code.
8092     //
8093     // Note that we cannot do the transformation unless we know that the
8094     // introduced loads cannot trap!  Something like this is valid as long as
8095     // the condition is always false: load (select bool %C, int* null, int* %G),
8096     // but it would not be valid if we transformed it to load from null
8097     // unconditionally.
8098     //
8099     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8100       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8101       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8102           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8103         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8104                                      SI->getOperand(1)->getName()+".val"), LI);
8105         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8106                                      SI->getOperand(2)->getName()+".val"), LI);
8107         return new SelectInst(SI->getCondition(), V1, V2);
8108       }
8109
8110       // load (select (cond, null, P)) -> load P
8111       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8112         if (C->isNullValue()) {
8113           LI.setOperand(0, SI->getOperand(2));
8114           return &LI;
8115         }
8116
8117       // load (select (cond, P, null)) -> load P
8118       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8119         if (C->isNullValue()) {
8120           LI.setOperand(0, SI->getOperand(1));
8121           return &LI;
8122         }
8123     }
8124   }
8125   return 0;
8126 }
8127
8128 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8129 /// when possible.
8130 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8131   User *CI = cast<User>(SI.getOperand(1));
8132   Value *CastOp = CI->getOperand(0);
8133
8134   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8135   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8136     const Type *SrcPTy = SrcTy->getElementType();
8137
8138     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8139       // If the source is an array, the code below will not succeed.  Check to
8140       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8141       // constants.
8142       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8143         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8144           if (ASrcTy->getNumElements() != 0) {
8145             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8146             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8147             SrcTy = cast<PointerType>(CastOp->getType());
8148             SrcPTy = SrcTy->getElementType();
8149           }
8150
8151       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8152           IC.getTargetData().getTypeSize(SrcPTy) ==
8153                IC.getTargetData().getTypeSize(DestPTy)) {
8154
8155         // Okay, we are casting from one integer or pointer type to another of
8156         // the same size.  Instead of casting the pointer before the store, cast
8157         // the value to be stored.
8158         Value *NewCast;
8159         Instruction::CastOps opcode = Instruction::BitCast;
8160         Value *SIOp0 = SI.getOperand(0);
8161         if (isa<PointerType>(SrcPTy)) {
8162           if (SIOp0->getType()->isIntegral())
8163             opcode = Instruction::IntToPtr;
8164         } else if (SrcPTy->isIntegral()) {
8165           if (isa<PointerType>(SIOp0->getType()))
8166             opcode = Instruction::PtrToInt;
8167         }
8168         if (Constant *C = dyn_cast<Constant>(SIOp0))
8169           NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
8170         else
8171           NewCast = IC.InsertNewInstBefore(
8172             CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
8173         return new StoreInst(NewCast, CastOp);
8174       }
8175     }
8176   }
8177   return 0;
8178 }
8179
8180 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8181   Value *Val = SI.getOperand(0);
8182   Value *Ptr = SI.getOperand(1);
8183
8184   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8185     EraseInstFromFunction(SI);
8186     ++NumCombined;
8187     return 0;
8188   }
8189
8190   // Do really simple DSE, to catch cases where there are several consequtive
8191   // stores to the same location, separated by a few arithmetic operations. This
8192   // situation often occurs with bitfield accesses.
8193   BasicBlock::iterator BBI = &SI;
8194   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8195        --ScanInsts) {
8196     --BBI;
8197     
8198     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8199       // Prev store isn't volatile, and stores to the same location?
8200       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8201         ++NumDeadStore;
8202         ++BBI;
8203         EraseInstFromFunction(*PrevSI);
8204         continue;
8205       }
8206       break;
8207     }
8208     
8209     // If this is a load, we have to stop.  However, if the loaded value is from
8210     // the pointer we're loading and is producing the pointer we're storing,
8211     // then *this* store is dead (X = load P; store X -> P).
8212     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8213       if (LI == Val && LI->getOperand(0) == Ptr) {
8214         EraseInstFromFunction(SI);
8215         ++NumCombined;
8216         return 0;
8217       }
8218       // Otherwise, this is a load from some other location.  Stores before it
8219       // may not be dead.
8220       break;
8221     }
8222     
8223     // Don't skip over loads or things that can modify memory.
8224     if (BBI->mayWriteToMemory())
8225       break;
8226   }
8227   
8228   
8229   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8230
8231   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8232   if (isa<ConstantPointerNull>(Ptr)) {
8233     if (!isa<UndefValue>(Val)) {
8234       SI.setOperand(0, UndefValue::get(Val->getType()));
8235       if (Instruction *U = dyn_cast<Instruction>(Val))
8236         WorkList.push_back(U);  // Dropped a use.
8237       ++NumCombined;
8238     }
8239     return 0;  // Do not modify these!
8240   }
8241
8242   // store undef, Ptr -> noop
8243   if (isa<UndefValue>(Val)) {
8244     EraseInstFromFunction(SI);
8245     ++NumCombined;
8246     return 0;
8247   }
8248
8249   // If the pointer destination is a cast, see if we can fold the cast into the
8250   // source instead.
8251   if (isa<CastInst>(Ptr))
8252     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8253       return Res;
8254   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8255     if (CE->isCast())
8256       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8257         return Res;
8258
8259   
8260   // If this store is the last instruction in the basic block, and if the block
8261   // ends with an unconditional branch, try to move it to the successor block.
8262   BBI = &SI; ++BBI;
8263   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8264     if (BI->isUnconditional()) {
8265       // Check to see if the successor block has exactly two incoming edges.  If
8266       // so, see if the other predecessor contains a store to the same location.
8267       // if so, insert a PHI node (if needed) and move the stores down.
8268       BasicBlock *Dest = BI->getSuccessor(0);
8269
8270       pred_iterator PI = pred_begin(Dest);
8271       BasicBlock *Other = 0;
8272       if (*PI != BI->getParent())
8273         Other = *PI;
8274       ++PI;
8275       if (PI != pred_end(Dest)) {
8276         if (*PI != BI->getParent())
8277           if (Other)
8278             Other = 0;
8279           else
8280             Other = *PI;
8281         if (++PI != pred_end(Dest))
8282           Other = 0;
8283       }
8284       if (Other) {  // If only one other pred...
8285         BBI = Other->getTerminator();
8286         // Make sure this other block ends in an unconditional branch and that
8287         // there is an instruction before the branch.
8288         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8289             BBI != Other->begin()) {
8290           --BBI;
8291           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8292           
8293           // If this instruction is a store to the same location.
8294           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8295             // Okay, we know we can perform this transformation.  Insert a PHI
8296             // node now if we need it.
8297             Value *MergedVal = OtherStore->getOperand(0);
8298             if (MergedVal != SI.getOperand(0)) {
8299               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8300               PN->reserveOperandSpace(2);
8301               PN->addIncoming(SI.getOperand(0), SI.getParent());
8302               PN->addIncoming(OtherStore->getOperand(0), Other);
8303               MergedVal = InsertNewInstBefore(PN, Dest->front());
8304             }
8305             
8306             // Advance to a place where it is safe to insert the new store and
8307             // insert it.
8308             BBI = Dest->begin();
8309             while (isa<PHINode>(BBI)) ++BBI;
8310             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8311                                               OtherStore->isVolatile()), *BBI);
8312
8313             // Nuke the old stores.
8314             EraseInstFromFunction(SI);
8315             EraseInstFromFunction(*OtherStore);
8316             ++NumCombined;
8317             return 0;
8318           }
8319         }
8320       }
8321     }
8322   
8323   return 0;
8324 }
8325
8326
8327 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8328   // Change br (not X), label True, label False to: br X, label False, True
8329   Value *X = 0;
8330   BasicBlock *TrueDest;
8331   BasicBlock *FalseDest;
8332   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8333       !isa<Constant>(X)) {
8334     // Swap Destinations and condition...
8335     BI.setCondition(X);
8336     BI.setSuccessor(0, FalseDest);
8337     BI.setSuccessor(1, TrueDest);
8338     return &BI;
8339   }
8340
8341   // Cannonicalize fcmp_one -> fcmp_oeq
8342   FCmpInst::Predicate FPred; Value *Y;
8343   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8344                              TrueDest, FalseDest)))
8345     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8346          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8347       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8348       std::string Name = I->getName(); I->setName("");
8349       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8350       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8351       // Swap Destinations and condition...
8352       BI.setCondition(NewSCC);
8353       BI.setSuccessor(0, FalseDest);
8354       BI.setSuccessor(1, TrueDest);
8355       removeFromWorkList(I);
8356       I->getParent()->getInstList().erase(I);
8357       WorkList.push_back(cast<Instruction>(NewSCC));
8358       return &BI;
8359     }
8360
8361   // Cannonicalize icmp_ne -> icmp_eq
8362   ICmpInst::Predicate IPred;
8363   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8364                       TrueDest, FalseDest)))
8365     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8366          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8367          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8368       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8369       std::string Name = I->getName(); I->setName("");
8370       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8371       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8372       // Swap Destinations and condition...
8373       BI.setCondition(NewSCC);
8374       BI.setSuccessor(0, FalseDest);
8375       BI.setSuccessor(1, TrueDest);
8376       removeFromWorkList(I);
8377       I->getParent()->getInstList().erase(I);
8378       WorkList.push_back(cast<Instruction>(NewSCC));
8379       return &BI;
8380     }
8381
8382   return 0;
8383 }
8384
8385 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8386   Value *Cond = SI.getCondition();
8387   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8388     if (I->getOpcode() == Instruction::Add)
8389       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8390         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8391         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8392           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8393                                                 AddRHS));
8394         SI.setOperand(0, I->getOperand(0));
8395         WorkList.push_back(I);
8396         return &SI;
8397       }
8398   }
8399   return 0;
8400 }
8401
8402 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8403 /// is to leave as a vector operation.
8404 static bool CheapToScalarize(Value *V, bool isConstant) {
8405   if (isa<ConstantAggregateZero>(V)) 
8406     return true;
8407   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8408     if (isConstant) return true;
8409     // If all elts are the same, we can extract.
8410     Constant *Op0 = C->getOperand(0);
8411     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8412       if (C->getOperand(i) != Op0)
8413         return false;
8414     return true;
8415   }
8416   Instruction *I = dyn_cast<Instruction>(V);
8417   if (!I) return false;
8418   
8419   // Insert element gets simplified to the inserted element or is deleted if
8420   // this is constant idx extract element and its a constant idx insertelt.
8421   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8422       isa<ConstantInt>(I->getOperand(2)))
8423     return true;
8424   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8425     return true;
8426   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8427     if (BO->hasOneUse() &&
8428         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8429          CheapToScalarize(BO->getOperand(1), isConstant)))
8430       return true;
8431   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8432     if (CI->hasOneUse() &&
8433         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8434          CheapToScalarize(CI->getOperand(1), isConstant)))
8435       return true;
8436   
8437   return false;
8438 }
8439
8440 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8441 /// elements into values that are larger than the #elts in the input.
8442 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8443   unsigned NElts = SVI->getType()->getNumElements();
8444   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8445     return std::vector<unsigned>(NElts, 0);
8446   if (isa<UndefValue>(SVI->getOperand(2)))
8447     return std::vector<unsigned>(NElts, 2*NElts);
8448
8449   std::vector<unsigned> Result;
8450   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8451   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8452     if (isa<UndefValue>(CP->getOperand(i)))
8453       Result.push_back(NElts*2);  // undef -> 8
8454     else
8455       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8456   return Result;
8457 }
8458
8459 /// FindScalarElement - Given a vector and an element number, see if the scalar
8460 /// value is already around as a register, for example if it were inserted then
8461 /// extracted from the vector.
8462 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8463   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8464   const PackedType *PTy = cast<PackedType>(V->getType());
8465   unsigned Width = PTy->getNumElements();
8466   if (EltNo >= Width)  // Out of range access.
8467     return UndefValue::get(PTy->getElementType());
8468   
8469   if (isa<UndefValue>(V))
8470     return UndefValue::get(PTy->getElementType());
8471   else if (isa<ConstantAggregateZero>(V))
8472     return Constant::getNullValue(PTy->getElementType());
8473   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8474     return CP->getOperand(EltNo);
8475   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8476     // If this is an insert to a variable element, we don't know what it is.
8477     if (!isa<ConstantInt>(III->getOperand(2))) 
8478       return 0;
8479     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8480     
8481     // If this is an insert to the element we are looking for, return the
8482     // inserted value.
8483     if (EltNo == IIElt) 
8484       return III->getOperand(1);
8485     
8486     // Otherwise, the insertelement doesn't modify the value, recurse on its
8487     // vector input.
8488     return FindScalarElement(III->getOperand(0), EltNo);
8489   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8490     unsigned InEl = getShuffleMask(SVI)[EltNo];
8491     if (InEl < Width)
8492       return FindScalarElement(SVI->getOperand(0), InEl);
8493     else if (InEl < Width*2)
8494       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8495     else
8496       return UndefValue::get(PTy->getElementType());
8497   }
8498   
8499   // Otherwise, we don't know.
8500   return 0;
8501 }
8502
8503 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8504
8505   // If packed val is undef, replace extract with scalar undef.
8506   if (isa<UndefValue>(EI.getOperand(0)))
8507     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8508
8509   // If packed val is constant 0, replace extract with scalar 0.
8510   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8511     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8512   
8513   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8514     // If packed val is constant with uniform operands, replace EI
8515     // with that operand
8516     Constant *op0 = C->getOperand(0);
8517     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8518       if (C->getOperand(i) != op0) {
8519         op0 = 0; 
8520         break;
8521       }
8522     if (op0)
8523       return ReplaceInstUsesWith(EI, op0);
8524   }
8525   
8526   // If extracting a specified index from the vector, see if we can recursively
8527   // find a previously computed scalar that was inserted into the vector.
8528   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8529     // This instruction only demands the single element from the input vector.
8530     // If the input vector has a single use, simplify it based on this use
8531     // property.
8532     uint64_t IndexVal = IdxC->getZExtValue();
8533     if (EI.getOperand(0)->hasOneUse()) {
8534       uint64_t UndefElts;
8535       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8536                                                 1 << IndexVal,
8537                                                 UndefElts)) {
8538         EI.setOperand(0, V);
8539         return &EI;
8540       }
8541     }
8542     
8543     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8544       return ReplaceInstUsesWith(EI, Elt);
8545   }
8546   
8547   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8548     if (I->hasOneUse()) {
8549       // Push extractelement into predecessor operation if legal and
8550       // profitable to do so
8551       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8552         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8553         if (CheapToScalarize(BO, isConstantElt)) {
8554           ExtractElementInst *newEI0 = 
8555             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8556                                    EI.getName()+".lhs");
8557           ExtractElementInst *newEI1 =
8558             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8559                                    EI.getName()+".rhs");
8560           InsertNewInstBefore(newEI0, EI);
8561           InsertNewInstBefore(newEI1, EI);
8562           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8563         }
8564       } else if (isa<LoadInst>(I)) {
8565         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8566                                       PointerType::get(EI.getType()), EI);
8567         GetElementPtrInst *GEP = 
8568           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8569         InsertNewInstBefore(GEP, EI);
8570         return new LoadInst(GEP);
8571       }
8572     }
8573     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8574       // Extracting the inserted element?
8575       if (IE->getOperand(2) == EI.getOperand(1))
8576         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8577       // If the inserted and extracted elements are constants, they must not
8578       // be the same value, extract from the pre-inserted value instead.
8579       if (isa<Constant>(IE->getOperand(2)) &&
8580           isa<Constant>(EI.getOperand(1))) {
8581         AddUsesToWorkList(EI);
8582         EI.setOperand(0, IE->getOperand(0));
8583         return &EI;
8584       }
8585     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8586       // If this is extracting an element from a shufflevector, figure out where
8587       // it came from and extract from the appropriate input element instead.
8588       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8589         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8590         Value *Src;
8591         if (SrcIdx < SVI->getType()->getNumElements())
8592           Src = SVI->getOperand(0);
8593         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8594           SrcIdx -= SVI->getType()->getNumElements();
8595           Src = SVI->getOperand(1);
8596         } else {
8597           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8598         }
8599         return new ExtractElementInst(Src, SrcIdx);
8600       }
8601     }
8602   }
8603   return 0;
8604 }
8605
8606 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8607 /// elements from either LHS or RHS, return the shuffle mask and true. 
8608 /// Otherwise, return false.
8609 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8610                                          std::vector<Constant*> &Mask) {
8611   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8612          "Invalid CollectSingleShuffleElements");
8613   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8614
8615   if (isa<UndefValue>(V)) {
8616     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8617     return true;
8618   } else if (V == LHS) {
8619     for (unsigned i = 0; i != NumElts; ++i)
8620       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8621     return true;
8622   } else if (V == RHS) {
8623     for (unsigned i = 0; i != NumElts; ++i)
8624       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8625     return true;
8626   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8627     // If this is an insert of an extract from some other vector, include it.
8628     Value *VecOp    = IEI->getOperand(0);
8629     Value *ScalarOp = IEI->getOperand(1);
8630     Value *IdxOp    = IEI->getOperand(2);
8631     
8632     if (!isa<ConstantInt>(IdxOp))
8633       return false;
8634     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8635     
8636     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8637       // Okay, we can handle this if the vector we are insertinting into is
8638       // transitively ok.
8639       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8640         // If so, update the mask to reflect the inserted undef.
8641         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8642         return true;
8643       }      
8644     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8645       if (isa<ConstantInt>(EI->getOperand(1)) &&
8646           EI->getOperand(0)->getType() == V->getType()) {
8647         unsigned ExtractedIdx =
8648           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8649         
8650         // This must be extracting from either LHS or RHS.
8651         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8652           // Okay, we can handle this if the vector we are insertinting into is
8653           // transitively ok.
8654           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8655             // If so, update the mask to reflect the inserted value.
8656             if (EI->getOperand(0) == LHS) {
8657               Mask[InsertedIdx & (NumElts-1)] = 
8658                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8659             } else {
8660               assert(EI->getOperand(0) == RHS);
8661               Mask[InsertedIdx & (NumElts-1)] = 
8662                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8663               
8664             }
8665             return true;
8666           }
8667         }
8668       }
8669     }
8670   }
8671   // TODO: Handle shufflevector here!
8672   
8673   return false;
8674 }
8675
8676 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8677 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8678 /// that computes V and the LHS value of the shuffle.
8679 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8680                                      Value *&RHS) {
8681   assert(isa<PackedType>(V->getType()) && 
8682          (RHS == 0 || V->getType() == RHS->getType()) &&
8683          "Invalid shuffle!");
8684   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8685
8686   if (isa<UndefValue>(V)) {
8687     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8688     return V;
8689   } else if (isa<ConstantAggregateZero>(V)) {
8690     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8691     return V;
8692   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8693     // If this is an insert of an extract from some other vector, include it.
8694     Value *VecOp    = IEI->getOperand(0);
8695     Value *ScalarOp = IEI->getOperand(1);
8696     Value *IdxOp    = IEI->getOperand(2);
8697     
8698     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8699       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8700           EI->getOperand(0)->getType() == V->getType()) {
8701         unsigned ExtractedIdx =
8702           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8703         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8704         
8705         // Either the extracted from or inserted into vector must be RHSVec,
8706         // otherwise we'd end up with a shuffle of three inputs.
8707         if (EI->getOperand(0) == RHS || RHS == 0) {
8708           RHS = EI->getOperand(0);
8709           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8710           Mask[InsertedIdx & (NumElts-1)] = 
8711             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8712           return V;
8713         }
8714         
8715         if (VecOp == RHS) {
8716           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8717           // Everything but the extracted element is replaced with the RHS.
8718           for (unsigned i = 0; i != NumElts; ++i) {
8719             if (i != InsertedIdx)
8720               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8721           }
8722           return V;
8723         }
8724         
8725         // If this insertelement is a chain that comes from exactly these two
8726         // vectors, return the vector and the effective shuffle.
8727         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8728           return EI->getOperand(0);
8729         
8730       }
8731     }
8732   }
8733   // TODO: Handle shufflevector here!
8734   
8735   // Otherwise, can't do anything fancy.  Return an identity vector.
8736   for (unsigned i = 0; i != NumElts; ++i)
8737     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8738   return V;
8739 }
8740
8741 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8742   Value *VecOp    = IE.getOperand(0);
8743   Value *ScalarOp = IE.getOperand(1);
8744   Value *IdxOp    = IE.getOperand(2);
8745   
8746   // If the inserted element was extracted from some other vector, and if the 
8747   // indexes are constant, try to turn this into a shufflevector operation.
8748   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8749     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8750         EI->getOperand(0)->getType() == IE.getType()) {
8751       unsigned NumVectorElts = IE.getType()->getNumElements();
8752       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8753       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8754       
8755       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8756         return ReplaceInstUsesWith(IE, VecOp);
8757       
8758       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8759         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8760       
8761       // If we are extracting a value from a vector, then inserting it right
8762       // back into the same place, just use the input vector.
8763       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8764         return ReplaceInstUsesWith(IE, VecOp);      
8765       
8766       // We could theoretically do this for ANY input.  However, doing so could
8767       // turn chains of insertelement instructions into a chain of shufflevector
8768       // instructions, and right now we do not merge shufflevectors.  As such,
8769       // only do this in a situation where it is clear that there is benefit.
8770       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8771         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8772         // the values of VecOp, except then one read from EIOp0.
8773         // Build a new shuffle mask.
8774         std::vector<Constant*> Mask;
8775         if (isa<UndefValue>(VecOp))
8776           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8777         else {
8778           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8779           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8780                                                        NumVectorElts));
8781         } 
8782         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8783         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8784                                      ConstantPacked::get(Mask));
8785       }
8786       
8787       // If this insertelement isn't used by some other insertelement, turn it
8788       // (and any insertelements it points to), into one big shuffle.
8789       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8790         std::vector<Constant*> Mask;
8791         Value *RHS = 0;
8792         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8793         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8794         // We now have a shuffle of LHS, RHS, Mask.
8795         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8796       }
8797     }
8798   }
8799
8800   return 0;
8801 }
8802
8803
8804 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8805   Value *LHS = SVI.getOperand(0);
8806   Value *RHS = SVI.getOperand(1);
8807   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8808
8809   bool MadeChange = false;
8810   
8811   // Undefined shuffle mask -> undefined value.
8812   if (isa<UndefValue>(SVI.getOperand(2)))
8813     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8814   
8815   // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8816   // the undef, change them to undefs.
8817   
8818   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8819   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8820   if (LHS == RHS || isa<UndefValue>(LHS)) {
8821     if (isa<UndefValue>(LHS) && LHS == RHS) {
8822       // shuffle(undef,undef,mask) -> undef.
8823       return ReplaceInstUsesWith(SVI, LHS);
8824     }
8825     
8826     // Remap any references to RHS to use LHS.
8827     std::vector<Constant*> Elts;
8828     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8829       if (Mask[i] >= 2*e)
8830         Elts.push_back(UndefValue::get(Type::Int32Ty));
8831       else {
8832         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8833             (Mask[i] <  e && isa<UndefValue>(LHS)))
8834           Mask[i] = 2*e;     // Turn into undef.
8835         else
8836           Mask[i] &= (e-1);  // Force to LHS.
8837         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8838       }
8839     }
8840     SVI.setOperand(0, SVI.getOperand(1));
8841     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8842     SVI.setOperand(2, ConstantPacked::get(Elts));
8843     LHS = SVI.getOperand(0);
8844     RHS = SVI.getOperand(1);
8845     MadeChange = true;
8846   }
8847   
8848   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8849   bool isLHSID = true, isRHSID = true;
8850     
8851   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8852     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8853     // Is this an identity shuffle of the LHS value?
8854     isLHSID &= (Mask[i] == i);
8855       
8856     // Is this an identity shuffle of the RHS value?
8857     isRHSID &= (Mask[i]-e == i);
8858   }
8859
8860   // Eliminate identity shuffles.
8861   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8862   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8863   
8864   // If the LHS is a shufflevector itself, see if we can combine it with this
8865   // one without producing an unusual shuffle.  Here we are really conservative:
8866   // we are absolutely afraid of producing a shuffle mask not in the input
8867   // program, because the code gen may not be smart enough to turn a merged
8868   // shuffle into two specific shuffles: it may produce worse code.  As such,
8869   // we only merge two shuffles if the result is one of the two input shuffle
8870   // masks.  In this case, merging the shuffles just removes one instruction,
8871   // which we know is safe.  This is good for things like turning:
8872   // (splat(splat)) -> splat.
8873   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8874     if (isa<UndefValue>(RHS)) {
8875       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8876
8877       std::vector<unsigned> NewMask;
8878       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8879         if (Mask[i] >= 2*e)
8880           NewMask.push_back(2*e);
8881         else
8882           NewMask.push_back(LHSMask[Mask[i]]);
8883       
8884       // If the result mask is equal to the src shuffle or this shuffle mask, do
8885       // the replacement.
8886       if (NewMask == LHSMask || NewMask == Mask) {
8887         std::vector<Constant*> Elts;
8888         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8889           if (NewMask[i] >= e*2) {
8890             Elts.push_back(UndefValue::get(Type::Int32Ty));
8891           } else {
8892             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8893           }
8894         }
8895         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8896                                      LHSSVI->getOperand(1),
8897                                      ConstantPacked::get(Elts));
8898       }
8899     }
8900   }
8901   
8902   return MadeChange ? &SVI : 0;
8903 }
8904
8905
8906
8907 void InstCombiner::removeFromWorkList(Instruction *I) {
8908   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8909                  WorkList.end());
8910 }
8911
8912
8913 /// TryToSinkInstruction - Try to move the specified instruction from its
8914 /// current block into the beginning of DestBlock, which can only happen if it's
8915 /// safe to move the instruction past all of the instructions between it and the
8916 /// end of its block.
8917 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8918   assert(I->hasOneUse() && "Invariants didn't hold!");
8919
8920   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8921   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8922
8923   // Do not sink alloca instructions out of the entry block.
8924   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8925     return false;
8926
8927   // We can only sink load instructions if there is nothing between the load and
8928   // the end of block that could change the value.
8929   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8930     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8931          Scan != E; ++Scan)
8932       if (Scan->mayWriteToMemory())
8933         return false;
8934   }
8935
8936   BasicBlock::iterator InsertPos = DestBlock->begin();
8937   while (isa<PHINode>(InsertPos)) ++InsertPos;
8938
8939   I->moveBefore(InsertPos);
8940   ++NumSunkInst;
8941   return true;
8942 }
8943
8944 /// OptimizeConstantExpr - Given a constant expression and target data layout
8945 /// information, symbolically evaluate the constant expr to something simpler
8946 /// if possible.
8947 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8948   if (!TD) return CE;
8949   
8950   Constant *Ptr = CE->getOperand(0);
8951   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8952       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8953     // If this is a constant expr gep that is effectively computing an
8954     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8955     bool isFoldableGEP = true;
8956     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8957       if (!isa<ConstantInt>(CE->getOperand(i)))
8958         isFoldableGEP = false;
8959     if (isFoldableGEP) {
8960       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8961       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8962       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
8963       return ConstantExpr::getIntToPtr(C, CE->getType());
8964     }
8965   }
8966   
8967   return CE;
8968 }
8969
8970
8971 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8972 /// all reachable code to the worklist.
8973 ///
8974 /// This has a couple of tricks to make the code faster and more powerful.  In
8975 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8976 /// them to the worklist (this significantly speeds up instcombine on code where
8977 /// many instructions are dead or constant).  Additionally, if we find a branch
8978 /// whose condition is a known constant, we only visit the reachable successors.
8979 ///
8980 static void AddReachableCodeToWorklist(BasicBlock *BB, 
8981                                        std::set<BasicBlock*> &Visited,
8982                                        std::vector<Instruction*> &WorkList,
8983                                        const TargetData *TD) {
8984   // We have now visited this block!  If we've already been here, bail out.
8985   if (!Visited.insert(BB).second) return;
8986     
8987   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8988     Instruction *Inst = BBI++;
8989     
8990     // DCE instruction if trivially dead.
8991     if (isInstructionTriviallyDead(Inst)) {
8992       ++NumDeadInst;
8993       DOUT << "IC: DCE: " << *Inst;
8994       Inst->eraseFromParent();
8995       continue;
8996     }
8997     
8998     // ConstantProp instruction if trivially constant.
8999     if (Constant *C = ConstantFoldInstruction(Inst)) {
9000       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9001         C = OptimizeConstantExpr(CE, TD);
9002       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9003       Inst->replaceAllUsesWith(C);
9004       ++NumConstProp;
9005       Inst->eraseFromParent();
9006       continue;
9007     }
9008     
9009     WorkList.push_back(Inst);
9010   }
9011
9012   // Recursively visit successors.  If this is a branch or switch on a constant,
9013   // only visit the reachable successor.
9014   TerminatorInst *TI = BB->getTerminator();
9015   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9016     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9017       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
9018       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9019                                  TD);
9020       return;
9021     }
9022   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9023     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9024       // See if this is an explicit destination.
9025       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9026         if (SI->getCaseValue(i) == Cond) {
9027           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9028           return;
9029         }
9030       
9031       // Otherwise it is the default destination.
9032       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9033       return;
9034     }
9035   }
9036   
9037   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9038     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9039 }
9040
9041 bool InstCombiner::runOnFunction(Function &F) {
9042   bool Changed = false;
9043   TD = &getAnalysis<TargetData>();
9044
9045   {
9046     // Do a depth-first traversal of the function, populate the worklist with
9047     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9048     // track of which blocks we visit.
9049     std::set<BasicBlock*> Visited;
9050     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9051
9052     // Do a quick scan over the function.  If we find any blocks that are
9053     // unreachable, remove any instructions inside of them.  This prevents
9054     // the instcombine code from having to deal with some bad special cases.
9055     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9056       if (!Visited.count(BB)) {
9057         Instruction *Term = BB->getTerminator();
9058         while (Term != BB->begin()) {   // Remove instrs bottom-up
9059           BasicBlock::iterator I = Term; --I;
9060
9061           DOUT << "IC: DCE: " << *I;
9062           ++NumDeadInst;
9063
9064           if (!I->use_empty())
9065             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9066           I->eraseFromParent();
9067         }
9068       }
9069   }
9070
9071   while (!WorkList.empty()) {
9072     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9073     WorkList.pop_back();
9074
9075     // Check to see if we can DCE the instruction.
9076     if (isInstructionTriviallyDead(I)) {
9077       // Add operands to the worklist.
9078       if (I->getNumOperands() < 4)
9079         AddUsesToWorkList(*I);
9080       ++NumDeadInst;
9081
9082       DOUT << "IC: DCE: " << *I;
9083
9084       I->eraseFromParent();
9085       removeFromWorkList(I);
9086       continue;
9087     }
9088
9089     // Instruction isn't dead, see if we can constant propagate it.
9090     if (Constant *C = ConstantFoldInstruction(I)) {
9091       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9092         C = OptimizeConstantExpr(CE, TD);
9093       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9094
9095       // Add operands to the worklist.
9096       AddUsesToWorkList(*I);
9097       ReplaceInstUsesWith(*I, C);
9098
9099       ++NumConstProp;
9100       I->eraseFromParent();
9101       removeFromWorkList(I);
9102       continue;
9103     }
9104
9105     // See if we can trivially sink this instruction to a successor basic block.
9106     if (I->hasOneUse()) {
9107       BasicBlock *BB = I->getParent();
9108       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9109       if (UserParent != BB) {
9110         bool UserIsSuccessor = false;
9111         // See if the user is one of our successors.
9112         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9113           if (*SI == UserParent) {
9114             UserIsSuccessor = true;
9115             break;
9116           }
9117
9118         // If the user is one of our immediate successors, and if that successor
9119         // only has us as a predecessors (we'd have to split the critical edge
9120         // otherwise), we can keep going.
9121         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9122             next(pred_begin(UserParent)) == pred_end(UserParent))
9123           // Okay, the CFG is simple enough, try to sink this instruction.
9124           Changed |= TryToSinkInstruction(I, UserParent);
9125       }
9126     }
9127
9128     // Now that we have an instruction, try combining it to simplify it...
9129     if (Instruction *Result = visit(*I)) {
9130       ++NumCombined;
9131       // Should we replace the old instruction with a new one?
9132       if (Result != I) {
9133         DOUT << "IC: Old = " << *I
9134              << "    New = " << *Result;
9135
9136         // Everything uses the new instruction now.
9137         I->replaceAllUsesWith(Result);
9138
9139         // Push the new instruction and any users onto the worklist.
9140         WorkList.push_back(Result);
9141         AddUsersToWorkList(*Result);
9142
9143         // Move the name to the new instruction first...
9144         std::string OldName = I->getName(); I->setName("");
9145         Result->setName(OldName);
9146
9147         // Insert the new instruction into the basic block...
9148         BasicBlock *InstParent = I->getParent();
9149         BasicBlock::iterator InsertPos = I;
9150
9151         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9152           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9153             ++InsertPos;
9154
9155         InstParent->getInstList().insert(InsertPos, Result);
9156
9157         // Make sure that we reprocess all operands now that we reduced their
9158         // use counts.
9159         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9160           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9161             WorkList.push_back(OpI);
9162
9163         // Instructions can end up on the worklist more than once.  Make sure
9164         // we do not process an instruction that has been deleted.
9165         removeFromWorkList(I);
9166
9167         // Erase the old instruction.
9168         InstParent->getInstList().erase(I);
9169       } else {
9170         DOUT << "IC: MOD = " << *I;
9171
9172         // If the instruction was modified, it's possible that it is now dead.
9173         // if so, remove it.
9174         if (isInstructionTriviallyDead(I)) {
9175           // Make sure we process all operands now that we are reducing their
9176           // use counts.
9177           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9178             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9179               WorkList.push_back(OpI);
9180
9181           // Instructions may end up in the worklist more than once.  Erase all
9182           // occurrences of this instruction.
9183           removeFromWorkList(I);
9184           I->eraseFromParent();
9185         } else {
9186           WorkList.push_back(Result);
9187           AddUsersToWorkList(*Result);
9188         }
9189       }
9190       Changed = true;
9191     }
9192   }
9193
9194   return Changed;
9195 }
9196
9197 FunctionPass *llvm::createInstructionCombiningPass() {
9198   return new InstCombiner();
9199 }
9200