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