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