rename Type::isIntegral to Type::isInteger, eliminating the old Type::isInteger.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add int %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62 STATISTIC(NumSunkInst , "Number of instructions sunk");
63
64 namespace {
65   class VISIBILITY_HIDDEN InstCombiner
66     : public FunctionPass,
67       public InstVisitor<InstCombiner, Instruction*> {
68     // Worklist of all of the instructions that need to be simplified.
69     std::vector<Instruction*> WorkList;
70     TargetData *TD;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(Value &I) {
77       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78            UI != UE; ++UI)
79         WorkList.push_back(cast<Instruction>(*UI));
80     }
81
82     /// AddUsesToWorkList - When an instruction is simplified, add operands to
83     /// the work lists because they might get more simplified now.
84     ///
85     void AddUsesToWorkList(Instruction &I) {
86       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88           WorkList.push_back(Op);
89     }
90     
91     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92     /// dead.  Add all of its operands to the worklist, turning them into
93     /// undef's to reduce the number of uses of those instructions.
94     ///
95     /// Return the specified operand before it is turned into an undef.
96     ///
97     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98       Value *R = I.getOperand(op);
99       
100       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102           WorkList.push_back(Op);
103           // Set the operand to undef to drop the use.
104           I.setOperand(i, UndefValue::get(Op->getType()));
105         }
106       
107       return R;
108     }
109
110     // removeFromWorkList - remove all instances of I from the worklist.
111     void removeFromWorkList(Instruction *I);
112   public:
113     virtual bool runOnFunction(Function &F);
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<TargetData>();
117       AU.addPreservedID(LCSSAID);
118       AU.setPreservesCFG();
119     }
120
121     TargetData &getTargetData() const { return *TD; }
122
123     // Visitation implementation - Implement instruction combining for different
124     // instruction types.  The semantics are as follows:
125     // Return Value:
126     //    null        - No change was made
127     //     I          - Change was made, I is still valid, I may be dead though
128     //   otherwise    - Change was made, replace I with returned instruction
129     //
130     Instruction *visitAdd(BinaryOperator &I);
131     Instruction *visitSub(BinaryOperator &I);
132     Instruction *visitMul(BinaryOperator &I);
133     Instruction *visitURem(BinaryOperator &I);
134     Instruction *visitSRem(BinaryOperator &I);
135     Instruction *visitFRem(BinaryOperator &I);
136     Instruction *commonRemTransforms(BinaryOperator &I);
137     Instruction *commonIRemTransforms(BinaryOperator &I);
138     Instruction *commonDivTransforms(BinaryOperator &I);
139     Instruction *commonIDivTransforms(BinaryOperator &I);
140     Instruction *visitUDiv(BinaryOperator &I);
141     Instruction *visitSDiv(BinaryOperator &I);
142     Instruction *visitFDiv(BinaryOperator &I);
143     Instruction *visitAnd(BinaryOperator &I);
144     Instruction *visitOr (BinaryOperator &I);
145     Instruction *visitXor(BinaryOperator &I);
146     Instruction *visitFCmpInst(FCmpInst &I);
147     Instruction *visitICmpInst(ICmpInst &I);
148     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
149
150     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151                              ICmpInst::Predicate Cond, Instruction &I);
152     Instruction *visitShiftInst(ShiftInst &I);
153     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154                                      ShiftInst &I);
155     Instruction *commonCastTransforms(CastInst &CI);
156     Instruction *commonIntCastTransforms(CastInst &CI);
157     Instruction *visitTrunc(CastInst &CI);
158     Instruction *visitZExt(CastInst &CI);
159     Instruction *visitSExt(CastInst &CI);
160     Instruction *visitFPTrunc(CastInst &CI);
161     Instruction *visitFPExt(CastInst &CI);
162     Instruction *visitFPToUI(CastInst &CI);
163     Instruction *visitFPToSI(CastInst &CI);
164     Instruction *visitUIToFP(CastInst &CI);
165     Instruction *visitSIToFP(CastInst &CI);
166     Instruction *visitPtrToInt(CastInst &CI);
167     Instruction *visitIntToPtr(CastInst &CI);
168     Instruction *visitBitCast(CastInst &CI);
169     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170                                 Instruction *FI);
171     Instruction *visitSelectInst(SelectInst &CI);
172     Instruction *visitCallInst(CallInst &CI);
173     Instruction *visitInvokeInst(InvokeInst &II);
174     Instruction *visitPHINode(PHINode &PN);
175     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
176     Instruction *visitAllocationInst(AllocationInst &AI);
177     Instruction *visitFreeInst(FreeInst &FI);
178     Instruction *visitLoadInst(LoadInst &LI);
179     Instruction *visitStoreInst(StoreInst &SI);
180     Instruction *visitBranchInst(BranchInst &BI);
181     Instruction *visitSwitchInst(SwitchInst &SI);
182     Instruction *visitInsertElementInst(InsertElementInst &IE);
183     Instruction *visitExtractElementInst(ExtractElementInst &EI);
184     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
185
186     // visitInstruction - Specify what to return for unhandled instructions...
187     Instruction *visitInstruction(Instruction &I) { return 0; }
188
189   private:
190     Instruction *visitCallSite(CallSite CS);
191     bool transformConstExprCastCall(CallSite CS);
192
193   public:
194     // InsertNewInstBefore - insert an instruction New before instruction Old
195     // in the program.  Add the new instruction to the worklist.
196     //
197     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
198       assert(New && New->getParent() == 0 &&
199              "New instruction already inserted into a basic block!");
200       BasicBlock *BB = Old.getParent();
201       BB->getInstList().insert(&Old, New);  // Insert inst
202       WorkList.push_back(New);              // Add to worklist
203       return New;
204     }
205
206     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207     /// This also adds the cast to the worklist.  Finally, this returns the
208     /// cast.
209     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210                             Instruction &Pos) {
211       if (V->getType() == Ty) return V;
212
213       if (Constant *CV = dyn_cast<Constant>(V))
214         return ConstantExpr::getCast(opc, CV, Ty);
215       
216       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
217       WorkList.push_back(C);
218       return C;
219     }
220
221     // ReplaceInstUsesWith - This method is to be used when an instruction is
222     // found to be dead, replacable with another preexisting expression.  Here
223     // we add all uses of I to the worklist, replace all uses of I with the new
224     // value, then return I, so that the inst combiner will know that I was
225     // modified.
226     //
227     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
228       AddUsersToWorkList(I);         // Add all modified instrs to worklist
229       if (&I != V) {
230         I.replaceAllUsesWith(V);
231         return &I;
232       } else {
233         // If we are replacing the instruction with itself, this must be in a
234         // segment of unreachable code, so just clobber the instruction.
235         I.replaceAllUsesWith(UndefValue::get(I.getType()));
236         return &I;
237       }
238     }
239
240     // UpdateValueUsesWith - This method is to be used when an value is
241     // found to be replacable with another preexisting expression or was
242     // updated.  Here we add all uses of I to the worklist, replace all uses of
243     // I with the new value (unless the instruction was just updated), then
244     // return true, so that the inst combiner will know that I was modified.
245     //
246     bool UpdateValueUsesWith(Value *Old, Value *New) {
247       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
248       if (Old != New)
249         Old->replaceAllUsesWith(New);
250       if (Instruction *I = dyn_cast<Instruction>(Old))
251         WorkList.push_back(I);
252       if (Instruction *I = dyn_cast<Instruction>(New))
253         WorkList.push_back(I);
254       return true;
255     }
256     
257     // EraseInstFromFunction - When dealing with an instruction that has side
258     // effects or produces a void value, we can't rely on DCE to delete the
259     // instruction.  Instead, visit methods should return the value returned by
260     // this function.
261     Instruction *EraseInstFromFunction(Instruction &I) {
262       assert(I.use_empty() && "Cannot erase instruction that is used!");
263       AddUsesToWorkList(I);
264       removeFromWorkList(&I);
265       I.eraseFromParent();
266       return 0;  // Don't do anything with FI
267     }
268
269   private:
270     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
272     /// casts that are known to not do anything...
273     ///
274     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275                                    Value *V, const Type *DestTy,
276                                    Instruction *InsertBefore);
277
278     /// SimplifyCommutative - This performs a few simplifications for 
279     /// commutative operators.
280     bool SimplifyCommutative(BinaryOperator &I);
281
282     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283     /// most-complex to least-complex order.
284     bool SimplifyCompare(CmpInst &I);
285
286     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
287                               uint64_t &KnownZero, uint64_t &KnownOne,
288                               unsigned Depth = 0);
289
290     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291                                       uint64_t &UndefElts, unsigned Depth = 0);
292       
293     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294     // PHI node as operand #0, see if we can fold the instruction into the PHI
295     // (which is only possible if all operands to the PHI are constants).
296     Instruction *FoldOpIntoPhi(Instruction &I);
297
298     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299     // operator and they all are only used by the PHI, PHI together their
300     // inputs, and do the operation once, to the result of the PHI.
301     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
302     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303     
304     
305     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
306                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
307     
308     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
309                               bool isSub, Instruction &I);
310     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
311                                  bool isSigned, bool Inside, Instruction &IB);
312     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
313     Instruction *MatchBSwap(BinaryOperator &I);
314
315     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
316   };
317
318   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
319 }
320
321 // getComplexity:  Assign a complexity or rank value to LLVM Values...
322 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
323 static unsigned getComplexity(Value *V) {
324   if (isa<Instruction>(V)) {
325     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
326       return 3;
327     return 4;
328   }
329   if (isa<Argument>(V)) return 3;
330   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
331 }
332
333 // isOnlyUse - Return true if this instruction will be deleted if we stop using
334 // it.
335 static bool isOnlyUse(Value *V) {
336   return V->hasOneUse() || isa<Constant>(V);
337 }
338
339 // getPromotedType - Return the specified type promoted as it would be to pass
340 // though a va_arg area...
341 static const Type *getPromotedType(const Type *Ty) {
342   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
343     if (ITy->getBitWidth() < 32)
344       return Type::Int32Ty;
345   } else if (Ty == Type::FloatTy)
346     return Type::DoubleTy;
347   return Ty;
348 }
349
350 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
351 /// expression bitcast,  return the operand value, otherwise return null.
352 static Value *getBitCastOperand(Value *V) {
353   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
354     return I->getOperand(0);
355   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
356     if (CE->getOpcode() == Instruction::BitCast)
357       return CE->getOperand(0);
358   return 0;
359 }
360
361 /// This function is a wrapper around CastInst::isEliminableCastPair. It
362 /// simply extracts arguments and returns what that function returns.
363 /// @Determine if it is valid to eliminate a Convert pair
364 static Instruction::CastOps 
365 isEliminableCastPair(
366   const CastInst *CI, ///< The first cast instruction
367   unsigned opcode,       ///< The opcode of the second cast instruction
368   const Type *DstTy,     ///< The target type for the second cast instruction
369   TargetData *TD         ///< The target data for pointer size
370 ) {
371   
372   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
373   const Type *MidTy = CI->getType();                  // B from above
374
375   // Get the opcodes of the two Cast instructions
376   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
378
379   return Instruction::CastOps(
380       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381                                      DstTy, TD->getIntPtrType()));
382 }
383
384 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385 /// in any code being generated.  It does not require codegen if V is simple
386 /// enough or if the cast can be folded into other casts.
387 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
388                               const Type *Ty, TargetData *TD) {
389   if (V->getType() == Ty || isa<Constant>(V)) return false;
390   
391   // If this is another cast that can be eliminated, it isn't codegen either.
392   if (const CastInst *CI = dyn_cast<CastInst>(V))
393     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
394       return false;
395   return true;
396 }
397
398 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
400 /// casts that are known to not do anything...
401 ///
402 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403                                              Value *V, const Type *DestTy,
404                                              Instruction *InsertBefore) {
405   if (V->getType() == DestTy) return V;
406   if (Constant *C = dyn_cast<Constant>(V))
407     return ConstantExpr::getCast(opcode, C, DestTy);
408   
409   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
410 }
411
412 // SimplifyCommutative - This performs a few simplifications for commutative
413 // operators:
414 //
415 //  1. Order operands such that they are listed from right (least complex) to
416 //     left (most complex).  This puts constants before unary operators before
417 //     binary operators.
418 //
419 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
421 //
422 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
423   bool Changed = false;
424   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425     Changed = !I.swapOperands();
426
427   if (!I.isAssociative()) return Changed;
428   Instruction::BinaryOps Opcode = I.getOpcode();
429   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431       if (isa<Constant>(I.getOperand(1))) {
432         Constant *Folded = ConstantExpr::get(I.getOpcode(),
433                                              cast<Constant>(I.getOperand(1)),
434                                              cast<Constant>(Op->getOperand(1)));
435         I.setOperand(0, Op->getOperand(0));
436         I.setOperand(1, Folded);
437         return true;
438       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440             isOnlyUse(Op) && isOnlyUse(Op1)) {
441           Constant *C1 = cast<Constant>(Op->getOperand(1));
442           Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
445           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
446           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447                                                     Op1->getOperand(0),
448                                                     Op1->getName(), &I);
449           WorkList.push_back(New);
450           I.setOperand(0, New);
451           I.setOperand(1, Folded);
452           return true;
453         }
454     }
455   return Changed;
456 }
457
458 /// SimplifyCompare - For a CmpInst this function just orders the operands
459 /// so that theyare listed from right (least complex) to left (most complex).
460 /// This puts constants before unary operators before binary operators.
461 bool InstCombiner::SimplifyCompare(CmpInst &I) {
462   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463     return false;
464   I.swapOperands();
465   // Compare instructions are not associative so there's nothing else we can do.
466   return true;
467 }
468
469 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470 // if the LHS is a constant zero (which is the 'negate' form).
471 //
472 static inline Value *dyn_castNegVal(Value *V) {
473   if (BinaryOperator::isNeg(V))
474     return BinaryOperator::getNegArgument(V);
475
476   // Constants can be considered to be negated values if they can be folded.
477   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478     return ConstantExpr::getNeg(C);
479   return 0;
480 }
481
482 static inline Value *dyn_castNotVal(Value *V) {
483   if (BinaryOperator::isNot(V))
484     return BinaryOperator::getNotArgument(V);
485
486   // Constants can be considered to be not'ed values...
487   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
488     return ConstantExpr::getNot(C);
489   return 0;
490 }
491
492 // dyn_castFoldableMul - If this value is a multiply that can be folded into
493 // other computations (because it has a constant operand), return the
494 // non-constant operand of the multiply, and set CST to point to the multiplier.
495 // Otherwise, return null.
496 //
497 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
498   if (V->hasOneUse() && V->getType()->isInteger())
499     if (Instruction *I = dyn_cast<Instruction>(V)) {
500       if (I->getOpcode() == Instruction::Mul)
501         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
502           return I->getOperand(0);
503       if (I->getOpcode() == Instruction::Shl)
504         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
505           // The multiplier is really 1 << CST.
506           Constant *One = ConstantInt::get(V->getType(), 1);
507           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508           return I->getOperand(0);
509         }
510     }
511   return 0;
512 }
513
514 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515 /// expression, return it.
516 static User *dyn_castGetElementPtr(Value *V) {
517   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519     if (CE->getOpcode() == Instruction::GetElementPtr)
520       return cast<User>(V);
521   return false;
522 }
523
524 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
525 static ConstantInt *AddOne(ConstantInt *C) {
526   return cast<ConstantInt>(ConstantExpr::getAdd(C,
527                                          ConstantInt::get(C->getType(), 1)));
528 }
529 static ConstantInt *SubOne(ConstantInt *C) {
530   return cast<ConstantInt>(ConstantExpr::getSub(C,
531                                          ConstantInt::get(C->getType(), 1)));
532 }
533
534 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
535 /// known to be either zero or one and return them in the KnownZero/KnownOne
536 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
537 /// processing.
538 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
539                               uint64_t &KnownOne, unsigned Depth = 0) {
540   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
541   // we cannot optimize based on the assumption that it is zero without changing
542   // it to be an explicit zero.  If we don't change it to zero, other code could
543   // optimized based on the contradictory assumption that it is non-zero.
544   // Because instcombine aggressively folds operations with undef args anyway,
545   // this won't lose us code quality.
546   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
547     // We know all of the bits for a constant!
548     KnownOne = CI->getZExtValue() & Mask;
549     KnownZero = ~KnownOne & Mask;
550     return;
551   }
552
553   KnownZero = KnownOne = 0;   // Don't know anything.
554   if (Depth == 6 || Mask == 0)
555     return;  // Limit search depth.
556
557   uint64_t KnownZero2, KnownOne2;
558   Instruction *I = dyn_cast<Instruction>(V);
559   if (!I) return;
560
561   Mask &= V->getType()->getIntegerTypeMask();
562   
563   switch (I->getOpcode()) {
564   case Instruction::And:
565     // If either the LHS or the RHS are Zero, the result is zero.
566     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
567     Mask &= ~KnownZero;
568     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
569     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
570     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
571     
572     // Output known-1 bits are only known if set in both the LHS & RHS.
573     KnownOne &= KnownOne2;
574     // Output known-0 are known to be clear if zero in either the LHS | RHS.
575     KnownZero |= KnownZero2;
576     return;
577   case Instruction::Or:
578     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
579     Mask &= ~KnownOne;
580     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
581     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
582     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
583     
584     // Output known-0 bits are only known if clear in both the LHS & RHS.
585     KnownZero &= KnownZero2;
586     // Output known-1 are known to be set if set in either the LHS | RHS.
587     KnownOne |= KnownOne2;
588     return;
589   case Instruction::Xor: {
590     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
591     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
592     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
593     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
594     
595     // Output known-0 bits are known if clear or set in both the LHS & RHS.
596     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
597     // Output known-1 are known to be set if set in only one of the LHS, RHS.
598     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
599     KnownZero = KnownZeroOut;
600     return;
601   }
602   case Instruction::Select:
603     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
604     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
605     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
606     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
607
608     // Only known if known in both the LHS and RHS.
609     KnownOne &= KnownOne2;
610     KnownZero &= KnownZero2;
611     return;
612   case Instruction::FPTrunc:
613   case Instruction::FPExt:
614   case Instruction::FPToUI:
615   case Instruction::FPToSI:
616   case Instruction::SIToFP:
617   case Instruction::PtrToInt:
618   case Instruction::UIToFP:
619   case Instruction::IntToPtr:
620     return; // Can't work with floating point or pointers
621   case Instruction::Trunc: 
622     // All these have integer operands
623     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
624     return;
625   case Instruction::BitCast: {
626     const Type *SrcTy = I->getOperand(0)->getType();
627     if (SrcTy->isInteger()) {
628       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
629       return;
630     }
631     break;
632   }
633   case Instruction::ZExt:  {
634     // Compute the bits in the result that are not present in the input.
635     const Type *SrcTy = I->getOperand(0)->getType();
636     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
637     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
638       
639     Mask &= SrcTy->getIntegerTypeMask();
640     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
641     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
642     // The top bits are known to be zero.
643     KnownZero |= NewBits;
644     return;
645   }
646   case Instruction::SExt: {
647     // Compute the bits in the result that are not present in the input.
648     const Type *SrcTy = I->getOperand(0)->getType();
649     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
650     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
651       
652     Mask &= SrcTy->getIntegerTypeMask();
653     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
655
656     // If the sign bit of the input is known set or clear, then we know the
657     // top bits of the result.
658     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
659     if (KnownZero & InSignBit) {          // Input sign bit known zero
660       KnownZero |= NewBits;
661       KnownOne &= ~NewBits;
662     } else if (KnownOne & InSignBit) {    // Input sign bit known set
663       KnownOne |= NewBits;
664       KnownZero &= ~NewBits;
665     } else {                              // Input sign bit unknown
666       KnownZero &= ~NewBits;
667       KnownOne &= ~NewBits;
668     }
669     return;
670   }
671   case Instruction::Shl:
672     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
673     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
674       uint64_t ShiftAmt = SA->getZExtValue();
675       Mask >>= ShiftAmt;
676       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
677       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
678       KnownZero <<= ShiftAmt;
679       KnownOne  <<= ShiftAmt;
680       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
681       return;
682     }
683     break;
684   case Instruction::LShr:
685     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
686     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687       // Compute the new bits that are at the top now.
688       uint64_t ShiftAmt = SA->getZExtValue();
689       uint64_t HighBits = (1ULL << ShiftAmt)-1;
690       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
691       
692       // Unsigned shift right.
693       Mask <<= ShiftAmt;
694       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
695       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
696       KnownZero >>= ShiftAmt;
697       KnownOne  >>= ShiftAmt;
698       KnownZero |= HighBits;  // high bits known zero.
699       return;
700     }
701     break;
702   case Instruction::AShr:
703     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
704     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
705       // Compute the new bits that are at the top now.
706       uint64_t ShiftAmt = SA->getZExtValue();
707       uint64_t HighBits = (1ULL << ShiftAmt)-1;
708       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
709       
710       // Signed shift right.
711       Mask <<= ShiftAmt;
712       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
714       KnownZero >>= ShiftAmt;
715       KnownOne  >>= ShiftAmt;
716         
717       // Handle the sign bits.
718       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
719       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
720         
721       if (KnownZero & SignBit) {       // New bits are known zero.
722         KnownZero |= HighBits;
723       } else if (KnownOne & SignBit) { // New bits are known one.
724         KnownOne |= HighBits;
725       }
726       return;
727     }
728     break;
729   }
730 }
731
732 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
733 /// this predicate to simplify operations downstream.  Mask is known to be zero
734 /// for bits that V cannot have.
735 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
736   uint64_t KnownZero, KnownOne;
737   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
738   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
739   return (KnownZero & Mask) == Mask;
740 }
741
742 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
743 /// specified instruction is a constant integer.  If so, check to see if there
744 /// are any bits set in the constant that are not demanded.  If so, shrink the
745 /// constant and return true.
746 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
747                                    uint64_t Demanded) {
748   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
749   if (!OpC) return false;
750
751   // If there are no bits set that aren't demanded, nothing to do.
752   if ((~Demanded & OpC->getZExtValue()) == 0)
753     return false;
754
755   // This is producing any bits that are not needed, shrink the RHS.
756   uint64_t Val = Demanded & OpC->getZExtValue();
757   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
758   return true;
759 }
760
761 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
762 // set of known zero and one bits, compute the maximum and minimum values that
763 // could have the specified known zero and known one bits, returning them in
764 // min/max.
765 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
766                                                    uint64_t KnownZero,
767                                                    uint64_t KnownOne,
768                                                    int64_t &Min, int64_t &Max) {
769   uint64_t TypeBits = Ty->getIntegerTypeMask();
770   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
771
772   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
773   
774   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
775   // bit if it is unknown.
776   Min = KnownOne;
777   Max = KnownOne|UnknownBits;
778   
779   if (SignBit & UnknownBits) { // Sign bit is unknown
780     Min |= SignBit;
781     Max &= ~SignBit;
782   }
783   
784   // Sign extend the min/max values.
785   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
786   Min = (Min << ShAmt) >> ShAmt;
787   Max = (Max << ShAmt) >> ShAmt;
788 }
789
790 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
791 // a set of known zero and one bits, compute the maximum and minimum values that
792 // could have the specified known zero and known one bits, returning them in
793 // min/max.
794 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
795                                                      uint64_t KnownZero,
796                                                      uint64_t KnownOne,
797                                                      uint64_t &Min,
798                                                      uint64_t &Max) {
799   uint64_t TypeBits = Ty->getIntegerTypeMask();
800   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
801   
802   // The minimum value is when the unknown bits are all zeros.
803   Min = KnownOne;
804   // The maximum value is when the unknown bits are all ones.
805   Max = KnownOne|UnknownBits;
806 }
807
808
809 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
810 /// DemandedMask bits of the result of V are ever used downstream.  If we can
811 /// use this information to simplify V, do so and return true.  Otherwise,
812 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
813 /// the expression (used to simplify the caller).  The KnownZero/One bits may
814 /// only be accurate for those bits in the DemandedMask.
815 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
816                                         uint64_t &KnownZero, uint64_t &KnownOne,
817                                         unsigned Depth) {
818   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
819     // We know all of the bits for a constant!
820     KnownOne = CI->getZExtValue() & DemandedMask;
821     KnownZero = ~KnownOne & DemandedMask;
822     return false;
823   }
824   
825   KnownZero = KnownOne = 0;
826   if (!V->hasOneUse()) {    // Other users may use these bits.
827     if (Depth != 0) {       // Not at the root.
828       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
829       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
830       return false;
831     }
832     // If this is the root being simplified, allow it to have multiple uses,
833     // just set the DemandedMask to all bits.
834     DemandedMask = V->getType()->getIntegerTypeMask();
835   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
836     if (V != UndefValue::get(V->getType()))
837       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
838     return false;
839   } else if (Depth == 6) {        // Limit search depth.
840     return false;
841   }
842   
843   Instruction *I = dyn_cast<Instruction>(V);
844   if (!I) return false;        // Only analyze instructions.
845
846   DemandedMask &= V->getType()->getIntegerTypeMask();
847   
848   uint64_t KnownZero2 = 0, KnownOne2 = 0;
849   switch (I->getOpcode()) {
850   default: break;
851   case Instruction::And:
852     // If either the LHS or the RHS are Zero, the result is zero.
853     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854                              KnownZero, KnownOne, Depth+1))
855       return true;
856     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
857
858     // If something is known zero on the RHS, the bits aren't demanded on the
859     // LHS.
860     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
861                              KnownZero2, KnownOne2, Depth+1))
862       return true;
863     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
864
865     // If all of the demanded bits are known 1 on one side, return the other.
866     // These bits cannot contribute to the result of the 'and'.
867     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
868       return UpdateValueUsesWith(I, I->getOperand(0));
869     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
870       return UpdateValueUsesWith(I, I->getOperand(1));
871     
872     // If all of the demanded bits in the inputs are known zeros, return zero.
873     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
874       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
875       
876     // If the RHS is a constant, see if we can simplify it.
877     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
878       return UpdateValueUsesWith(I, I);
879       
880     // Output known-1 bits are only known if set in both the LHS & RHS.
881     KnownOne &= KnownOne2;
882     // Output known-0 are known to be clear if zero in either the LHS | RHS.
883     KnownZero |= KnownZero2;
884     break;
885   case Instruction::Or:
886     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
887                              KnownZero, KnownOne, Depth+1))
888       return true;
889     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
890     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
891                              KnownZero2, KnownOne2, Depth+1))
892       return true;
893     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
894     
895     // If all of the demanded bits are known zero on one side, return the other.
896     // These bits cannot contribute to the result of the 'or'.
897     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
898       return UpdateValueUsesWith(I, I->getOperand(0));
899     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
900       return UpdateValueUsesWith(I, I->getOperand(1));
901
902     // If all of the potentially set bits on one side are known to be set on
903     // the other side, just use the 'other' side.
904     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
905         (DemandedMask & (~KnownZero)))
906       return UpdateValueUsesWith(I, I->getOperand(0));
907     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
908         (DemandedMask & (~KnownZero2)))
909       return UpdateValueUsesWith(I, I->getOperand(1));
910         
911     // If the RHS is a constant, see if we can simplify it.
912     if (ShrinkDemandedConstant(I, 1, DemandedMask))
913       return UpdateValueUsesWith(I, I);
914           
915     // Output known-0 bits are only known if clear in both the LHS & RHS.
916     KnownZero &= KnownZero2;
917     // Output known-1 are known to be set if set in either the LHS | RHS.
918     KnownOne |= KnownOne2;
919     break;
920   case Instruction::Xor: {
921     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922                              KnownZero, KnownOne, Depth+1))
923       return true;
924     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
925     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
926                              KnownZero2, KnownOne2, Depth+1))
927       return true;
928     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
929     
930     // If all of the demanded bits are known zero on one side, return the other.
931     // These bits cannot contribute to the result of the 'xor'.
932     if ((DemandedMask & KnownZero) == DemandedMask)
933       return UpdateValueUsesWith(I, I->getOperand(0));
934     if ((DemandedMask & KnownZero2) == DemandedMask)
935       return UpdateValueUsesWith(I, I->getOperand(1));
936     
937     // Output known-0 bits are known if clear or set in both the LHS & RHS.
938     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
939     // Output known-1 are known to be set if set in only one of the LHS, RHS.
940     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
941     
942     // If all of the demanded bits are known to be zero on one side or the
943     // other, turn this into an *inclusive* or.
944     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
945     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
946       Instruction *Or =
947         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
948                                  I->getName());
949       InsertNewInstBefore(Or, *I);
950       return UpdateValueUsesWith(I, Or);
951     }
952     
953     // If all of the demanded bits on one side are known, and all of the set
954     // bits on that side are also known to be set on the other side, turn this
955     // into an AND, as we know the bits will be cleared.
956     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
958       if ((KnownOne & KnownOne2) == KnownOne) {
959         Constant *AndC = ConstantInt::get(I->getType(), 
960                                           ~KnownOne & DemandedMask);
961         Instruction *And = 
962           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
963         InsertNewInstBefore(And, *I);
964         return UpdateValueUsesWith(I, And);
965       }
966     }
967     
968     // If the RHS is a constant, see if we can simplify it.
969     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
970     if (ShrinkDemandedConstant(I, 1, DemandedMask))
971       return UpdateValueUsesWith(I, I);
972     
973     KnownZero = KnownZeroOut;
974     KnownOne  = KnownOneOut;
975     break;
976   }
977   case Instruction::Select:
978     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
979                              KnownZero, KnownOne, Depth+1))
980       return true;
981     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
982                              KnownZero2, KnownOne2, Depth+1))
983       return true;
984     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
985     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
986     
987     // If the operands are constants, see if we can simplify them.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask))
989       return UpdateValueUsesWith(I, I);
990     if (ShrinkDemandedConstant(I, 2, DemandedMask))
991       return UpdateValueUsesWith(I, I);
992     
993     // Only known if known in both the LHS and RHS.
994     KnownOne &= KnownOne2;
995     KnownZero &= KnownZero2;
996     break;
997   case Instruction::Trunc:
998     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999                              KnownZero, KnownOne, Depth+1))
1000       return true;
1001     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1002     break;
1003   case Instruction::BitCast:
1004     if (!I->getOperand(0)->getType()->isInteger())
1005       return false;
1006       
1007     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008                              KnownZero, KnownOne, Depth+1))
1009       return true;
1010     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1011     break;
1012   case Instruction::ZExt: {
1013     // Compute the bits in the result that are not present in the input.
1014     const Type *SrcTy = I->getOperand(0)->getType();
1015     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1016     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
1017     
1018     DemandedMask &= SrcTy->getIntegerTypeMask();
1019     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020                              KnownZero, KnownOne, Depth+1))
1021       return true;
1022     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1023     // The top bits are known to be zero.
1024     KnownZero |= NewBits;
1025     break;
1026   }
1027   case Instruction::SExt: {
1028     // Compute the bits in the result that are not present in the input.
1029     const Type *SrcTy = I->getOperand(0)->getType();
1030     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1031     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
1032     
1033     // Get the sign bit for the source type
1034     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035     int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegerTypeMask();
1036
1037     // If any of the sign extended bits are demanded, we know that the sign
1038     // bit is demanded.
1039     if (NewBits & DemandedMask)
1040       InputDemandedBits |= InSignBit;
1041       
1042     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043                              KnownZero, KnownOne, Depth+1))
1044       return true;
1045     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1046       
1047     // If the sign bit of the input is known set or clear, then we know the
1048     // top bits of the result.
1049
1050     // If the input sign bit is known zero, or if the NewBits are not demanded
1051     // convert this into a zero extension.
1052     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1053       // Convert to ZExt cast
1054       CastInst *NewCast = CastInst::create(
1055         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1056       return UpdateValueUsesWith(I, NewCast);
1057     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1058       KnownOne |= NewBits;
1059       KnownZero &= ~NewBits;
1060     } else {                              // Input sign bit unknown
1061       KnownZero &= ~NewBits;
1062       KnownOne &= ~NewBits;
1063     }
1064     break;
1065   }
1066   case Instruction::Add:
1067     // If there is a constant on the RHS, there are a variety of xformations
1068     // we can do.
1069     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070       // If null, this should be simplified elsewhere.  Some of the xforms here
1071       // won't work if the RHS is zero.
1072       if (RHS->isNullValue())
1073         break;
1074       
1075       // Figure out what the input bits are.  If the top bits of the and result
1076       // are not demanded, then the add doesn't demand them from its input
1077       // either.
1078       
1079       // Shift the demanded mask up so that it's at the top of the uint64_t.
1080       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1081       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1082       
1083       // If the top bit of the output is demanded, demand everything from the
1084       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1085       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1086
1087       // Find information about known zero/one bits in the input.
1088       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1089                                KnownZero2, KnownOne2, Depth+1))
1090         return true;
1091
1092       // If the RHS of the add has bits set that can't affect the input, reduce
1093       // the constant.
1094       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1095         return UpdateValueUsesWith(I, I);
1096       
1097       // Avoid excess work.
1098       if (KnownZero2 == 0 && KnownOne2 == 0)
1099         break;
1100       
1101       // Turn it into OR if input bits are zero.
1102       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1103         Instruction *Or =
1104           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1105                                    I->getName());
1106         InsertNewInstBefore(Or, *I);
1107         return UpdateValueUsesWith(I, Or);
1108       }
1109       
1110       // We can say something about the output known-zero and known-one bits,
1111       // depending on potential carries from the input constant and the
1112       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1113       // bits set and the RHS constant is 0x01001, then we know we have a known
1114       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1115       
1116       // To compute this, we first compute the potential carry bits.  These are
1117       // the bits which may be modified.  I'm not aware of a better way to do
1118       // this scan.
1119       uint64_t RHSVal = RHS->getZExtValue();
1120       
1121       bool CarryIn = false;
1122       uint64_t CarryBits = 0;
1123       uint64_t CurBit = 1;
1124       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1125         // Record the current carry in.
1126         if (CarryIn) CarryBits |= CurBit;
1127         
1128         bool CarryOut;
1129         
1130         // This bit has a carry out unless it is "zero + zero" or
1131         // "zero + anything" with no carry in.
1132         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1133           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1134         } else if (!CarryIn &&
1135                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1136           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1137         } else {
1138           // Otherwise, we have to assume we have a carry out.
1139           CarryOut = true;
1140         }
1141         
1142         // This stage's carry out becomes the next stage's carry-in.
1143         CarryIn = CarryOut;
1144       }
1145       
1146       // Now that we know which bits have carries, compute the known-1/0 sets.
1147       
1148       // Bits are known one if they are known zero in one operand and one in the
1149       // other, and there is no input carry.
1150       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1151       
1152       // Bits are known zero if they are known zero in both operands and there
1153       // is no input carry.
1154       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1155     }
1156     break;
1157   case Instruction::Shl:
1158     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159       uint64_t ShiftAmt = SA->getZExtValue();
1160       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1161                                KnownZero, KnownOne, Depth+1))
1162         return true;
1163       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1164       KnownZero <<= ShiftAmt;
1165       KnownOne  <<= ShiftAmt;
1166       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1167     }
1168     break;
1169   case Instruction::LShr:
1170     // For a logical shift right
1171     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172       unsigned ShiftAmt = SA->getZExtValue();
1173       
1174       // Compute the new bits that are at the top now.
1175       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1176       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1177       uint64_t TypeMask = I->getType()->getIntegerTypeMask();
1178       // Unsigned shift right.
1179       if (SimplifyDemandedBits(I->getOperand(0),
1180                               (DemandedMask << ShiftAmt) & TypeMask,
1181                                KnownZero, KnownOne, Depth+1))
1182         return true;
1183       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1184       KnownZero &= TypeMask;
1185       KnownOne  &= TypeMask;
1186       KnownZero >>= ShiftAmt;
1187       KnownOne  >>= ShiftAmt;
1188       KnownZero |= HighBits;  // high bits known zero.
1189     }
1190     break;
1191   case Instruction::AShr:
1192     // If this is an arithmetic shift right and only the low-bit is set, we can
1193     // always convert this into a logical shr, even if the shift amount is
1194     // variable.  The low bit of the shift cannot be an input sign bit unless
1195     // the shift amount is >= the size of the datatype, which is undefined.
1196     if (DemandedMask == 1) {
1197       // Perform the logical shift right.
1198       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1199                                     I->getOperand(1), I->getName());
1200       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1201       return UpdateValueUsesWith(I, NewVal);
1202     }    
1203     
1204     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205       unsigned ShiftAmt = SA->getZExtValue();
1206       
1207       // Compute the new bits that are at the top now.
1208       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1209       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1210       uint64_t TypeMask = I->getType()->getIntegerTypeMask();
1211       // Signed shift right.
1212       if (SimplifyDemandedBits(I->getOperand(0),
1213                                (DemandedMask << ShiftAmt) & TypeMask,
1214                                KnownZero, KnownOne, Depth+1))
1215         return true;
1216       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1217       KnownZero &= TypeMask;
1218       KnownOne  &= TypeMask;
1219       KnownZero >>= ShiftAmt;
1220       KnownOne  >>= ShiftAmt;
1221         
1222       // Handle the sign bits.
1223       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1224       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1225         
1226       // If the input sign bit is known to be zero, or if none of the top bits
1227       // are demanded, turn this into an unsigned shift right.
1228       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1229         // Perform the logical shift right.
1230         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1231                                       SA, I->getName());
1232         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1233         return UpdateValueUsesWith(I, NewVal);
1234       } else if (KnownOne & SignBit) { // New bits are known one.
1235         KnownOne |= HighBits;
1236       }
1237     }
1238     break;
1239   }
1240   
1241   // If the client is only demanding bits that we know, return the known
1242   // constant.
1243   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1244     return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
1245   return false;
1246 }  
1247
1248
1249 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1250 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1251 /// actually used by the caller.  This method analyzes which elements of the
1252 /// operand are undef and returns that information in UndefElts.
1253 ///
1254 /// If the information about demanded elements can be used to simplify the
1255 /// operation, the operation is simplified, then the resultant value is
1256 /// returned.  This returns null if no change was made.
1257 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1258                                                 uint64_t &UndefElts,
1259                                                 unsigned Depth) {
1260   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1261   assert(VWidth <= 64 && "Vector too wide to analyze!");
1262   uint64_t EltMask = ~0ULL >> (64-VWidth);
1263   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1264          "Invalid DemandedElts!");
1265
1266   if (isa<UndefValue>(V)) {
1267     // If the entire vector is undefined, just return this info.
1268     UndefElts = EltMask;
1269     return 0;
1270   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1271     UndefElts = EltMask;
1272     return UndefValue::get(V->getType());
1273   }
1274   
1275   UndefElts = 0;
1276   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1277     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1278     Constant *Undef = UndefValue::get(EltTy);
1279
1280     std::vector<Constant*> Elts;
1281     for (unsigned i = 0; i != VWidth; ++i)
1282       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1283         Elts.push_back(Undef);
1284         UndefElts |= (1ULL << i);
1285       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1286         Elts.push_back(Undef);
1287         UndefElts |= (1ULL << i);
1288       } else {                               // Otherwise, defined.
1289         Elts.push_back(CP->getOperand(i));
1290       }
1291         
1292     // If we changed the constant, return it.
1293     Constant *NewCP = ConstantPacked::get(Elts);
1294     return NewCP != CP ? NewCP : 0;
1295   } else if (isa<ConstantAggregateZero>(V)) {
1296     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1297     // set to undef.
1298     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1299     Constant *Zero = Constant::getNullValue(EltTy);
1300     Constant *Undef = UndefValue::get(EltTy);
1301     std::vector<Constant*> Elts;
1302     for (unsigned i = 0; i != VWidth; ++i)
1303       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1304     UndefElts = DemandedElts ^ EltMask;
1305     return ConstantPacked::get(Elts);
1306   }
1307   
1308   if (!V->hasOneUse()) {    // Other users may use these bits.
1309     if (Depth != 0) {       // Not at the root.
1310       // TODO: Just compute the UndefElts information recursively.
1311       return false;
1312     }
1313     return false;
1314   } else if (Depth == 10) {        // Limit search depth.
1315     return false;
1316   }
1317   
1318   Instruction *I = dyn_cast<Instruction>(V);
1319   if (!I) return false;        // Only analyze instructions.
1320   
1321   bool MadeChange = false;
1322   uint64_t UndefElts2;
1323   Value *TmpV;
1324   switch (I->getOpcode()) {
1325   default: break;
1326     
1327   case Instruction::InsertElement: {
1328     // If this is a variable index, we don't know which element it overwrites.
1329     // demand exactly the same input as we produce.
1330     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1331     if (Idx == 0) {
1332       // Note that we can't propagate undef elt info, because we don't know
1333       // which elt is getting updated.
1334       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1335                                         UndefElts2, Depth+1);
1336       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1337       break;
1338     }
1339     
1340     // If this is inserting an element that isn't demanded, remove this
1341     // insertelement.
1342     unsigned IdxNo = Idx->getZExtValue();
1343     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1344       return AddSoonDeadInstToWorklist(*I, 0);
1345     
1346     // Otherwise, the element inserted overwrites whatever was there, so the
1347     // input demanded set is simpler than the output set.
1348     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1349                                       DemandedElts & ~(1ULL << IdxNo),
1350                                       UndefElts, Depth+1);
1351     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1352
1353     // The inserted element is defined.
1354     UndefElts |= 1ULL << IdxNo;
1355     break;
1356   }
1357     
1358   case Instruction::And:
1359   case Instruction::Or:
1360   case Instruction::Xor:
1361   case Instruction::Add:
1362   case Instruction::Sub:
1363   case Instruction::Mul:
1364     // div/rem demand all inputs, because they don't want divide by zero.
1365     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1366                                       UndefElts, Depth+1);
1367     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1368     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1369                                       UndefElts2, Depth+1);
1370     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1371       
1372     // Output elements are undefined if both are undefined.  Consider things
1373     // like undef&0.  The result is known zero, not undef.
1374     UndefElts &= UndefElts2;
1375     break;
1376     
1377   case Instruction::Call: {
1378     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1379     if (!II) break;
1380     switch (II->getIntrinsicID()) {
1381     default: break;
1382       
1383     // Binary vector operations that work column-wise.  A dest element is a
1384     // function of the corresponding input elements from the two inputs.
1385     case Intrinsic::x86_sse_sub_ss:
1386     case Intrinsic::x86_sse_mul_ss:
1387     case Intrinsic::x86_sse_min_ss:
1388     case Intrinsic::x86_sse_max_ss:
1389     case Intrinsic::x86_sse2_sub_sd:
1390     case Intrinsic::x86_sse2_mul_sd:
1391     case Intrinsic::x86_sse2_min_sd:
1392     case Intrinsic::x86_sse2_max_sd:
1393       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1394                                         UndefElts, Depth+1);
1395       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1396       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1397                                         UndefElts2, Depth+1);
1398       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1399
1400       // If only the low elt is demanded and this is a scalarizable intrinsic,
1401       // scalarize it now.
1402       if (DemandedElts == 1) {
1403         switch (II->getIntrinsicID()) {
1404         default: break;
1405         case Intrinsic::x86_sse_sub_ss:
1406         case Intrinsic::x86_sse_mul_ss:
1407         case Intrinsic::x86_sse2_sub_sd:
1408         case Intrinsic::x86_sse2_mul_sd:
1409           // TODO: Lower MIN/MAX/ABS/etc
1410           Value *LHS = II->getOperand(1);
1411           Value *RHS = II->getOperand(2);
1412           // Extract the element as scalars.
1413           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1414           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1415           
1416           switch (II->getIntrinsicID()) {
1417           default: assert(0 && "Case stmts out of sync!");
1418           case Intrinsic::x86_sse_sub_ss:
1419           case Intrinsic::x86_sse2_sub_sd:
1420             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1421                                                         II->getName()), *II);
1422             break;
1423           case Intrinsic::x86_sse_mul_ss:
1424           case Intrinsic::x86_sse2_mul_sd:
1425             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1426                                                          II->getName()), *II);
1427             break;
1428           }
1429           
1430           Instruction *New =
1431             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1432                                   II->getName());
1433           InsertNewInstBefore(New, *II);
1434           AddSoonDeadInstToWorklist(*II, 0);
1435           return New;
1436         }            
1437       }
1438         
1439       // Output elements are undefined if both are undefined.  Consider things
1440       // like undef&0.  The result is known zero, not undef.
1441       UndefElts &= UndefElts2;
1442       break;
1443     }
1444     break;
1445   }
1446   }
1447   return MadeChange ? I : 0;
1448 }
1449
1450 /// @returns true if the specified compare instruction is
1451 /// true when both operands are equal...
1452 /// @brief Determine if the ICmpInst returns true if both operands are equal
1453 static bool isTrueWhenEqual(ICmpInst &ICI) {
1454   ICmpInst::Predicate pred = ICI.getPredicate();
1455   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1456          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1457          pred == ICmpInst::ICMP_SLE;
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::Int8Ty, 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 (CmpInst *CI = dyn_cast<CmpInst>(&I))
1594     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1595                           SO->getName()+".cmp");
1596   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1598   else {
1599     assert(0 && "Unknown binary instruction type!");
1600     abort();
1601   }
1602   return IC->InsertNewInstBefore(New, I);
1603 }
1604
1605 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606 // constant as the other operand, try to fold the binary operator into the
1607 // select arguments.  This also works for Cast instructions, which obviously do
1608 // not have a second operand.
1609 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610                                      InstCombiner *IC) {
1611   // Don't modify shared select instructions
1612   if (!SI->hasOneUse()) return 0;
1613   Value *TV = SI->getOperand(1);
1614   Value *FV = SI->getOperand(2);
1615
1616   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1617     // Bool selects with constant operands can be folded to logical ops.
1618     if (SI->getType() == Type::Int1Ty) return 0;
1619
1620     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623     return new SelectInst(SI->getCondition(), SelectTrueVal,
1624                           SelectFalseVal);
1625   }
1626   return 0;
1627 }
1628
1629
1630 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631 /// node as operand #0, see if we can fold the instruction into the PHI (which
1632 /// is only possible if all operands to the PHI are constants).
1633 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634   PHINode *PN = cast<PHINode>(I.getOperand(0));
1635   unsigned NumPHIValues = PN->getNumIncomingValues();
1636   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1637
1638   // Check to see if all of the operands of the PHI are constants.  If there is
1639   // one non-constant value, remember the BB it is.  If there is more than one
1640   // bail out.
1641   BasicBlock *NonConstBB = 0;
1642   for (unsigned i = 0; i != NumPHIValues; ++i)
1643     if (!isa<Constant>(PN->getIncomingValue(i))) {
1644       if (NonConstBB) return 0;  // More than one non-const value.
1645       NonConstBB = PN->getIncomingBlock(i);
1646       
1647       // If the incoming non-constant value is in I's block, we have an infinite
1648       // loop.
1649       if (NonConstBB == I.getParent())
1650         return 0;
1651     }
1652   
1653   // If there is exactly one non-constant value, we can insert a copy of the
1654   // operation in that block.  However, if this is a critical edge, we would be
1655   // inserting the computation one some other paths (e.g. inside a loop).  Only
1656   // do this if the pred block is unconditionally branching into the phi block.
1657   if (NonConstBB) {
1658     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659     if (!BI || !BI->isUnconditional()) return 0;
1660   }
1661
1662   // Okay, we can do the transformation: create the new PHI node.
1663   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664   I.setName("");
1665   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1666   InsertNewInstBefore(NewPN, *PN);
1667
1668   // Next, add all of the operands to the PHI.
1669   if (I.getNumOperands() == 2) {
1670     Constant *C = cast<Constant>(I.getOperand(1));
1671     for (unsigned i = 0; i != NumPHIValues; ++i) {
1672       Value *InV;
1673       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1674         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1675           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1676         else
1677           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1678       } else {
1679         assert(PN->getIncomingBlock(i) == NonConstBB);
1680         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1681           InV = BinaryOperator::create(BO->getOpcode(),
1682                                        PN->getIncomingValue(i), C, "phitmp",
1683                                        NonConstBB->getTerminator());
1684         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1685           InV = CmpInst::create(CI->getOpcode(), 
1686                                 CI->getPredicate(),
1687                                 PN->getIncomingValue(i), C, "phitmp",
1688                                 NonConstBB->getTerminator());
1689         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1690           InV = new ShiftInst(SI->getOpcode(),
1691                               PN->getIncomingValue(i), C, "phitmp",
1692                               NonConstBB->getTerminator());
1693         else
1694           assert(0 && "Unknown binop!");
1695         
1696         WorkList.push_back(cast<Instruction>(InV));
1697       }
1698       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1699     }
1700   } else { 
1701     CastInst *CI = cast<CastInst>(&I);
1702     const Type *RetTy = CI->getType();
1703     for (unsigned i = 0; i != NumPHIValues; ++i) {
1704       Value *InV;
1705       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1706         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1707       } else {
1708         assert(PN->getIncomingBlock(i) == NonConstBB);
1709         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1710                                I.getType(), "phitmp", 
1711                                NonConstBB->getTerminator());
1712         WorkList.push_back(cast<Instruction>(InV));
1713       }
1714       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1715     }
1716   }
1717   return ReplaceInstUsesWith(I, NewPN);
1718 }
1719
1720 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1721   bool Changed = SimplifyCommutative(I);
1722   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1723
1724   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1725     // X + undef -> undef
1726     if (isa<UndefValue>(RHS))
1727       return ReplaceInstUsesWith(I, RHS);
1728
1729     // X + 0 --> X
1730     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1731       if (RHSC->isNullValue())
1732         return ReplaceInstUsesWith(I, LHS);
1733     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1734       if (CFP->isExactlyValue(-0.0))
1735         return ReplaceInstUsesWith(I, LHS);
1736     }
1737
1738     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1739       // X + (signbit) --> X ^ signbit
1740       uint64_t Val = CI->getZExtValue();
1741       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1742         return BinaryOperator::createXor(LHS, RHS);
1743       
1744       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1745       // (X & 254)+1 -> (X&254)|1
1746       uint64_t KnownZero, KnownOne;
1747       if (!isa<PackedType>(I.getType()) &&
1748           SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
1749                                KnownZero, KnownOne))
1750         return &I;
1751     }
1752
1753     if (isa<PHINode>(LHS))
1754       if (Instruction *NV = FoldOpIntoPhi(I))
1755         return NV;
1756     
1757     ConstantInt *XorRHS = 0;
1758     Value *XorLHS = 0;
1759     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1760       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1761       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1762       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1763       
1764       uint64_t C0080Val = 1ULL << 31;
1765       int64_t CFF80Val = -C0080Val;
1766       unsigned Size = 32;
1767       do {
1768         if (TySizeBits > Size) {
1769           bool Found = false;
1770           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1771           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1772           if (RHSSExt == CFF80Val) {
1773             if (XorRHS->getZExtValue() == C0080Val)
1774               Found = true;
1775           } else if (RHSZExt == C0080Val) {
1776             if (XorRHS->getSExtValue() == CFF80Val)
1777               Found = true;
1778           }
1779           if (Found) {
1780             // This is a sign extend if the top bits are known zero.
1781             uint64_t Mask = ~0ULL;
1782             Mask <<= 64-(TySizeBits-Size);
1783             Mask &= XorLHS->getType()->getIntegerTypeMask();
1784             if (!MaskedValueIsZero(XorLHS, Mask))
1785               Size = 0;  // Not a sign ext, but can't be any others either.
1786             goto FoundSExt;
1787           }
1788         }
1789         Size >>= 1;
1790         C0080Val >>= Size;
1791         CFF80Val >>= Size;
1792       } while (Size >= 8);
1793       
1794 FoundSExt:
1795       const Type *MiddleType = 0;
1796       switch (Size) {
1797       default: break;
1798       case 32: MiddleType = Type::Int32Ty; break;
1799       case 16: MiddleType = Type::Int16Ty; break;
1800       case 8:  MiddleType = Type::Int8Ty; break;
1801       }
1802       if (MiddleType) {
1803         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1804         InsertNewInstBefore(NewTrunc, I);
1805         return new SExtInst(NewTrunc, I.getType());
1806       }
1807     }
1808   }
1809
1810   // X + X --> X << 1
1811   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1812     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1813
1814     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1815       if (RHSI->getOpcode() == Instruction::Sub)
1816         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1817           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1818     }
1819     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1820       if (LHSI->getOpcode() == Instruction::Sub)
1821         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1822           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1823     }
1824   }
1825
1826   // -A + B  -->  B - A
1827   if (Value *V = dyn_castNegVal(LHS))
1828     return BinaryOperator::createSub(RHS, V);
1829
1830   // A + -B  -->  A - B
1831   if (!isa<Constant>(RHS))
1832     if (Value *V = dyn_castNegVal(RHS))
1833       return BinaryOperator::createSub(LHS, V);
1834
1835
1836   ConstantInt *C2;
1837   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1838     if (X == RHS)   // X*C + X --> X * (C+1)
1839       return BinaryOperator::createMul(RHS, AddOne(C2));
1840
1841     // X*C1 + X*C2 --> X * (C1+C2)
1842     ConstantInt *C1;
1843     if (X == dyn_castFoldableMul(RHS, C1))
1844       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1845   }
1846
1847   // X + X*C --> X * (C+1)
1848   if (dyn_castFoldableMul(RHS, C2) == LHS)
1849     return BinaryOperator::createMul(LHS, AddOne(C2));
1850
1851   // X + ~X --> -1   since   ~X = -X-1
1852   if (dyn_castNotVal(LHS) == RHS ||
1853       dyn_castNotVal(RHS) == LHS)
1854     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1855   
1856
1857   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1858   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1859     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1860       return R;
1861
1862   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1863     Value *X = 0;
1864     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1865       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1866       return BinaryOperator::createSub(C, X);
1867     }
1868
1869     // (X & FF00) + xx00  -> (X+xx00) & FF00
1870     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1871       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1872       if (Anded == CRHS) {
1873         // See if all bits from the first bit set in the Add RHS up are included
1874         // in the mask.  First, get the rightmost bit.
1875         uint64_t AddRHSV = CRHS->getZExtValue();
1876
1877         // Form a mask of all bits from the lowest bit added through the top.
1878         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1879         AddRHSHighBits &= C2->getType()->getIntegerTypeMask();
1880
1881         // See if the and mask includes all of these bits.
1882         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1883
1884         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1885           // Okay, the xform is safe.  Insert the new add pronto.
1886           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1887                                                             LHS->getName()), I);
1888           return BinaryOperator::createAnd(NewAdd, C2);
1889         }
1890       }
1891     }
1892
1893     // Try to fold constant add into select arguments.
1894     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1895       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1896         return R;
1897   }
1898
1899   // add (cast *A to intptrtype) B -> 
1900   //   cast (GEP (cast *A to sbyte*) B) -> 
1901   //     intptrtype
1902   {
1903     CastInst *CI = dyn_cast<CastInst>(LHS);
1904     Value *Other = RHS;
1905     if (!CI) {
1906       CI = dyn_cast<CastInst>(RHS);
1907       Other = LHS;
1908     }
1909     if (CI && CI->getType()->isSized() && 
1910         (CI->getType()->getPrimitiveSizeInBits() == 
1911          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1912         && isa<PointerType>(CI->getOperand(0)->getType())) {
1913       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1914                                    PointerType::get(Type::Int8Ty), I);
1915       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1916       return new PtrToIntInst(I2, CI->getType());
1917     }
1918   }
1919
1920   return Changed ? &I : 0;
1921 }
1922
1923 // isSignBit - Return true if the value represented by the constant only has the
1924 // highest order bit set.
1925 static bool isSignBit(ConstantInt *CI) {
1926   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1927   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1928 }
1929
1930 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1931 ///
1932 static Value *RemoveNoopCast(Value *V) {
1933   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1934     const Type *CTy = CI->getType();
1935     const Type *OpTy = CI->getOperand(0)->getType();
1936     if (CTy->isInteger() && OpTy->isInteger()) {
1937       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1938         return RemoveNoopCast(CI->getOperand(0));
1939     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1940       return RemoveNoopCast(CI->getOperand(0));
1941   }
1942   return V;
1943 }
1944
1945 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1946   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1947
1948   if (Op0 == Op1)         // sub X, X  -> 0
1949     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1950
1951   // If this is a 'B = x-(-A)', change to B = x+A...
1952   if (Value *V = dyn_castNegVal(Op1))
1953     return BinaryOperator::createAdd(Op0, V);
1954
1955   if (isa<UndefValue>(Op0))
1956     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1957   if (isa<UndefValue>(Op1))
1958     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1959
1960   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1961     // Replace (-1 - A) with (~A)...
1962     if (C->isAllOnesValue())
1963       return BinaryOperator::createNot(Op1);
1964
1965     // C - ~X == X + (1+C)
1966     Value *X = 0;
1967     if (match(Op1, m_Not(m_Value(X))))
1968       return BinaryOperator::createAdd(X,
1969                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1970     // -((uint)X >> 31) -> ((int)X >> 31)
1971     // -((int)X >> 31) -> ((uint)X >> 31)
1972     if (C->isNullValue()) {
1973       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1974       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1975         if (SI->getOpcode() == Instruction::LShr) {
1976           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1977             // Check to see if we are shifting out everything but the sign bit.
1978             if (CU->getZExtValue() == 
1979                 SI->getType()->getPrimitiveSizeInBits()-1) {
1980               // Ok, the transformation is safe.  Insert AShr.
1981               // FIXME: Once integer types are signless, this cast should be 
1982               // removed.  
1983               Value *ShiftOp = SI->getOperand(0); 
1984               return new ShiftInst(Instruction::AShr, ShiftOp, CU,
1985                                    SI->getName());
1986             }
1987           }
1988         }
1989         else if (SI->getOpcode() == Instruction::AShr) {
1990           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1991             // Check to see if we are shifting out everything but the sign bit.
1992             if (CU->getZExtValue() == 
1993                 SI->getType()->getPrimitiveSizeInBits()-1) {
1994               
1995               // Ok, the transformation is safe.  Insert LShr. 
1996               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
1997                                    SI->getName());
1998             }
1999           }
2000         } 
2001     }
2002
2003     // Try to fold constant sub into select arguments.
2004     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2005       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2006         return R;
2007
2008     if (isa<PHINode>(Op0))
2009       if (Instruction *NV = FoldOpIntoPhi(I))
2010         return NV;
2011   }
2012
2013   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2014     if (Op1I->getOpcode() == Instruction::Add &&
2015         !Op0->getType()->isFPOrFPVector()) {
2016       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2017         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2018       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2019         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2020       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2021         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2022           // C1-(X+C2) --> (C1-C2)-X
2023           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2024                                            Op1I->getOperand(0));
2025       }
2026     }
2027
2028     if (Op1I->hasOneUse()) {
2029       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2030       // is not used by anyone else...
2031       //
2032       if (Op1I->getOpcode() == Instruction::Sub &&
2033           !Op1I->getType()->isFPOrFPVector()) {
2034         // Swap the two operands of the subexpr...
2035         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2036         Op1I->setOperand(0, IIOp1);
2037         Op1I->setOperand(1, IIOp0);
2038
2039         // Create the new top level add instruction...
2040         return BinaryOperator::createAdd(Op0, Op1);
2041       }
2042
2043       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2044       //
2045       if (Op1I->getOpcode() == Instruction::And &&
2046           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2047         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2048
2049         Value *NewNot =
2050           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2051         return BinaryOperator::createAnd(Op0, NewNot);
2052       }
2053
2054       // 0 - (X sdiv C)  -> (X sdiv -C)
2055       if (Op1I->getOpcode() == Instruction::SDiv)
2056         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2057           if (CSI->isNullValue())
2058             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2059               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2060                                                ConstantExpr::getNeg(DivRHS));
2061
2062       // X - X*C --> X * (1-C)
2063       ConstantInt *C2 = 0;
2064       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2065         Constant *CP1 =
2066           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2067         return BinaryOperator::createMul(Op0, CP1);
2068       }
2069     }
2070   }
2071
2072   if (!Op0->getType()->isFPOrFPVector())
2073     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2074       if (Op0I->getOpcode() == Instruction::Add) {
2075         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2076           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2077         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2078           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2079       } else if (Op0I->getOpcode() == Instruction::Sub) {
2080         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2081           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2082       }
2083
2084   ConstantInt *C1;
2085   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2086     if (X == Op1) { // X*C - X --> X * (C-1)
2087       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2088       return BinaryOperator::createMul(Op1, CP1);
2089     }
2090
2091     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2092     if (X == dyn_castFoldableMul(Op1, C2))
2093       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2094   }
2095   return 0;
2096 }
2097
2098 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2099 /// really just returns true if the most significant (sign) bit is set.
2100 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2101   switch (pred) {
2102     case ICmpInst::ICMP_SLT: 
2103       // True if LHS s< RHS and RHS == 0
2104       return RHS->isNullValue();
2105     case ICmpInst::ICMP_SLE: 
2106       // True if LHS s<= RHS and RHS == -1
2107       return RHS->isAllOnesValue();
2108     case ICmpInst::ICMP_UGE: 
2109       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2110       return RHS->getZExtValue() == (1ULL << 
2111         (RHS->getType()->getPrimitiveSizeInBits()-1));
2112     case ICmpInst::ICMP_UGT:
2113       // True if LHS u> RHS and RHS == high-bit-mask - 1
2114       return RHS->getZExtValue() ==
2115         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2116     default:
2117       return false;
2118   }
2119 }
2120
2121 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2122   bool Changed = SimplifyCommutative(I);
2123   Value *Op0 = I.getOperand(0);
2124
2125   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2126     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2127
2128   // Simplify mul instructions with a constant RHS...
2129   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2130     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2131
2132       // ((X << C1)*C2) == (X * (C2 << C1))
2133       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2134         if (SI->getOpcode() == Instruction::Shl)
2135           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2136             return BinaryOperator::createMul(SI->getOperand(0),
2137                                              ConstantExpr::getShl(CI, ShOp));
2138
2139       if (CI->isNullValue())
2140         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2141       if (CI->equalsInt(1))                  // X * 1  == X
2142         return ReplaceInstUsesWith(I, Op0);
2143       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2144         return BinaryOperator::createNeg(Op0, I.getName());
2145
2146       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2147       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2148         uint64_t C = Log2_64(Val);
2149         return new ShiftInst(Instruction::Shl, Op0,
2150                              ConstantInt::get(Type::Int8Ty, C));
2151       }
2152     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2153       if (Op1F->isNullValue())
2154         return ReplaceInstUsesWith(I, Op1);
2155
2156       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2157       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2158       if (Op1F->getValue() == 1.0)
2159         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2160     }
2161     
2162     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2163       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2164           isa<ConstantInt>(Op0I->getOperand(1))) {
2165         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2166         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2167                                                      Op1, "tmp");
2168         InsertNewInstBefore(Add, I);
2169         Value *C1C2 = ConstantExpr::getMul(Op1, 
2170                                            cast<Constant>(Op0I->getOperand(1)));
2171         return BinaryOperator::createAdd(Add, C1C2);
2172         
2173       }
2174
2175     // Try to fold constant mul into select arguments.
2176     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2177       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2178         return R;
2179
2180     if (isa<PHINode>(Op0))
2181       if (Instruction *NV = FoldOpIntoPhi(I))
2182         return NV;
2183   }
2184
2185   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2186     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2187       return BinaryOperator::createMul(Op0v, Op1v);
2188
2189   // If one of the operands of the multiply is a cast from a boolean value, then
2190   // we know the bool is either zero or one, so this is a 'masking' multiply.
2191   // See if we can simplify things based on how the boolean was originally
2192   // formed.
2193   CastInst *BoolCast = 0;
2194   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2195     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2196       BoolCast = CI;
2197   if (!BoolCast)
2198     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2199       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2200         BoolCast = CI;
2201   if (BoolCast) {
2202     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2203       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2204       const Type *SCOpTy = SCIOp0->getType();
2205
2206       // If the icmp is true iff the sign bit of X is set, then convert this
2207       // multiply into a shift/and combination.
2208       if (isa<ConstantInt>(SCIOp1) &&
2209           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2210         // Shift the X value right to turn it into "all signbits".
2211         Constant *Amt = ConstantInt::get(Type::Int8Ty,
2212                                           SCOpTy->getPrimitiveSizeInBits()-1);
2213         Value *V =
2214           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2215                                             BoolCast->getOperand(0)->getName()+
2216                                             ".mask"), I);
2217
2218         // If the multiply type is not the same as the source type, sign extend
2219         // or truncate to the multiply type.
2220         if (I.getType() != V->getType()) {
2221           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2222           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2223           Instruction::CastOps opcode = 
2224             (SrcBits == DstBits ? Instruction::BitCast : 
2225              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2226           V = InsertCastBefore(opcode, V, I.getType(), I);
2227         }
2228
2229         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2230         return BinaryOperator::createAnd(V, OtherOp);
2231       }
2232     }
2233   }
2234
2235   return Changed ? &I : 0;
2236 }
2237
2238 /// This function implements the transforms on div instructions that work
2239 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2240 /// used by the visitors to those instructions.
2241 /// @brief Transforms common to all three div instructions
2242 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2243   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2244
2245   // undef / X -> 0
2246   if (isa<UndefValue>(Op0))
2247     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2248
2249   // X / undef -> undef
2250   if (isa<UndefValue>(Op1))
2251     return ReplaceInstUsesWith(I, Op1);
2252
2253   // Handle cases involving: div X, (select Cond, Y, Z)
2254   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2255     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2256     // same basic block, then we replace the select with Y, and the condition 
2257     // of the select with false (if the cond value is in the same BB).  If the
2258     // select has uses other than the div, this allows them to be simplified
2259     // also. Note that div X, Y is just as good as div X, 0 (undef)
2260     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2261       if (ST->isNullValue()) {
2262         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2263         if (CondI && CondI->getParent() == I.getParent())
2264           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2265         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2266           I.setOperand(1, SI->getOperand(2));
2267         else
2268           UpdateValueUsesWith(SI, SI->getOperand(2));
2269         return &I;
2270       }
2271
2272     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2273     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2274       if (ST->isNullValue()) {
2275         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2276         if (CondI && CondI->getParent() == I.getParent())
2277           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2278         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2279           I.setOperand(1, SI->getOperand(1));
2280         else
2281           UpdateValueUsesWith(SI, SI->getOperand(1));
2282         return &I;
2283       }
2284   }
2285
2286   return 0;
2287 }
2288
2289 /// This function implements the transforms common to both integer division
2290 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2291 /// division instructions.
2292 /// @brief Common integer divide transforms
2293 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2294   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2295
2296   if (Instruction *Common = commonDivTransforms(I))
2297     return Common;
2298
2299   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2300     // div X, 1 == X
2301     if (RHS->equalsInt(1))
2302       return ReplaceInstUsesWith(I, Op0);
2303
2304     // (X / C1) / C2  -> X / (C1*C2)
2305     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2306       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2307         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2308           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2309                                         ConstantExpr::getMul(RHS, LHSRHS));
2310         }
2311
2312     if (!RHS->isNullValue()) { // avoid X udiv 0
2313       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2314         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2315           return R;
2316       if (isa<PHINode>(Op0))
2317         if (Instruction *NV = FoldOpIntoPhi(I))
2318           return NV;
2319     }
2320   }
2321
2322   // 0 / X == 0, we don't need to preserve faults!
2323   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2324     if (LHS->equalsInt(0))
2325       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2326
2327   return 0;
2328 }
2329
2330 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2331   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2332
2333   // Handle the integer div common cases
2334   if (Instruction *Common = commonIDivTransforms(I))
2335     return Common;
2336
2337   // X udiv C^2 -> X >> C
2338   // Check to see if this is an unsigned division with an exact power of 2,
2339   // if so, convert to a right shift.
2340   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2341     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2342       if (isPowerOf2_64(Val)) {
2343         uint64_t ShiftAmt = Log2_64(Val);
2344         return new ShiftInst(Instruction::LShr, Op0, 
2345                               ConstantInt::get(Type::Int8Ty, ShiftAmt));
2346       }
2347   }
2348
2349   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2350   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2351     if (RHSI->getOpcode() == Instruction::Shl &&
2352         isa<ConstantInt>(RHSI->getOperand(0))) {
2353       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2354       if (isPowerOf2_64(C1)) {
2355         Value *N = RHSI->getOperand(1);
2356         const Type *NTy = N->getType();
2357         if (uint64_t C2 = Log2_64(C1)) {
2358           Constant *C2V = ConstantInt::get(NTy, C2);
2359           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2360         }
2361         return new ShiftInst(Instruction::LShr, Op0, N);
2362       }
2363     }
2364   }
2365   
2366   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2367   // where C1&C2 are powers of two.
2368   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2369     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2370       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2371         if (!STO->isNullValue() && !STO->isNullValue()) {
2372           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2373           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2374             // Compute the shift amounts
2375             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2376             // Construct the "on true" case of the select
2377             Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2378             Instruction *TSI = 
2379               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2380             TSI = InsertNewInstBefore(TSI, I);
2381     
2382             // Construct the "on false" case of the select
2383             Constant *FC = ConstantInt::get(Type::Int8Ty, FSA); 
2384             Instruction *FSI = 
2385               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2386             FSI = InsertNewInstBefore(FSI, I);
2387
2388             // construct the select instruction and return it.
2389             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2390           }
2391         }
2392   }
2393   return 0;
2394 }
2395
2396 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2397   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2398
2399   // Handle the integer div common cases
2400   if (Instruction *Common = commonIDivTransforms(I))
2401     return Common;
2402
2403   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2404     // sdiv X, -1 == -X
2405     if (RHS->isAllOnesValue())
2406       return BinaryOperator::createNeg(Op0);
2407
2408     // -X/C -> X/-C
2409     if (Value *LHSNeg = dyn_castNegVal(Op0))
2410       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2411   }
2412
2413   // If the sign bits of both operands are zero (i.e. we can prove they are
2414   // unsigned inputs), turn this into a udiv.
2415   if (I.getType()->isInteger()) {
2416     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2417     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2418       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2419     }
2420   }      
2421   
2422   return 0;
2423 }
2424
2425 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2426   return commonDivTransforms(I);
2427 }
2428
2429 /// GetFactor - If we can prove that the specified value is at least a multiple
2430 /// of some factor, return that factor.
2431 static Constant *GetFactor(Value *V) {
2432   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2433     return CI;
2434   
2435   // Unless we can be tricky, we know this is a multiple of 1.
2436   Constant *Result = ConstantInt::get(V->getType(), 1);
2437   
2438   Instruction *I = dyn_cast<Instruction>(V);
2439   if (!I) return Result;
2440   
2441   if (I->getOpcode() == Instruction::Mul) {
2442     // Handle multiplies by a constant, etc.
2443     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2444                                 GetFactor(I->getOperand(1)));
2445   } else if (I->getOpcode() == Instruction::Shl) {
2446     // (X<<C) -> X * (1 << C)
2447     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2448       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2449       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2450     }
2451   } else if (I->getOpcode() == Instruction::And) {
2452     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2453       // X & 0xFFF0 is known to be a multiple of 16.
2454       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2455       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2456         return ConstantExpr::getShl(Result, 
2457                                     ConstantInt::get(Type::Int8Ty, Zeros));
2458     }
2459   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2460     // Only handle int->int casts.
2461     if (!CI->isIntegerCast())
2462       return Result;
2463     Value *Op = CI->getOperand(0);
2464     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2465   }    
2466   return Result;
2467 }
2468
2469 /// This function implements the transforms on rem instructions that work
2470 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2471 /// is used by the visitors to those instructions.
2472 /// @brief Transforms common to all three rem instructions
2473 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2474   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2475
2476   // 0 % X == 0, we don't need to preserve faults!
2477   if (Constant *LHS = dyn_cast<Constant>(Op0))
2478     if (LHS->isNullValue())
2479       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2480
2481   if (isa<UndefValue>(Op0))              // undef % X -> 0
2482     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2483   if (isa<UndefValue>(Op1))
2484     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2485
2486   // Handle cases involving: rem X, (select Cond, Y, Z)
2487   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2488     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2489     // the same basic block, then we replace the select with Y, and the
2490     // condition of the select with false (if the cond value is in the same
2491     // BB).  If the select has uses other than the div, this allows them to be
2492     // simplified also.
2493     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2494       if (ST->isNullValue()) {
2495         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2496         if (CondI && CondI->getParent() == I.getParent())
2497           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2498         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2499           I.setOperand(1, SI->getOperand(2));
2500         else
2501           UpdateValueUsesWith(SI, SI->getOperand(2));
2502         return &I;
2503       }
2504     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2505     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2506       if (ST->isNullValue()) {
2507         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2508         if (CondI && CondI->getParent() == I.getParent())
2509           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2510         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2511           I.setOperand(1, SI->getOperand(1));
2512         else
2513           UpdateValueUsesWith(SI, SI->getOperand(1));
2514         return &I;
2515       }
2516   }
2517
2518   return 0;
2519 }
2520
2521 /// This function implements the transforms common to both integer remainder
2522 /// instructions (urem and srem). It is called by the visitors to those integer
2523 /// remainder instructions.
2524 /// @brief Common integer remainder transforms
2525 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2526   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2527
2528   if (Instruction *common = commonRemTransforms(I))
2529     return common;
2530
2531   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2532     // X % 0 == undef, we don't need to preserve faults!
2533     if (RHS->equalsInt(0))
2534       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2535     
2536     if (RHS->equalsInt(1))  // X % 1 == 0
2537       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2538
2539     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2540       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2541         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2542           return R;
2543       } else if (isa<PHINode>(Op0I)) {
2544         if (Instruction *NV = FoldOpIntoPhi(I))
2545           return NV;
2546       }
2547       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2548       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2549         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2550     }
2551   }
2552
2553   return 0;
2554 }
2555
2556 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2557   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2558
2559   if (Instruction *common = commonIRemTransforms(I))
2560     return common;
2561   
2562   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2563     // X urem C^2 -> X and C
2564     // Check to see if this is an unsigned remainder with an exact power of 2,
2565     // if so, convert to a bitwise and.
2566     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2567       if (isPowerOf2_64(C->getZExtValue()))
2568         return BinaryOperator::createAnd(Op0, SubOne(C));
2569   }
2570
2571   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2572     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2573     if (RHSI->getOpcode() == Instruction::Shl &&
2574         isa<ConstantInt>(RHSI->getOperand(0))) {
2575       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2576       if (isPowerOf2_64(C1)) {
2577         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2578         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2579                                                                    "tmp"), I);
2580         return BinaryOperator::createAnd(Op0, Add);
2581       }
2582     }
2583   }
2584
2585   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2586   // where C1&C2 are powers of two.
2587   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2588     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2589       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2590         // STO == 0 and SFO == 0 handled above.
2591         if (isPowerOf2_64(STO->getZExtValue()) && 
2592             isPowerOf2_64(SFO->getZExtValue())) {
2593           Value *TrueAnd = InsertNewInstBefore(
2594             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2595           Value *FalseAnd = InsertNewInstBefore(
2596             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2597           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2598         }
2599       }
2600   }
2601   
2602   return 0;
2603 }
2604
2605 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2606   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2607
2608   if (Instruction *common = commonIRemTransforms(I))
2609     return common;
2610   
2611   if (Value *RHSNeg = dyn_castNegVal(Op1))
2612     if (!isa<ConstantInt>(RHSNeg) || 
2613         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2614       // X % -Y -> X % Y
2615       AddUsesToWorkList(I);
2616       I.setOperand(1, RHSNeg);
2617       return &I;
2618     }
2619  
2620   // If the top bits of both operands are zero (i.e. we can prove they are
2621   // unsigned inputs), turn this into a urem.
2622   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2623   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2624     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2625     return BinaryOperator::createURem(Op0, Op1, I.getName());
2626   }
2627
2628   return 0;
2629 }
2630
2631 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2632   return commonRemTransforms(I);
2633 }
2634
2635 // isMaxValueMinusOne - return true if this is Max-1
2636 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2637   if (isSigned) {
2638     // Calculate 0111111111..11111
2639     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2640     int64_t Val = INT64_MAX;             // All ones
2641     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2642     return C->getSExtValue() == Val-1;
2643   }
2644   return C->getZExtValue() == C->getType()->getIntegerTypeMask()-1;
2645 }
2646
2647 // isMinValuePlusOne - return true if this is Min+1
2648 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2649   if (isSigned) {
2650     // Calculate 1111111111000000000000
2651     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2652     int64_t Val = -1;                    // All ones
2653     Val <<= TypeBits-1;                  // Shift over to the right spot
2654     return C->getSExtValue() == Val+1;
2655   }
2656   return C->getZExtValue() == 1; // unsigned
2657 }
2658
2659 // isOneBitSet - Return true if there is exactly one bit set in the specified
2660 // constant.
2661 static bool isOneBitSet(const ConstantInt *CI) {
2662   uint64_t V = CI->getZExtValue();
2663   return V && (V & (V-1)) == 0;
2664 }
2665
2666 #if 0   // Currently unused
2667 // isLowOnes - Return true if the constant is of the form 0+1+.
2668 static bool isLowOnes(const ConstantInt *CI) {
2669   uint64_t V = CI->getZExtValue();
2670
2671   // There won't be bits set in parts that the type doesn't contain.
2672   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2673
2674   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2675   return U && V && (U & V) == 0;
2676 }
2677 #endif
2678
2679 // isHighOnes - Return true if the constant is of the form 1+0+.
2680 // This is the same as lowones(~X).
2681 static bool isHighOnes(const ConstantInt *CI) {
2682   uint64_t V = ~CI->getZExtValue();
2683   if (~V == 0) return false;  // 0's does not match "1+"
2684
2685   // There won't be bits set in parts that the type doesn't contain.
2686   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2687
2688   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2689   return U && V && (U & V) == 0;
2690 }
2691
2692 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2693 /// are carefully arranged to allow folding of expressions such as:
2694 ///
2695 ///      (A < B) | (A > B) --> (A != B)
2696 ///
2697 /// Note that this is only valid if the first and second predicates have the
2698 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2699 ///
2700 /// Three bits are used to represent the condition, as follows:
2701 ///   0  A > B
2702 ///   1  A == B
2703 ///   2  A < B
2704 ///
2705 /// <=>  Value  Definition
2706 /// 000     0   Always false
2707 /// 001     1   A >  B
2708 /// 010     2   A == B
2709 /// 011     3   A >= B
2710 /// 100     4   A <  B
2711 /// 101     5   A != B
2712 /// 110     6   A <= B
2713 /// 111     7   Always true
2714 ///  
2715 static unsigned getICmpCode(const ICmpInst *ICI) {
2716   switch (ICI->getPredicate()) {
2717     // False -> 0
2718   case ICmpInst::ICMP_UGT: return 1;  // 001
2719   case ICmpInst::ICMP_SGT: return 1;  // 001
2720   case ICmpInst::ICMP_EQ:  return 2;  // 010
2721   case ICmpInst::ICMP_UGE: return 3;  // 011
2722   case ICmpInst::ICMP_SGE: return 3;  // 011
2723   case ICmpInst::ICMP_ULT: return 4;  // 100
2724   case ICmpInst::ICMP_SLT: return 4;  // 100
2725   case ICmpInst::ICMP_NE:  return 5;  // 101
2726   case ICmpInst::ICMP_ULE: return 6;  // 110
2727   case ICmpInst::ICMP_SLE: return 6;  // 110
2728     // True -> 7
2729   default:
2730     assert(0 && "Invalid ICmp predicate!");
2731     return 0;
2732   }
2733 }
2734
2735 /// getICmpValue - This is the complement of getICmpCode, which turns an
2736 /// opcode and two operands into either a constant true or false, or a brand 
2737 /// new /// ICmp instruction. The sign is passed in to determine which kind
2738 /// of predicate to use in new icmp instructions.
2739 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2740   switch (code) {
2741   default: assert(0 && "Illegal ICmp code!");
2742   case  0: return ConstantInt::getFalse();
2743   case  1: 
2744     if (sign)
2745       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2746     else
2747       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2748   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2749   case  3: 
2750     if (sign)
2751       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2752     else
2753       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2754   case  4: 
2755     if (sign)
2756       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2757     else
2758       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2759   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2760   case  6: 
2761     if (sign)
2762       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2763     else
2764       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2765   case  7: return ConstantInt::getTrue();
2766   }
2767 }
2768
2769 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2770   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2771     (ICmpInst::isSignedPredicate(p1) && 
2772      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2773     (ICmpInst::isSignedPredicate(p2) && 
2774      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2775 }
2776
2777 namespace { 
2778 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2779 struct FoldICmpLogical {
2780   InstCombiner &IC;
2781   Value *LHS, *RHS;
2782   ICmpInst::Predicate pred;
2783   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2784     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2785       pred(ICI->getPredicate()) {}
2786   bool shouldApply(Value *V) const {
2787     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2788       if (PredicatesFoldable(pred, ICI->getPredicate()))
2789         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2790                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2791     return false;
2792   }
2793   Instruction *apply(Instruction &Log) const {
2794     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2795     if (ICI->getOperand(0) != LHS) {
2796       assert(ICI->getOperand(1) == LHS);
2797       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2798     }
2799
2800     unsigned LHSCode = getICmpCode(ICI);
2801     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2802     unsigned Code;
2803     switch (Log.getOpcode()) {
2804     case Instruction::And: Code = LHSCode & RHSCode; break;
2805     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2806     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2807     default: assert(0 && "Illegal logical opcode!"); return 0;
2808     }
2809
2810     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2811     if (Instruction *I = dyn_cast<Instruction>(RV))
2812       return I;
2813     // Otherwise, it's a constant boolean value...
2814     return IC.ReplaceInstUsesWith(Log, RV);
2815   }
2816 };
2817 } // end anonymous namespace
2818
2819 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2820 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2821 // guaranteed to be either a shift instruction or a binary operator.
2822 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2823                                     ConstantInt *OpRHS,
2824                                     ConstantInt *AndRHS,
2825                                     BinaryOperator &TheAnd) {
2826   Value *X = Op->getOperand(0);
2827   Constant *Together = 0;
2828   if (!isa<ShiftInst>(Op))
2829     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2830
2831   switch (Op->getOpcode()) {
2832   case Instruction::Xor:
2833     if (Op->hasOneUse()) {
2834       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2835       std::string OpName = Op->getName(); Op->setName("");
2836       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2837       InsertNewInstBefore(And, TheAnd);
2838       return BinaryOperator::createXor(And, Together);
2839     }
2840     break;
2841   case Instruction::Or:
2842     if (Together == AndRHS) // (X | C) & C --> C
2843       return ReplaceInstUsesWith(TheAnd, AndRHS);
2844
2845     if (Op->hasOneUse() && Together != OpRHS) {
2846       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2847       std::string Op0Name = Op->getName(); Op->setName("");
2848       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2849       InsertNewInstBefore(Or, TheAnd);
2850       return BinaryOperator::createAnd(Or, AndRHS);
2851     }
2852     break;
2853   case Instruction::Add:
2854     if (Op->hasOneUse()) {
2855       // Adding a one to a single bit bit-field should be turned into an XOR
2856       // of the bit.  First thing to check is to see if this AND is with a
2857       // single bit constant.
2858       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2859
2860       // Clear bits that are not part of the constant.
2861       AndRHSV &= AndRHS->getType()->getIntegerTypeMask();
2862
2863       // If there is only one bit set...
2864       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2865         // Ok, at this point, we know that we are masking the result of the
2866         // ADD down to exactly one bit.  If the constant we are adding has
2867         // no bits set below this bit, then we can eliminate the ADD.
2868         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2869
2870         // Check to see if any bits below the one bit set in AndRHSV are set.
2871         if ((AddRHS & (AndRHSV-1)) == 0) {
2872           // If not, the only thing that can effect the output of the AND is
2873           // the bit specified by AndRHSV.  If that bit is set, the effect of
2874           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2875           // no effect.
2876           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2877             TheAnd.setOperand(0, X);
2878             return &TheAnd;
2879           } else {
2880             std::string Name = Op->getName(); Op->setName("");
2881             // Pull the XOR out of the AND.
2882             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2883             InsertNewInstBefore(NewAnd, TheAnd);
2884             return BinaryOperator::createXor(NewAnd, AndRHS);
2885           }
2886         }
2887       }
2888     }
2889     break;
2890
2891   case Instruction::Shl: {
2892     // We know that the AND will not produce any of the bits shifted in, so if
2893     // the anded constant includes them, clear them now!
2894     //
2895     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2896     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2897     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2898
2899     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2900       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2901     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2902       TheAnd.setOperand(1, CI);
2903       return &TheAnd;
2904     }
2905     break;
2906   }
2907   case Instruction::LShr:
2908   {
2909     // We know that the AND will not produce any of the bits shifted in, so if
2910     // the anded constant includes them, clear them now!  This only applies to
2911     // unsigned shifts, because a signed shr may bring in set bits!
2912     //
2913     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2914     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2915     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2916
2917     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2918       return ReplaceInstUsesWith(TheAnd, Op);
2919     } else if (CI != AndRHS) {
2920       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2921       return &TheAnd;
2922     }
2923     break;
2924   }
2925   case Instruction::AShr:
2926     // Signed shr.
2927     // See if this is shifting in some sign extension, then masking it out
2928     // with an and.
2929     if (Op->hasOneUse()) {
2930       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2931       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2932       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2933       if (C == AndRHS) {          // Masking out bits shifted in.
2934         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2935         // Make the argument unsigned.
2936         Value *ShVal = Op->getOperand(0);
2937         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2938                                     OpRHS, Op->getName()), TheAnd);
2939         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2940       }
2941     }
2942     break;
2943   }
2944   return 0;
2945 }
2946
2947
2948 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2949 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2950 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2951 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2952 /// insert new instructions.
2953 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2954                                            bool isSigned, bool Inside, 
2955                                            Instruction &IB) {
2956   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
2957             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2958          "Lo is not <= Hi in range emission code!");
2959     
2960   if (Inside) {
2961     if (Lo == Hi)  // Trivially false.
2962       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2963
2964     // V >= Min && V < Hi --> V < Hi
2965     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2966     ICmpInst::Predicate pred = (isSigned ? 
2967         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2968       return new ICmpInst(pred, V, Hi);
2969     }
2970
2971     // Emit V-Lo <u Hi-Lo
2972     Constant *NegLo = ConstantExpr::getNeg(Lo);
2973     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2974     InsertNewInstBefore(Add, IB);
2975     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2976     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2977   }
2978
2979   if (Lo == Hi)  // Trivially true.
2980     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2981
2982   // V < Min || V >= Hi ->'V > Hi-1'
2983   Hi = SubOne(cast<ConstantInt>(Hi));
2984   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2985     ICmpInst::Predicate pred = (isSigned ? 
2986         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2987     return new ICmpInst(pred, V, Hi);
2988   }
2989
2990   // Emit V-Lo > Hi-1-Lo
2991   Constant *NegLo = ConstantExpr::getNeg(Lo);
2992   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2993   InsertNewInstBefore(Add, IB);
2994   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2995   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
2996 }
2997
2998 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2999 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3000 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3001 // not, since all 1s are not contiguous.
3002 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3003   uint64_t V = Val->getZExtValue();
3004   if (!isShiftedMask_64(V)) return false;
3005
3006   // look for the first zero bit after the run of ones
3007   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3008   // look for the first non-zero bit
3009   ME = 64-CountLeadingZeros_64(V);
3010   return true;
3011 }
3012
3013
3014
3015 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3016 /// where isSub determines whether the operator is a sub.  If we can fold one of
3017 /// the following xforms:
3018 /// 
3019 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3020 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3021 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3022 ///
3023 /// return (A +/- B).
3024 ///
3025 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3026                                         ConstantInt *Mask, bool isSub,
3027                                         Instruction &I) {
3028   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3029   if (!LHSI || LHSI->getNumOperands() != 2 ||
3030       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3031
3032   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3033
3034   switch (LHSI->getOpcode()) {
3035   default: return 0;
3036   case Instruction::And:
3037     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3038       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3039       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3040         break;
3041
3042       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3043       // part, we don't need any explicit masks to take them out of A.  If that
3044       // is all N is, ignore it.
3045       unsigned MB, ME;
3046       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3047         uint64_t Mask = RHS->getType()->getIntegerTypeMask();
3048         Mask >>= 64-MB+1;
3049         if (MaskedValueIsZero(RHS, Mask))
3050           break;
3051       }
3052     }
3053     return 0;
3054   case Instruction::Or:
3055   case Instruction::Xor:
3056     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3057     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3058         ConstantExpr::getAnd(N, Mask)->isNullValue())
3059       break;
3060     return 0;
3061   }
3062   
3063   Instruction *New;
3064   if (isSub)
3065     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3066   else
3067     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3068   return InsertNewInstBefore(New, I);
3069 }
3070
3071 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3072   bool Changed = SimplifyCommutative(I);
3073   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3074
3075   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3076     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3077
3078   // and X, X = X
3079   if (Op0 == Op1)
3080     return ReplaceInstUsesWith(I, Op1);
3081
3082   // See if we can simplify any instructions used by the instruction whose sole 
3083   // purpose is to compute bits we don't care about.
3084   uint64_t KnownZero, KnownOne;
3085   if (!isa<PackedType>(I.getType()) &&
3086       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3087                            KnownZero, KnownOne))
3088     return &I;
3089   
3090   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3091     uint64_t AndRHSMask = AndRHS->getZExtValue();
3092     uint64_t TypeMask = Op0->getType()->getIntegerTypeMask();
3093     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3094
3095     // Optimize a variety of ((val OP C1) & C2) combinations...
3096     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3097       Instruction *Op0I = cast<Instruction>(Op0);
3098       Value *Op0LHS = Op0I->getOperand(0);
3099       Value *Op0RHS = Op0I->getOperand(1);
3100       switch (Op0I->getOpcode()) {
3101       case Instruction::Xor:
3102       case Instruction::Or:
3103         // If the mask is only needed on one incoming arm, push it up.
3104         if (Op0I->hasOneUse()) {
3105           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3106             // Not masking anything out for the LHS, move to RHS.
3107             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3108                                                    Op0RHS->getName()+".masked");
3109             InsertNewInstBefore(NewRHS, I);
3110             return BinaryOperator::create(
3111                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3112           }
3113           if (!isa<Constant>(Op0RHS) &&
3114               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3115             // Not masking anything out for the RHS, move to LHS.
3116             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3117                                                    Op0LHS->getName()+".masked");
3118             InsertNewInstBefore(NewLHS, I);
3119             return BinaryOperator::create(
3120                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3121           }
3122         }
3123
3124         break;
3125       case Instruction::Add:
3126         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3127         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3128         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3129         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3130           return BinaryOperator::createAnd(V, AndRHS);
3131         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3132           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3133         break;
3134
3135       case Instruction::Sub:
3136         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3137         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3138         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3139         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3140           return BinaryOperator::createAnd(V, AndRHS);
3141         break;
3142       }
3143
3144       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3145         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3146           return Res;
3147     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3148       // If this is an integer truncation or change from signed-to-unsigned, and
3149       // if the source is an and/or with immediate, transform it.  This
3150       // frequently occurs for bitfield accesses.
3151       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3152         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3153             CastOp->getNumOperands() == 2)
3154           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3155             if (CastOp->getOpcode() == Instruction::And) {
3156               // Change: and (cast (and X, C1) to T), C2
3157               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3158               // This will fold the two constants together, which may allow 
3159               // other simplifications.
3160               Instruction *NewCast = CastInst::createTruncOrBitCast(
3161                 CastOp->getOperand(0), I.getType(), 
3162                 CastOp->getName()+".shrunk");
3163               NewCast = InsertNewInstBefore(NewCast, I);
3164               // trunc_or_bitcast(C1)&C2
3165               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3166               C3 = ConstantExpr::getAnd(C3, AndRHS);
3167               return BinaryOperator::createAnd(NewCast, C3);
3168             } else if (CastOp->getOpcode() == Instruction::Or) {
3169               // Change: and (cast (or X, C1) to T), C2
3170               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3171               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3172               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3173                 return ReplaceInstUsesWith(I, AndRHS);
3174             }
3175       }
3176     }
3177
3178     // Try to fold constant and into select arguments.
3179     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3180       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3181         return R;
3182     if (isa<PHINode>(Op0))
3183       if (Instruction *NV = FoldOpIntoPhi(I))
3184         return NV;
3185   }
3186
3187   Value *Op0NotVal = dyn_castNotVal(Op0);
3188   Value *Op1NotVal = dyn_castNotVal(Op1);
3189
3190   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3191     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3192
3193   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3194   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3195     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3196                                                I.getName()+".demorgan");
3197     InsertNewInstBefore(Or, I);
3198     return BinaryOperator::createNot(Or);
3199   }
3200   
3201   {
3202     Value *A = 0, *B = 0;
3203     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3204       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3205         return ReplaceInstUsesWith(I, Op1);
3206     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3207       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3208         return ReplaceInstUsesWith(I, Op0);
3209     
3210     if (Op0->hasOneUse() &&
3211         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3212       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3213         I.swapOperands();     // Simplify below
3214         std::swap(Op0, Op1);
3215       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3216         cast<BinaryOperator>(Op0)->swapOperands();
3217         I.swapOperands();     // Simplify below
3218         std::swap(Op0, Op1);
3219       }
3220     }
3221     if (Op1->hasOneUse() &&
3222         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3223       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3224         cast<BinaryOperator>(Op1)->swapOperands();
3225         std::swap(A, B);
3226       }
3227       if (A == Op0) {                                // A&(A^B) -> A & ~B
3228         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3229         InsertNewInstBefore(NotB, I);
3230         return BinaryOperator::createAnd(A, NotB);
3231       }
3232     }
3233   }
3234   
3235   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3236     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3237     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3238       return R;
3239
3240     Value *LHSVal, *RHSVal;
3241     ConstantInt *LHSCst, *RHSCst;
3242     ICmpInst::Predicate LHSCC, RHSCC;
3243     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3244       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3245         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3246             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3247             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3248             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3249             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3250             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3251           // Ensure that the larger constant is on the RHS.
3252           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3253             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3254           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3255           ICmpInst *LHS = cast<ICmpInst>(Op0);
3256           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3257             std::swap(LHS, RHS);
3258             std::swap(LHSCst, RHSCst);
3259             std::swap(LHSCC, RHSCC);
3260           }
3261
3262           // At this point, we know we have have two icmp instructions
3263           // comparing a value against two constants and and'ing the result
3264           // together.  Because of the above check, we know that we only have
3265           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3266           // (from the FoldICmpLogical check above), that the two constants 
3267           // are not equal and that the larger constant is on the RHS
3268           assert(LHSCst != RHSCst && "Compares not folded above?");
3269
3270           switch (LHSCC) {
3271           default: assert(0 && "Unknown integer condition code!");
3272           case ICmpInst::ICMP_EQ:
3273             switch (RHSCC) {
3274             default: assert(0 && "Unknown integer condition code!");
3275             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3276             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3277             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3278               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3279             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3280             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3281             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3282               return ReplaceInstUsesWith(I, LHS);
3283             }
3284           case ICmpInst::ICMP_NE:
3285             switch (RHSCC) {
3286             default: assert(0 && "Unknown integer condition code!");
3287             case ICmpInst::ICMP_ULT:
3288               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3289                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3290               break;                        // (X != 13 & X u< 15) -> no change
3291             case ICmpInst::ICMP_SLT:
3292               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3293                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3294               break;                        // (X != 13 & X s< 15) -> no change
3295             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3296             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3297             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3298               return ReplaceInstUsesWith(I, RHS);
3299             case ICmpInst::ICMP_NE:
3300               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3301                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3302                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3303                                                       LHSVal->getName()+".off");
3304                 InsertNewInstBefore(Add, I);
3305                 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3306               }
3307               break;                        // (X != 13 & X != 15) -> no change
3308             }
3309             break;
3310           case ICmpInst::ICMP_ULT:
3311             switch (RHSCC) {
3312             default: assert(0 && "Unknown integer condition code!");
3313             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3314             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3315               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3316             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3317               break;
3318             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3319             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3320               return ReplaceInstUsesWith(I, LHS);
3321             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3322               break;
3323             }
3324             break;
3325           case ICmpInst::ICMP_SLT:
3326             switch (RHSCC) {
3327             default: assert(0 && "Unknown integer condition code!");
3328             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3329             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3330               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3331             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3332               break;
3333             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3334             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3335               return ReplaceInstUsesWith(I, LHS);
3336             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3337               break;
3338             }
3339             break;
3340           case ICmpInst::ICMP_UGT:
3341             switch (RHSCC) {
3342             default: assert(0 && "Unknown integer condition code!");
3343             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3344               return ReplaceInstUsesWith(I, LHS);
3345             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3346               return ReplaceInstUsesWith(I, RHS);
3347             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3348               break;
3349             case ICmpInst::ICMP_NE:
3350               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3351                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3352               break;                        // (X u> 13 & X != 15) -> no change
3353             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3354               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3355                                      true, I);
3356             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3357               break;
3358             }
3359             break;
3360           case ICmpInst::ICMP_SGT:
3361             switch (RHSCC) {
3362             default: assert(0 && "Unknown integer condition code!");
3363             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3364               return ReplaceInstUsesWith(I, LHS);
3365             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3366               return ReplaceInstUsesWith(I, RHS);
3367             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3368               break;
3369             case ICmpInst::ICMP_NE:
3370               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3371                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3372               break;                        // (X s> 13 & X != 15) -> no change
3373             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3374               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3375                                      true, I);
3376             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3377               break;
3378             }
3379             break;
3380           }
3381         }
3382   }
3383
3384   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3385   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3386     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3387       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3388         const Type *SrcTy = Op0C->getOperand(0)->getType();
3389         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3390             // Only do this if the casts both really cause code to be generated.
3391             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3392                               I.getType(), TD) &&
3393             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3394                               I.getType(), TD)) {
3395           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3396                                                          Op1C->getOperand(0),
3397                                                          I.getName());
3398           InsertNewInstBefore(NewOp, I);
3399           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3400         }
3401       }
3402     
3403   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3404   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3405     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3406       if (SI0->getOpcode() == SI1->getOpcode() && 
3407           SI0->getOperand(1) == SI1->getOperand(1) &&
3408           (SI0->hasOneUse() || SI1->hasOneUse())) {
3409         Instruction *NewOp =
3410           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3411                                                         SI1->getOperand(0),
3412                                                         SI0->getName()), I);
3413         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3414       }
3415   }
3416
3417   return Changed ? &I : 0;
3418 }
3419
3420 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3421 /// in the result.  If it does, and if the specified byte hasn't been filled in
3422 /// yet, fill it in and return false.
3423 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3424   Instruction *I = dyn_cast<Instruction>(V);
3425   if (I == 0) return true;
3426
3427   // If this is an or instruction, it is an inner node of the bswap.
3428   if (I->getOpcode() == Instruction::Or)
3429     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3430            CollectBSwapParts(I->getOperand(1), ByteValues);
3431   
3432   // If this is a shift by a constant int, and it is "24", then its operand
3433   // defines a byte.  We only handle unsigned types here.
3434   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3435     // Not shifting the entire input by N-1 bytes?
3436     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3437         8*(ByteValues.size()-1))
3438       return true;
3439     
3440     unsigned DestNo;
3441     if (I->getOpcode() == Instruction::Shl) {
3442       // X << 24 defines the top byte with the lowest of the input bytes.
3443       DestNo = ByteValues.size()-1;
3444     } else {
3445       // X >>u 24 defines the low byte with the highest of the input bytes.
3446       DestNo = 0;
3447     }
3448     
3449     // If the destination byte value is already defined, the values are or'd
3450     // together, which isn't a bswap (unless it's an or of the same bits).
3451     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3452       return true;
3453     ByteValues[DestNo] = I->getOperand(0);
3454     return false;
3455   }
3456   
3457   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3458   // don't have this.
3459   Value *Shift = 0, *ShiftLHS = 0;
3460   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3461   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3462       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3463     return true;
3464   Instruction *SI = cast<Instruction>(Shift);
3465
3466   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3467   if (ShiftAmt->getZExtValue() & 7 ||
3468       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3469     return true;
3470   
3471   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3472   unsigned DestByte;
3473   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3474     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3475       break;
3476   // Unknown mask for bswap.
3477   if (DestByte == ByteValues.size()) return true;
3478   
3479   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3480   unsigned SrcByte;
3481   if (SI->getOpcode() == Instruction::Shl)
3482     SrcByte = DestByte - ShiftBytes;
3483   else
3484     SrcByte = DestByte + ShiftBytes;
3485   
3486   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3487   if (SrcByte != ByteValues.size()-DestByte-1)
3488     return true;
3489   
3490   // If the destination byte value is already defined, the values are or'd
3491   // together, which isn't a bswap (unless it's an or of the same bits).
3492   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3493     return true;
3494   ByteValues[DestByte] = SI->getOperand(0);
3495   return false;
3496 }
3497
3498 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3499 /// If so, insert the new bswap intrinsic and return it.
3500 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3501   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3502   if (I.getType() == Type::Int8Ty)
3503     return 0;
3504   
3505   /// ByteValues - For each byte of the result, we keep track of which value
3506   /// defines each byte.
3507   std::vector<Value*> ByteValues;
3508   ByteValues.resize(TD->getTypeSize(I.getType()));
3509     
3510   // Try to find all the pieces corresponding to the bswap.
3511   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3512       CollectBSwapParts(I.getOperand(1), ByteValues))
3513     return 0;
3514   
3515   // Check to see if all of the bytes come from the same value.
3516   Value *V = ByteValues[0];
3517   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3518   
3519   // Check to make sure that all of the bytes come from the same value.
3520   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3521     if (ByteValues[i] != V)
3522       return 0;
3523     
3524   // If they do then *success* we can turn this into a bswap.  Figure out what
3525   // bswap to make it into.
3526   Module *M = I.getParent()->getParent()->getParent();
3527   const char *FnName = 0;
3528   if (I.getType() == Type::Int16Ty)
3529     FnName = "llvm.bswap.i16";
3530   else if (I.getType() == Type::Int32Ty)
3531     FnName = "llvm.bswap.i32";
3532   else if (I.getType() == Type::Int64Ty)
3533     FnName = "llvm.bswap.i64";
3534   else
3535     assert(0 && "Unknown integer type!");
3536   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3537   return new CallInst(F, V);
3538 }
3539
3540
3541 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3542   bool Changed = SimplifyCommutative(I);
3543   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3544
3545   if (isa<UndefValue>(Op1))
3546     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3547                                ConstantInt::getAllOnesValue(I.getType()));
3548
3549   // or X, X = X
3550   if (Op0 == Op1)
3551     return ReplaceInstUsesWith(I, Op0);
3552
3553   // See if we can simplify any instructions used by the instruction whose sole 
3554   // purpose is to compute bits we don't care about.
3555   uint64_t KnownZero, KnownOne;
3556   if (!isa<PackedType>(I.getType()) &&
3557       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3558                            KnownZero, KnownOne))
3559     return &I;
3560   
3561   // or X, -1 == -1
3562   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3563     ConstantInt *C1 = 0; Value *X = 0;
3564     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3565     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3566       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3567       Op0->setName("");
3568       InsertNewInstBefore(Or, I);
3569       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3570     }
3571
3572     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3573     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3574       std::string Op0Name = Op0->getName(); Op0->setName("");
3575       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3576       InsertNewInstBefore(Or, I);
3577       return BinaryOperator::createXor(Or,
3578                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3579     }
3580
3581     // Try to fold constant and into select arguments.
3582     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3583       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3584         return R;
3585     if (isa<PHINode>(Op0))
3586       if (Instruction *NV = FoldOpIntoPhi(I))
3587         return NV;
3588   }
3589
3590   Value *A = 0, *B = 0;
3591   ConstantInt *C1 = 0, *C2 = 0;
3592
3593   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3594     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3595       return ReplaceInstUsesWith(I, Op1);
3596   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3597     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3598       return ReplaceInstUsesWith(I, Op0);
3599
3600   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3601   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3602   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3603       match(Op1, m_Or(m_Value(), m_Value())) ||
3604       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3605        match(Op1, m_Shift(m_Value(), m_Value())))) {
3606     if (Instruction *BSwap = MatchBSwap(I))
3607       return BSwap;
3608   }
3609   
3610   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3611   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3612       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3613     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3614     Op0->setName("");
3615     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3616   }
3617
3618   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3619   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3620       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3621     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3622     Op0->setName("");
3623     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3624   }
3625
3626   // (A & C1)|(B & C2)
3627   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3628       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3629
3630     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3631       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3632
3633
3634     // If we have: ((V + N) & C1) | (V & C2)
3635     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3636     // replace with V+N.
3637     if (C1 == ConstantExpr::getNot(C2)) {
3638       Value *V1 = 0, *V2 = 0;
3639       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3640           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3641         // Add commutes, try both ways.
3642         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3643           return ReplaceInstUsesWith(I, A);
3644         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3645           return ReplaceInstUsesWith(I, A);
3646       }
3647       // Or commutes, try both ways.
3648       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3649           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3650         // Add commutes, try both ways.
3651         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3652           return ReplaceInstUsesWith(I, B);
3653         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3654           return ReplaceInstUsesWith(I, B);
3655       }
3656     }
3657   }
3658   
3659   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3660   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3661     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3662       if (SI0->getOpcode() == SI1->getOpcode() && 
3663           SI0->getOperand(1) == SI1->getOperand(1) &&
3664           (SI0->hasOneUse() || SI1->hasOneUse())) {
3665         Instruction *NewOp =
3666         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3667                                                      SI1->getOperand(0),
3668                                                      SI0->getName()), I);
3669         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3670       }
3671   }
3672
3673   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3674     if (A == Op1)   // ~A | A == -1
3675       return ReplaceInstUsesWith(I,
3676                                 ConstantInt::getAllOnesValue(I.getType()));
3677   } else {
3678     A = 0;
3679   }
3680   // Note, A is still live here!
3681   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3682     if (Op0 == B)
3683       return ReplaceInstUsesWith(I,
3684                                 ConstantInt::getAllOnesValue(I.getType()));
3685
3686     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3687     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3688       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3689                                               I.getName()+".demorgan"), I);
3690       return BinaryOperator::createNot(And);
3691     }
3692   }
3693
3694   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3695   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3696     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3697       return R;
3698
3699     Value *LHSVal, *RHSVal;
3700     ConstantInt *LHSCst, *RHSCst;
3701     ICmpInst::Predicate LHSCC, RHSCC;
3702     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3703       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3704         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3705             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3706             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3707             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3708             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3709             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3710           // Ensure that the larger constant is on the RHS.
3711           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3712             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3713           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3714           ICmpInst *LHS = cast<ICmpInst>(Op0);
3715           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3716             std::swap(LHS, RHS);
3717             std::swap(LHSCst, RHSCst);
3718             std::swap(LHSCC, RHSCC);
3719           }
3720
3721           // At this point, we know we have have two icmp instructions
3722           // comparing a value against two constants and or'ing the result
3723           // together.  Because of the above check, we know that we only have
3724           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3725           // FoldICmpLogical check above), that the two constants are not
3726           // equal.
3727           assert(LHSCst != RHSCst && "Compares not folded above?");
3728
3729           switch (LHSCC) {
3730           default: assert(0 && "Unknown integer condition code!");
3731           case ICmpInst::ICMP_EQ:
3732             switch (RHSCC) {
3733             default: assert(0 && "Unknown integer condition code!");
3734             case ICmpInst::ICMP_EQ:
3735               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3736                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3737                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3738                                                       LHSVal->getName()+".off");
3739                 InsertNewInstBefore(Add, I);
3740                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3741                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3742               }
3743               break;                         // (X == 13 | X == 15) -> no change
3744             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3745             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3746               break;
3747             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3748             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3749             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3750               return ReplaceInstUsesWith(I, RHS);
3751             }
3752             break;
3753           case ICmpInst::ICMP_NE:
3754             switch (RHSCC) {
3755             default: assert(0 && "Unknown integer condition code!");
3756             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3757             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3758             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3759               return ReplaceInstUsesWith(I, LHS);
3760             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3761             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3762             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3763               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3764             }
3765             break;
3766           case ICmpInst::ICMP_ULT:
3767             switch (RHSCC) {
3768             default: assert(0 && "Unknown integer condition code!");
3769             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3770               break;
3771             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3772               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3773                                      false, I);
3774             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3775               break;
3776             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3777             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3778               return ReplaceInstUsesWith(I, RHS);
3779             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3780               break;
3781             }
3782             break;
3783           case ICmpInst::ICMP_SLT:
3784             switch (RHSCC) {
3785             default: assert(0 && "Unknown integer condition code!");
3786             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3787               break;
3788             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3789               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3790                                      false, I);
3791             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3792               break;
3793             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3794             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3795               return ReplaceInstUsesWith(I, RHS);
3796             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3797               break;
3798             }
3799             break;
3800           case ICmpInst::ICMP_UGT:
3801             switch (RHSCC) {
3802             default: assert(0 && "Unknown integer condition code!");
3803             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3804             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3805               return ReplaceInstUsesWith(I, LHS);
3806             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3807               break;
3808             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3809             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3810               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3811             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3812               break;
3813             }
3814             break;
3815           case ICmpInst::ICMP_SGT:
3816             switch (RHSCC) {
3817             default: assert(0 && "Unknown integer condition code!");
3818             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3819             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3820               return ReplaceInstUsesWith(I, LHS);
3821             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3822               break;
3823             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3824             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3825               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3826             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3827               break;
3828             }
3829             break;
3830           }
3831         }
3832   }
3833     
3834   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3835   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3836     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3837       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3838         const Type *SrcTy = Op0C->getOperand(0)->getType();
3839         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3840             // Only do this if the casts both really cause code to be generated.
3841             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3842                               I.getType(), TD) &&
3843             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3844                               I.getType(), TD)) {
3845           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3846                                                         Op1C->getOperand(0),
3847                                                         I.getName());
3848           InsertNewInstBefore(NewOp, I);
3849           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3850         }
3851       }
3852       
3853
3854   return Changed ? &I : 0;
3855 }
3856
3857 // XorSelf - Implements: X ^ X --> 0
3858 struct XorSelf {
3859   Value *RHS;
3860   XorSelf(Value *rhs) : RHS(rhs) {}
3861   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3862   Instruction *apply(BinaryOperator &Xor) const {
3863     return &Xor;
3864   }
3865 };
3866
3867
3868 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3869   bool Changed = SimplifyCommutative(I);
3870   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3871
3872   if (isa<UndefValue>(Op1))
3873     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3874
3875   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3876   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3877     assert(Result == &I && "AssociativeOpt didn't work?");
3878     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3879   }
3880   
3881   // See if we can simplify any instructions used by the instruction whose sole 
3882   // purpose is to compute bits we don't care about.
3883   uint64_t KnownZero, KnownOne;
3884   if (!isa<PackedType>(I.getType()) &&
3885       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3886                            KnownZero, KnownOne))
3887     return &I;
3888
3889   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3890     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3891     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3892       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3893         return new ICmpInst(ICI->getInversePredicate(),
3894                             ICI->getOperand(0), ICI->getOperand(1));
3895
3896     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3897       // ~(c-X) == X-c-1 == X+(-c-1)
3898       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3899         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3900           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3901           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3902                                               ConstantInt::get(I.getType(), 1));
3903           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3904         }
3905
3906       // ~(~X & Y) --> (X | ~Y)
3907       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3908         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3909         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3910           Instruction *NotY =
3911             BinaryOperator::createNot(Op0I->getOperand(1),
3912                                       Op0I->getOperand(1)->getName()+".not");
3913           InsertNewInstBefore(NotY, I);
3914           return BinaryOperator::createOr(Op0NotVal, NotY);
3915         }
3916       }
3917
3918       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3919         if (Op0I->getOpcode() == Instruction::Add) {
3920           // ~(X-c) --> (-c-1)-X
3921           if (RHS->isAllOnesValue()) {
3922             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3923             return BinaryOperator::createSub(
3924                            ConstantExpr::getSub(NegOp0CI,
3925                                              ConstantInt::get(I.getType(), 1)),
3926                                           Op0I->getOperand(0));
3927           }
3928         } else if (Op0I->getOpcode() == Instruction::Or) {
3929           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3930           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3931             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3932             // Anything in both C1 and C2 is known to be zero, remove it from
3933             // NewRHS.
3934             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3935             NewRHS = ConstantExpr::getAnd(NewRHS, 
3936                                           ConstantExpr::getNot(CommonBits));
3937             WorkList.push_back(Op0I);
3938             I.setOperand(0, Op0I->getOperand(0));
3939             I.setOperand(1, NewRHS);
3940             return &I;
3941           }
3942         }
3943     }
3944
3945     // Try to fold constant and into select arguments.
3946     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3947       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3948         return R;
3949     if (isa<PHINode>(Op0))
3950       if (Instruction *NV = FoldOpIntoPhi(I))
3951         return NV;
3952   }
3953
3954   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3955     if (X == Op1)
3956       return ReplaceInstUsesWith(I,
3957                                 ConstantInt::getAllOnesValue(I.getType()));
3958
3959   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3960     if (X == Op0)
3961       return ReplaceInstUsesWith(I,
3962                                 ConstantInt::getAllOnesValue(I.getType()));
3963
3964   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3965     if (Op1I->getOpcode() == Instruction::Or) {
3966       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3967         Op1I->swapOperands();
3968         I.swapOperands();
3969         std::swap(Op0, Op1);
3970       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3971         I.swapOperands();     // Simplified below.
3972         std::swap(Op0, Op1);
3973       }
3974     } else if (Op1I->getOpcode() == Instruction::Xor) {
3975       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3976         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3977       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3978         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3979     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3980       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3981         Op1I->swapOperands();
3982       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3983         I.swapOperands();     // Simplified below.
3984         std::swap(Op0, Op1);
3985       }
3986     }
3987
3988   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3989     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3990       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3991         Op0I->swapOperands();
3992       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3993         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3994         InsertNewInstBefore(NotB, I);
3995         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3996       }
3997     } else if (Op0I->getOpcode() == Instruction::Xor) {
3998       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3999         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4000       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4001         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4002     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4003       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4004         Op0I->swapOperands();
4005       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4006           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4007         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4008         InsertNewInstBefore(N, I);
4009         return BinaryOperator::createAnd(N, Op1);
4010       }
4011     }
4012
4013   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4014   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4015     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4016       return R;
4017
4018   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4019   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4020     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4021       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4022         const Type *SrcTy = Op0C->getOperand(0)->getType();
4023         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4024             // Only do this if the casts both really cause code to be generated.
4025             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4026                               I.getType(), TD) &&
4027             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4028                               I.getType(), TD)) {
4029           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4030                                                          Op1C->getOperand(0),
4031                                                          I.getName());
4032           InsertNewInstBefore(NewOp, I);
4033           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4034         }
4035       }
4036
4037   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4038   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4039     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4040       if (SI0->getOpcode() == SI1->getOpcode() && 
4041           SI0->getOperand(1) == SI1->getOperand(1) &&
4042           (SI0->hasOneUse() || SI1->hasOneUse())) {
4043         Instruction *NewOp =
4044         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4045                                                       SI1->getOperand(0),
4046                                                       SI0->getName()), I);
4047         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4048       }
4049   }
4050     
4051   return Changed ? &I : 0;
4052 }
4053
4054 static bool isPositive(ConstantInt *C) {
4055   return C->getSExtValue() >= 0;
4056 }
4057
4058 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4059 /// overflowed for this type.
4060 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4061                             ConstantInt *In2) {
4062   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4063
4064   return cast<ConstantInt>(Result)->getZExtValue() <
4065          cast<ConstantInt>(In1)->getZExtValue();
4066 }
4067
4068 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4069 /// code necessary to compute the offset from the base pointer (without adding
4070 /// in the base pointer).  Return the result as a signed integer of intptr size.
4071 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4072   TargetData &TD = IC.getTargetData();
4073   gep_type_iterator GTI = gep_type_begin(GEP);
4074   const Type *IntPtrTy = TD.getIntPtrType();
4075   Value *Result = Constant::getNullValue(IntPtrTy);
4076
4077   // Build a mask for high order bits.
4078   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4079
4080   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4081     Value *Op = GEP->getOperand(i);
4082     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4083     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4084     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4085       if (!OpC->isNullValue()) {
4086         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4087         Scale = ConstantExpr::getMul(OpC, Scale);
4088         if (Constant *RC = dyn_cast<Constant>(Result))
4089           Result = ConstantExpr::getAdd(RC, Scale);
4090         else {
4091           // Emit an add instruction.
4092           Result = IC.InsertNewInstBefore(
4093              BinaryOperator::createAdd(Result, Scale,
4094                                        GEP->getName()+".offs"), I);
4095         }
4096       }
4097     } else {
4098       // Convert to correct type.
4099       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4100                                                Op->getName()+".c"), I);
4101       if (Size != 1)
4102         // We'll let instcombine(mul) convert this to a shl if possible.
4103         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4104                                                     GEP->getName()+".idx"), I);
4105
4106       // Emit an add instruction.
4107       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4108                                                     GEP->getName()+".offs"), I);
4109     }
4110   }
4111   return Result;
4112 }
4113
4114 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4115 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4116 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4117                                        ICmpInst::Predicate Cond,
4118                                        Instruction &I) {
4119   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4120
4121   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4122     if (isa<PointerType>(CI->getOperand(0)->getType()))
4123       RHS = CI->getOperand(0);
4124
4125   Value *PtrBase = GEPLHS->getOperand(0);
4126   if (PtrBase == RHS) {
4127     // As an optimization, we don't actually have to compute the actual value of
4128     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4129     // each index is zero or not.
4130     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4131       Instruction *InVal = 0;
4132       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4133       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4134         bool EmitIt = true;
4135         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4136           if (isa<UndefValue>(C))  // undef index -> undef.
4137             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4138           if (C->isNullValue())
4139             EmitIt = false;
4140           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4141             EmitIt = false;  // This is indexing into a zero sized array?
4142           } else if (isa<ConstantInt>(C))
4143             return ReplaceInstUsesWith(I, // No comparison is needed here.
4144                                  ConstantInt::get(Type::Int1Ty, 
4145                                                   Cond == ICmpInst::ICMP_NE));
4146         }
4147
4148         if (EmitIt) {
4149           Instruction *Comp =
4150             new ICmpInst(Cond, GEPLHS->getOperand(i),
4151                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4152           if (InVal == 0)
4153             InVal = Comp;
4154           else {
4155             InVal = InsertNewInstBefore(InVal, I);
4156             InsertNewInstBefore(Comp, I);
4157             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4158               InVal = BinaryOperator::createOr(InVal, Comp);
4159             else                              // True if all are equal
4160               InVal = BinaryOperator::createAnd(InVal, Comp);
4161           }
4162         }
4163       }
4164
4165       if (InVal)
4166         return InVal;
4167       else
4168         // No comparison is needed here, all indexes = 0
4169         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4170                                                 Cond == ICmpInst::ICMP_EQ));
4171     }
4172
4173     // Only lower this if the icmp is the only user of the GEP or if we expect
4174     // the result to fold to a constant!
4175     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4176       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4177       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4178       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4179                           Constant::getNullValue(Offset->getType()));
4180     }
4181   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4182     // If the base pointers are different, but the indices are the same, just
4183     // compare the base pointer.
4184     if (PtrBase != GEPRHS->getOperand(0)) {
4185       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4186       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4187                         GEPRHS->getOperand(0)->getType();
4188       if (IndicesTheSame)
4189         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4190           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4191             IndicesTheSame = false;
4192             break;
4193           }
4194
4195       // If all indices are the same, just compare the base pointers.
4196       if (IndicesTheSame)
4197         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4198                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4199
4200       // Otherwise, the base pointers are different and the indices are
4201       // different, bail out.
4202       return 0;
4203     }
4204
4205     // If one of the GEPs has all zero indices, recurse.
4206     bool AllZeros = true;
4207     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4208       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4209           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4210         AllZeros = false;
4211         break;
4212       }
4213     if (AllZeros)
4214       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4215                           ICmpInst::getSwappedPredicate(Cond), I);
4216
4217     // If the other GEP has all zero indices, recurse.
4218     AllZeros = true;
4219     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4220       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4221           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4222         AllZeros = false;
4223         break;
4224       }
4225     if (AllZeros)
4226       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4227
4228     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4229       // If the GEPs only differ by one index, compare it.
4230       unsigned NumDifferences = 0;  // Keep track of # differences.
4231       unsigned DiffOperand = 0;     // The operand that differs.
4232       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4233         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4234           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4235                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4236             // Irreconcilable differences.
4237             NumDifferences = 2;
4238             break;
4239           } else {
4240             if (NumDifferences++) break;
4241             DiffOperand = i;
4242           }
4243         }
4244
4245       if (NumDifferences == 0)   // SAME GEP?
4246         return ReplaceInstUsesWith(I, // No comparison is needed here.
4247                                    ConstantInt::get(Type::Int1Ty, 
4248                                                     Cond == ICmpInst::ICMP_EQ));
4249       else if (NumDifferences == 1) {
4250         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4251         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4252         // Make sure we do a signed comparison here.
4253         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4254       }
4255     }
4256
4257     // Only lower this if the icmp is the only user of the GEP or if we expect
4258     // the result to fold to a constant!
4259     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4260         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4261       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4262       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4263       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4264       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4265     }
4266   }
4267   return 0;
4268 }
4269
4270 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4271   bool Changed = SimplifyCompare(I);
4272   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4273
4274   // Fold trivial predicates.
4275   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4276     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4277   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4278     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4279   
4280   // Simplify 'fcmp pred X, X'
4281   if (Op0 == Op1) {
4282     switch (I.getPredicate()) {
4283     default: assert(0 && "Unknown predicate!");
4284     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4285     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4286     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4287       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4288     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4289     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4290     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4291       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4292       
4293     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4294     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4295     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4296     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4297       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4298       I.setPredicate(FCmpInst::FCMP_UNO);
4299       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4300       return &I;
4301       
4302     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4303     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4304     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4305     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4306       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4307       I.setPredicate(FCmpInst::FCMP_ORD);
4308       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4309       return &I;
4310     }
4311   }
4312     
4313   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4314     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4315
4316   // Handle fcmp with constant RHS
4317   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4318     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4319       switch (LHSI->getOpcode()) {
4320       case Instruction::PHI:
4321         if (Instruction *NV = FoldOpIntoPhi(I))
4322           return NV;
4323         break;
4324       case Instruction::Select:
4325         // If either operand of the select is a constant, we can fold the
4326         // comparison into the select arms, which will cause one to be
4327         // constant folded and the select turned into a bitwise or.
4328         Value *Op1 = 0, *Op2 = 0;
4329         if (LHSI->hasOneUse()) {
4330           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4331             // Fold the known value into the constant operand.
4332             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4333             // Insert a new FCmp of the other select operand.
4334             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4335                                                       LHSI->getOperand(2), RHSC,
4336                                                       I.getName()), I);
4337           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4338             // Fold the known value into the constant operand.
4339             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4340             // Insert a new FCmp of the other select operand.
4341             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4342                                                       LHSI->getOperand(1), RHSC,
4343                                                       I.getName()), I);
4344           }
4345         }
4346
4347         if (Op1)
4348           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4349         break;
4350       }
4351   }
4352
4353   return Changed ? &I : 0;
4354 }
4355
4356 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4357   bool Changed = SimplifyCompare(I);
4358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4359   const Type *Ty = Op0->getType();
4360
4361   // icmp X, X
4362   if (Op0 == Op1)
4363     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4364                                                    isTrueWhenEqual(I)));
4365
4366   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4367     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4368
4369   // icmp of GlobalValues can never equal each other as long as they aren't
4370   // external weak linkage type.
4371   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4372     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4373       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4374         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4375                                                        !isTrueWhenEqual(I)));
4376
4377   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4378   // addresses never equal each other!  We already know that Op0 != Op1.
4379   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4380        isa<ConstantPointerNull>(Op0)) &&
4381       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4382        isa<ConstantPointerNull>(Op1)))
4383     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4384                                                    !isTrueWhenEqual(I)));
4385
4386   // icmp's with boolean values can always be turned into bitwise operations
4387   if (Ty == Type::Int1Ty) {
4388     switch (I.getPredicate()) {
4389     default: assert(0 && "Invalid icmp instruction!");
4390     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4391       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4392       InsertNewInstBefore(Xor, I);
4393       return BinaryOperator::createNot(Xor);
4394     }
4395     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4396       return BinaryOperator::createXor(Op0, Op1);
4397
4398     case ICmpInst::ICMP_UGT:
4399     case ICmpInst::ICMP_SGT:
4400       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4401       // FALL THROUGH
4402     case ICmpInst::ICMP_ULT:
4403     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4404       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4405       InsertNewInstBefore(Not, I);
4406       return BinaryOperator::createAnd(Not, Op1);
4407     }
4408     case ICmpInst::ICMP_UGE:
4409     case ICmpInst::ICMP_SGE:
4410       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4411       // FALL THROUGH
4412     case ICmpInst::ICMP_ULE:
4413     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4414       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4415       InsertNewInstBefore(Not, I);
4416       return BinaryOperator::createOr(Not, Op1);
4417     }
4418     }
4419   }
4420
4421   // See if we are doing a comparison between a constant and an instruction that
4422   // can be folded into the comparison.
4423   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4424     switch (I.getPredicate()) {
4425     default: break;
4426     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4427       if (CI->isMinValue(false))
4428         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4429       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4430         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4431       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4432         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4433       break;
4434
4435     case ICmpInst::ICMP_SLT:
4436       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4437         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4438       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4439         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4440       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4441         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4442       break;
4443
4444     case ICmpInst::ICMP_UGT:
4445       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4446         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4447       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4448         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4449       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4450         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4451       break;
4452
4453     case ICmpInst::ICMP_SGT:
4454       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4455         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4456       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4457         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4458       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4459         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4460       break;
4461
4462     case ICmpInst::ICMP_ULE:
4463       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4464         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4465       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4466         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4467       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4468         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4469       break;
4470
4471     case ICmpInst::ICMP_SLE:
4472       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4473         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4474       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4475         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4476       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4477         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4478       break;
4479
4480     case ICmpInst::ICMP_UGE:
4481       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4482         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4483       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4484         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4485       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4486         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4487       break;
4488
4489     case ICmpInst::ICMP_SGE:
4490       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4491         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4492       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4493         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4494       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4495         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4496       break;
4497     }
4498
4499     // If we still have a icmp le or icmp ge instruction, turn it into the
4500     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4501     // already been handled above, this requires little checking.
4502     //
4503     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4504       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4505     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4506       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4507     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4508       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4509     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4510       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4511     
4512     // See if we can fold the comparison based on bits known to be zero or one
4513     // in the input.
4514     uint64_t KnownZero, KnownOne;
4515     if (SimplifyDemandedBits(Op0, Ty->getIntegerTypeMask(),
4516                              KnownZero, KnownOne, 0))
4517       return &I;
4518         
4519     // Given the known and unknown bits, compute a range that the LHS could be
4520     // in.
4521     if (KnownOne | KnownZero) {
4522       // Compute the Min, Max and RHS values based on the known bits. For the
4523       // EQ and NE we use unsigned values.
4524       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4525       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4526       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4527         SRHSVal = CI->getSExtValue();
4528         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4529                                                SMax);
4530       } else {
4531         URHSVal = CI->getZExtValue();
4532         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4533                                                  UMax);
4534       }
4535       switch (I.getPredicate()) {  // LE/GE have been folded already.
4536       default: assert(0 && "Unknown icmp opcode!");
4537       case ICmpInst::ICMP_EQ:
4538         if (UMax < URHSVal || UMin > URHSVal)
4539           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4540         break;
4541       case ICmpInst::ICMP_NE:
4542         if (UMax < URHSVal || UMin > URHSVal)
4543           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4544         break;
4545       case ICmpInst::ICMP_ULT:
4546         if (UMax < URHSVal)
4547           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4548         if (UMin > URHSVal)
4549           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4550         break;
4551       case ICmpInst::ICMP_UGT:
4552         if (UMin > URHSVal)
4553           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4554         if (UMax < URHSVal)
4555           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4556         break;
4557       case ICmpInst::ICMP_SLT:
4558         if (SMax < SRHSVal)
4559           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4560         if (SMin > SRHSVal)
4561           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4562         break;
4563       case ICmpInst::ICMP_SGT: 
4564         if (SMin > SRHSVal)
4565           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4566         if (SMax < SRHSVal)
4567           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4568         break;
4569       }
4570     }
4571           
4572     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4573     // instruction, see if that instruction also has constants so that the 
4574     // instruction can be folded into the icmp 
4575     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4576       switch (LHSI->getOpcode()) {
4577       case Instruction::And:
4578         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4579             LHSI->getOperand(0)->hasOneUse()) {
4580           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4581
4582           // If the LHS is an AND of a truncating cast, we can widen the
4583           // and/compare to be the input width without changing the value
4584           // produced, eliminating a cast.
4585           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4586             // We can do this transformation if either the AND constant does not
4587             // have its sign bit set or if it is an equality comparison. 
4588             // Extending a relational comparison when we're checking the sign
4589             // bit would not work.
4590             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4591                 (I.isEquality() ||
4592                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4593                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4594               ConstantInt *NewCST;
4595               ConstantInt *NewCI;
4596               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4597                                          AndCST->getZExtValue());
4598               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4599                                         CI->getZExtValue());
4600               Instruction *NewAnd = 
4601                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4602                                           LHSI->getName());
4603               InsertNewInstBefore(NewAnd, I);
4604               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4605             }
4606           }
4607           
4608           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4609           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4610           // happens a LOT in code produced by the C front-end, for bitfield
4611           // access.
4612           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4613
4614           // Check to see if there is a noop-cast between the shift and the and.
4615           if (!Shift) {
4616             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4617               if (CI->getOpcode() == Instruction::BitCast)
4618                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4619           }
4620
4621           ConstantInt *ShAmt;
4622           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4623           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4624           const Type *AndTy = AndCST->getType();          // Type of the and.
4625
4626           // We can fold this as long as we can't shift unknown bits
4627           // into the mask.  This can only happen with signed shift
4628           // rights, as they sign-extend.
4629           if (ShAmt) {
4630             bool CanFold = Shift->isLogicalShift();
4631             if (!CanFold) {
4632               // To test for the bad case of the signed shr, see if any
4633               // of the bits shifted in could be tested after the mask.
4634               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4635               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4636
4637               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4638               Constant *ShVal =
4639                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4640                                      OShAmt);
4641               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4642                 CanFold = true;
4643             }
4644
4645             if (CanFold) {
4646               Constant *NewCst;
4647               if (Shift->getOpcode() == Instruction::Shl)
4648                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4649               else
4650                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4651
4652               // Check to see if we are shifting out any of the bits being
4653               // compared.
4654               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4655                 // If we shifted bits out, the fold is not going to work out.
4656                 // As a special case, check to see if this means that the
4657                 // result is always true or false now.
4658                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4659                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4660                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4661                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4662               } else {
4663                 I.setOperand(1, NewCst);
4664                 Constant *NewAndCST;
4665                 if (Shift->getOpcode() == Instruction::Shl)
4666                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4667                 else
4668                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4669                 LHSI->setOperand(1, NewAndCST);
4670                 LHSI->setOperand(0, Shift->getOperand(0));
4671                 WorkList.push_back(Shift); // Shift is dead.
4672                 AddUsesToWorkList(I);
4673                 return &I;
4674               }
4675             }
4676           }
4677           
4678           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4679           // preferable because it allows the C<<Y expression to be hoisted out
4680           // of a loop if Y is invariant and X is not.
4681           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4682               I.isEquality() && !Shift->isArithmeticShift() &&
4683               isa<Instruction>(Shift->getOperand(0))) {
4684             // Compute C << Y.
4685             Value *NS;
4686             if (Shift->getOpcode() == Instruction::LShr) {
4687               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4688                                  "tmp");
4689             } else {
4690               // Insert a logical shift.
4691               NS = new ShiftInst(Instruction::LShr, AndCST,
4692                                  Shift->getOperand(1), "tmp");
4693             }
4694             InsertNewInstBefore(cast<Instruction>(NS), I);
4695
4696             // Compute X & (C << Y).
4697             Instruction *NewAnd = BinaryOperator::createAnd(
4698                 Shift->getOperand(0), NS, LHSI->getName());
4699             InsertNewInstBefore(NewAnd, I);
4700             
4701             I.setOperand(0, NewAnd);
4702             return &I;
4703           }
4704         }
4705         break;
4706
4707       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4708         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4709           if (I.isEquality()) {
4710             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4711
4712             // Check that the shift amount is in range.  If not, don't perform
4713             // undefined shifts.  When the shift is visited it will be
4714             // simplified.
4715             if (ShAmt->getZExtValue() >= TypeBits)
4716               break;
4717
4718             // If we are comparing against bits always shifted out, the
4719             // comparison cannot succeed.
4720             Constant *Comp =
4721               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4722             if (Comp != CI) {// Comparing against a bit that we know is zero.
4723               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4724               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4725               return ReplaceInstUsesWith(I, Cst);
4726             }
4727
4728             if (LHSI->hasOneUse()) {
4729               // Otherwise strength reduce the shift into an and.
4730               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4731               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4732               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4733
4734               Instruction *AndI =
4735                 BinaryOperator::createAnd(LHSI->getOperand(0),
4736                                           Mask, LHSI->getName()+".mask");
4737               Value *And = InsertNewInstBefore(AndI, I);
4738               return new ICmpInst(I.getPredicate(), And,
4739                                      ConstantExpr::getLShr(CI, ShAmt));
4740             }
4741           }
4742         }
4743         break;
4744
4745       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4746       case Instruction::AShr:
4747         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4748           if (I.isEquality()) {
4749             // Check that the shift amount is in range.  If not, don't perform
4750             // undefined shifts.  When the shift is visited it will be
4751             // simplified.
4752             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4753             if (ShAmt->getZExtValue() >= TypeBits)
4754               break;
4755
4756             // If we are comparing against bits always shifted out, the
4757             // comparison cannot succeed.
4758             Constant *Comp;
4759             if (LHSI->getOpcode() == Instruction::LShr) 
4760               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4761                                            ShAmt);
4762             else
4763               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4764                                            ShAmt);
4765
4766             if (Comp != CI) {// Comparing against a bit that we know is zero.
4767               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4768               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4769               return ReplaceInstUsesWith(I, Cst);
4770             }
4771
4772             if (LHSI->hasOneUse() || CI->isNullValue()) {
4773               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4774
4775               // Otherwise strength reduce the shift into an and.
4776               uint64_t Val = ~0ULL;          // All ones.
4777               Val <<= ShAmtVal;              // Shift over to the right spot.
4778               Val &= ~0ULL >> (64-TypeBits);
4779               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4780
4781               Instruction *AndI =
4782                 BinaryOperator::createAnd(LHSI->getOperand(0),
4783                                           Mask, LHSI->getName()+".mask");
4784               Value *And = InsertNewInstBefore(AndI, I);
4785               return new ICmpInst(I.getPredicate(), And,
4786                                      ConstantExpr::getShl(CI, ShAmt));
4787             }
4788           }
4789         }
4790         break;
4791
4792       case Instruction::SDiv:
4793       case Instruction::UDiv:
4794         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4795         // Fold this div into the comparison, producing a range check. 
4796         // Determine, based on the divide type, what the range is being 
4797         // checked.  If there is an overflow on the low or high side, remember 
4798         // it, otherwise compute the range [low, hi) bounding the new value.
4799         // See: InsertRangeTest above for the kinds of replacements possible.
4800         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4801           // FIXME: If the operand types don't match the type of the divide 
4802           // then don't attempt this transform. The code below doesn't have the
4803           // logic to deal with a signed divide and an unsigned compare (and
4804           // vice versa). This is because (x /s C1) <s C2  produces different 
4805           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4806           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4807           // work. :(  The if statement below tests that condition and bails 
4808           // if it finds it. 
4809           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4810           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4811             break;
4812
4813           // Initialize the variables that will indicate the nature of the
4814           // range check.
4815           bool LoOverflow = false, HiOverflow = false;
4816           ConstantInt *LoBound = 0, *HiBound = 0;
4817
4818           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4819           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4820           // C2 (CI). By solving for X we can turn this into a range check 
4821           // instead of computing a divide. 
4822           ConstantInt *Prod = 
4823             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4824
4825           // Determine if the product overflows by seeing if the product is
4826           // not equal to the divide. Make sure we do the same kind of divide
4827           // as in the LHS instruction that we're folding. 
4828           bool ProdOV = !DivRHS->isNullValue() && 
4829             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4830               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4831
4832           // Get the ICmp opcode
4833           ICmpInst::Predicate predicate = I.getPredicate();
4834
4835           if (DivRHS->isNullValue()) {  
4836             // Don't hack on divide by zeros!
4837           } else if (!DivIsSigned) {  // udiv
4838             LoBound = Prod;
4839             LoOverflow = ProdOV;
4840             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4841           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4842             if (CI->isNullValue()) {       // (X / pos) op 0
4843               // Can't overflow.
4844               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4845               HiBound = DivRHS;
4846             } else if (isPositive(CI)) {   // (X / pos) op pos
4847               LoBound = Prod;
4848               LoOverflow = ProdOV;
4849               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4850             } else {                       // (X / pos) op neg
4851               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4852               LoOverflow = AddWithOverflow(LoBound, Prod,
4853                                            cast<ConstantInt>(DivRHSH));
4854               HiBound = Prod;
4855               HiOverflow = ProdOV;
4856             }
4857           } else {                         // Divisor is < 0.
4858             if (CI->isNullValue()) {       // (X / neg) op 0
4859               LoBound = AddOne(DivRHS);
4860               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4861               if (HiBound == DivRHS)
4862                 LoBound = 0;               // - INTMIN = INTMIN
4863             } else if (isPositive(CI)) {   // (X / neg) op pos
4864               HiOverflow = LoOverflow = ProdOV;
4865               if (!LoOverflow)
4866                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4867               HiBound = AddOne(Prod);
4868             } else {                       // (X / neg) op neg
4869               LoBound = Prod;
4870               LoOverflow = HiOverflow = ProdOV;
4871               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4872             }
4873
4874             // Dividing by a negate swaps the condition.
4875             predicate = ICmpInst::getSwappedPredicate(predicate);
4876           }
4877
4878           if (LoBound) {
4879             Value *X = LHSI->getOperand(0);
4880             switch (predicate) {
4881             default: assert(0 && "Unhandled icmp opcode!");
4882             case ICmpInst::ICMP_EQ:
4883               if (LoOverflow && HiOverflow)
4884                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4885               else if (HiOverflow)
4886                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4887                                     ICmpInst::ICMP_UGE, X, LoBound);
4888               else if (LoOverflow)
4889                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4890                                     ICmpInst::ICMP_ULT, X, HiBound);
4891               else
4892                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4893                                        true, I);
4894             case ICmpInst::ICMP_NE:
4895               if (LoOverflow && HiOverflow)
4896                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4897               else if (HiOverflow)
4898                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4899                                     ICmpInst::ICMP_ULT, X, LoBound);
4900               else if (LoOverflow)
4901                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4902                                     ICmpInst::ICMP_UGE, X, HiBound);
4903               else
4904                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4905                                        false, I);
4906             case ICmpInst::ICMP_ULT:
4907             case ICmpInst::ICMP_SLT:
4908               if (LoOverflow)
4909                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4910               return new ICmpInst(predicate, X, LoBound);
4911             case ICmpInst::ICMP_UGT:
4912             case ICmpInst::ICMP_SGT:
4913               if (HiOverflow)
4914                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4915               if (predicate == ICmpInst::ICMP_UGT)
4916                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4917               else
4918                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4919             }
4920           }
4921         }
4922         break;
4923       }
4924
4925     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4926     if (I.isEquality()) {
4927       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4928
4929       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4930       // the second operand is a constant, simplify a bit.
4931       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4932         switch (BO->getOpcode()) {
4933         case Instruction::SRem:
4934           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4935           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4936               BO->hasOneUse()) {
4937             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4938             if (V > 1 && isPowerOf2_64(V)) {
4939               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4940                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4941               return new ICmpInst(I.getPredicate(), NewRem, 
4942                                   Constant::getNullValue(BO->getType()));
4943             }
4944           }
4945           break;
4946         case Instruction::Add:
4947           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4948           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4949             if (BO->hasOneUse())
4950               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4951                                   ConstantExpr::getSub(CI, BOp1C));
4952           } else if (CI->isNullValue()) {
4953             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4954             // efficiently invertible, or if the add has just this one use.
4955             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4956
4957             if (Value *NegVal = dyn_castNegVal(BOp1))
4958               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4959             else if (Value *NegVal = dyn_castNegVal(BOp0))
4960               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4961             else if (BO->hasOneUse()) {
4962               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4963               BO->setName("");
4964               InsertNewInstBefore(Neg, I);
4965               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4966             }
4967           }
4968           break;
4969         case Instruction::Xor:
4970           // For the xor case, we can xor two constants together, eliminating
4971           // the explicit xor.
4972           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4973             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4974                                 ConstantExpr::getXor(CI, BOC));
4975
4976           // FALLTHROUGH
4977         case Instruction::Sub:
4978           // Replace (([sub|xor] A, B) != 0) with (A != B)
4979           if (CI->isNullValue())
4980             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4981                                 BO->getOperand(1));
4982           break;
4983
4984         case Instruction::Or:
4985           // If bits are being or'd in that are not present in the constant we
4986           // are comparing against, then the comparison could never succeed!
4987           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4988             Constant *NotCI = ConstantExpr::getNot(CI);
4989             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4990               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4991                                                              isICMP_NE));
4992           }
4993           break;
4994
4995         case Instruction::And:
4996           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4997             // If bits are being compared against that are and'd out, then the
4998             // comparison can never succeed!
4999             if (!ConstantExpr::getAnd(CI,
5000                                       ConstantExpr::getNot(BOC))->isNullValue())
5001               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5002                                                              isICMP_NE));
5003
5004             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5005             if (CI == BOC && isOneBitSet(CI))
5006               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5007                                   ICmpInst::ICMP_NE, Op0,
5008                                   Constant::getNullValue(CI->getType()));
5009
5010             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5011             if (isSignBit(BOC)) {
5012               Value *X = BO->getOperand(0);
5013               Constant *Zero = Constant::getNullValue(X->getType());
5014               ICmpInst::Predicate pred = isICMP_NE ? 
5015                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5016               return new ICmpInst(pred, X, Zero);
5017             }
5018
5019             // ((X & ~7) == 0) --> X < 8
5020             if (CI->isNullValue() && isHighOnes(BOC)) {
5021               Value *X = BO->getOperand(0);
5022               Constant *NegX = ConstantExpr::getNeg(BOC);
5023               ICmpInst::Predicate pred = isICMP_NE ? 
5024                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5025               return new ICmpInst(pred, X, NegX);
5026             }
5027
5028           }
5029         default: break;
5030         }
5031       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5032         // Handle set{eq|ne} <intrinsic>, intcst.
5033         switch (II->getIntrinsicID()) {
5034         default: break;
5035         case Intrinsic::bswap_i16: 
5036           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5037           WorkList.push_back(II);  // Dead?
5038           I.setOperand(0, II->getOperand(1));
5039           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5040                                            ByteSwap_16(CI->getZExtValue())));
5041           return &I;
5042         case Intrinsic::bswap_i32:   
5043           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5044           WorkList.push_back(II);  // Dead?
5045           I.setOperand(0, II->getOperand(1));
5046           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5047                                            ByteSwap_32(CI->getZExtValue())));
5048           return &I;
5049         case Intrinsic::bswap_i64:   
5050           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5051           WorkList.push_back(II);  // Dead?
5052           I.setOperand(0, II->getOperand(1));
5053           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5054                                            ByteSwap_64(CI->getZExtValue())));
5055           return &I;
5056         }
5057       }
5058     } else {  // Not a ICMP_EQ/ICMP_NE
5059       // If the LHS is a cast from an integral value of the same size, then 
5060       // since we know the RHS is a constant, try to simlify.
5061       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5062         Value *CastOp = Cast->getOperand(0);
5063         const Type *SrcTy = CastOp->getType();
5064         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5065         if (SrcTy->isInteger() && 
5066             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5067           // If this is an unsigned comparison, try to make the comparison use
5068           // smaller constant values.
5069           switch (I.getPredicate()) {
5070             default: break;
5071             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5072               ConstantInt *CUI = cast<ConstantInt>(CI);
5073               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5074                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5075                                     ConstantInt::get(SrcTy, -1));
5076               break;
5077             }
5078             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5079               ConstantInt *CUI = cast<ConstantInt>(CI);
5080               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5081                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5082                                     Constant::getNullValue(SrcTy));
5083               break;
5084             }
5085           }
5086
5087         }
5088       }
5089     }
5090   }
5091
5092   // Handle icmp with constant RHS
5093   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5094     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5095       switch (LHSI->getOpcode()) {
5096       case Instruction::GetElementPtr:
5097         if (RHSC->isNullValue()) {
5098           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5099           bool isAllZeros = true;
5100           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5101             if (!isa<Constant>(LHSI->getOperand(i)) ||
5102                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5103               isAllZeros = false;
5104               break;
5105             }
5106           if (isAllZeros)
5107             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5108                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5109         }
5110         break;
5111
5112       case Instruction::PHI:
5113         if (Instruction *NV = FoldOpIntoPhi(I))
5114           return NV;
5115         break;
5116       case Instruction::Select:
5117         // If either operand of the select is a constant, we can fold the
5118         // comparison into the select arms, which will cause one to be
5119         // constant folded and the select turned into a bitwise or.
5120         Value *Op1 = 0, *Op2 = 0;
5121         if (LHSI->hasOneUse()) {
5122           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5123             // Fold the known value into the constant operand.
5124             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5125             // Insert a new ICmp of the other select operand.
5126             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5127                                                    LHSI->getOperand(2), RHSC,
5128                                                    I.getName()), I);
5129           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5130             // Fold the known value into the constant operand.
5131             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5132             // Insert a new ICmp of the other select operand.
5133             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5134                                                    LHSI->getOperand(1), RHSC,
5135                                                    I.getName()), I);
5136           }
5137         }
5138
5139         if (Op1)
5140           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5141         break;
5142       }
5143   }
5144
5145   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5146   if (User *GEP = dyn_castGetElementPtr(Op0))
5147     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5148       return NI;
5149   if (User *GEP = dyn_castGetElementPtr(Op1))
5150     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5151                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5152       return NI;
5153
5154   // Test to see if the operands of the icmp are casted versions of other
5155   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5156   // now.
5157   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5158     if (isa<PointerType>(Op0->getType()) && 
5159         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5160       // We keep moving the cast from the left operand over to the right
5161       // operand, where it can often be eliminated completely.
5162       Op0 = CI->getOperand(0);
5163
5164       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5165       // so eliminate it as well.
5166       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5167         Op1 = CI2->getOperand(0);
5168
5169       // If Op1 is a constant, we can fold the cast into the constant.
5170       if (Op0->getType() != Op1->getType())
5171         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5172           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5173         } else {
5174           // Otherwise, cast the RHS right before the icmp
5175           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5176         }
5177       return new ICmpInst(I.getPredicate(), Op0, Op1);
5178     }
5179   }
5180   
5181   if (isa<CastInst>(Op0)) {
5182     // Handle the special case of: icmp (cast bool to X), <cst>
5183     // This comes up when you have code like
5184     //   int X = A < B;
5185     //   if (X) ...
5186     // For generality, we handle any zero-extension of any operand comparison
5187     // with a constant or another cast from the same type.
5188     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5189       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5190         return R;
5191   }
5192   
5193   if (I.isEquality()) {
5194     Value *A, *B, *C, *D;
5195     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5196       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5197         Value *OtherVal = A == Op1 ? B : A;
5198         return new ICmpInst(I.getPredicate(), OtherVal,
5199                             Constant::getNullValue(A->getType()));
5200       }
5201
5202       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5203         // A^c1 == C^c2 --> A == C^(c1^c2)
5204         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5205           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5206             if (Op1->hasOneUse()) {
5207               Constant *NC = ConstantExpr::getXor(C1, C2);
5208               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5209               return new ICmpInst(I.getPredicate(), A,
5210                                   InsertNewInstBefore(Xor, I));
5211             }
5212         
5213         // A^B == A^D -> B == D
5214         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5215         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5216         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5217         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5218       }
5219     }
5220     
5221     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5222         (A == Op0 || B == Op0)) {
5223       // A == (A^B)  ->  B == 0
5224       Value *OtherVal = A == Op0 ? B : A;
5225       return new ICmpInst(I.getPredicate(), OtherVal,
5226                           Constant::getNullValue(A->getType()));
5227     }
5228     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5229       // (A-B) == A  ->  B == 0
5230       return new ICmpInst(I.getPredicate(), B,
5231                           Constant::getNullValue(B->getType()));
5232     }
5233     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5234       // A == (A-B)  ->  B == 0
5235       return new ICmpInst(I.getPredicate(), B,
5236                           Constant::getNullValue(B->getType()));
5237     }
5238     
5239     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5240     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5241         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5242         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5243       Value *X = 0, *Y = 0, *Z = 0;
5244       
5245       if (A == C) {
5246         X = B; Y = D; Z = A;
5247       } else if (A == D) {
5248         X = B; Y = C; Z = A;
5249       } else if (B == C) {
5250         X = A; Y = D; Z = B;
5251       } else if (B == D) {
5252         X = A; Y = C; Z = B;
5253       }
5254       
5255       if (X) {   // Build (X^Y) & Z
5256         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5257         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5258         I.setOperand(0, Op1);
5259         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5260         return &I;
5261       }
5262     }
5263   }
5264   return Changed ? &I : 0;
5265 }
5266
5267 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5268 // We only handle extending casts so far.
5269 //
5270 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5271   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5272   Value *LHSCIOp        = LHSCI->getOperand(0);
5273   const Type *SrcTy     = LHSCIOp->getType();
5274   const Type *DestTy    = LHSCI->getType();
5275   Value *RHSCIOp;
5276
5277   // We only handle extension cast instructions, so far. Enforce this.
5278   if (LHSCI->getOpcode() != Instruction::ZExt &&
5279       LHSCI->getOpcode() != Instruction::SExt)
5280     return 0;
5281
5282   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5283   bool isSignedCmp = ICI.isSignedPredicate();
5284
5285   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5286     // Not an extension from the same type?
5287     RHSCIOp = CI->getOperand(0);
5288     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5289       return 0;
5290     
5291     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5292     // and the other is a zext), then we can't handle this.
5293     if (CI->getOpcode() != LHSCI->getOpcode())
5294       return 0;
5295
5296     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5297     // then we can't handle this.
5298     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5299       return 0;
5300     
5301     // Okay, just insert a compare of the reduced operands now!
5302     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5303   }
5304
5305   // If we aren't dealing with a constant on the RHS, exit early
5306   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5307   if (!CI)
5308     return 0;
5309
5310   // Compute the constant that would happen if we truncated to SrcTy then
5311   // reextended to DestTy.
5312   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5313   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5314
5315   // If the re-extended constant didn't change...
5316   if (Res2 == CI) {
5317     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5318     // For example, we might have:
5319     //    %A = sext short %X to uint
5320     //    %B = icmp ugt uint %A, 1330
5321     // It is incorrect to transform this into 
5322     //    %B = icmp ugt short %X, 1330 
5323     // because %A may have negative value. 
5324     //
5325     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5326     // OR operation is EQ/NE.
5327     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5328       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5329     else
5330       return 0;
5331   }
5332
5333   // The re-extended constant changed so the constant cannot be represented 
5334   // in the shorter type. Consequently, we cannot emit a simple comparison.
5335
5336   // First, handle some easy cases. We know the result cannot be equal at this
5337   // point so handle the ICI.isEquality() cases
5338   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5339     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5340   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5341     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5342
5343   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5344   // should have been folded away previously and not enter in here.
5345   Value *Result;
5346   if (isSignedCmp) {
5347     // We're performing a signed comparison.
5348     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5349       Result = ConstantInt::getFalse();          // X < (small) --> false
5350     else
5351       Result = ConstantInt::getTrue();           // X < (large) --> true
5352   } else {
5353     // We're performing an unsigned comparison.
5354     if (isSignedExt) {
5355       // We're performing an unsigned comp with a sign extended value.
5356       // This is true if the input is >= 0. [aka >s -1]
5357       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5358       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5359                                    NegOne, ICI.getName()), ICI);
5360     } else {
5361       // Unsigned extend & unsigned compare -> always true.
5362       Result = ConstantInt::getTrue();
5363     }
5364   }
5365
5366   // Finally, return the value computed.
5367   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5368       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5369     return ReplaceInstUsesWith(ICI, Result);
5370   } else {
5371     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5372             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5373            "ICmp should be folded!");
5374     if (Constant *CI = dyn_cast<Constant>(Result))
5375       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5376     else
5377       return BinaryOperator::createNot(Result);
5378   }
5379 }
5380
5381 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5382   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5383   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5384
5385   // shl X, 0 == X and shr X, 0 == X
5386   // shl 0, X == 0 and shr 0, X == 0
5387   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5388       Op0 == Constant::getNullValue(Op0->getType()))
5389     return ReplaceInstUsesWith(I, Op0);
5390   
5391   if (isa<UndefValue>(Op0)) {            
5392     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5393       return ReplaceInstUsesWith(I, Op0);
5394     else                                    // undef << X -> 0, undef >>u X -> 0
5395       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5396   }
5397   if (isa<UndefValue>(Op1)) {
5398     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5399       return ReplaceInstUsesWith(I, Op0);          
5400     else                                     // X << undef, X >>u undef -> 0
5401       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5402   }
5403
5404   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5405   if (I.getOpcode() == Instruction::AShr)
5406     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5407       if (CSI->isAllOnesValue())
5408         return ReplaceInstUsesWith(I, CSI);
5409
5410   // Try to fold constant and into select arguments.
5411   if (isa<Constant>(Op0))
5412     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5413       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5414         return R;
5415
5416   // See if we can turn a signed shr into an unsigned shr.
5417   if (I.isArithmeticShift()) {
5418     if (MaskedValueIsZero(Op0,
5419                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5420       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5421     }
5422   }
5423
5424   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5425     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5426       return Res;
5427   return 0;
5428 }
5429
5430 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5431                                                ShiftInst &I) {
5432   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5433   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5434   bool isUnsignedShift = !isSignedShift;
5435
5436   // See if we can simplify any instructions used by the instruction whose sole 
5437   // purpose is to compute bits we don't care about.
5438   uint64_t KnownZero, KnownOne;
5439   if (SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
5440                            KnownZero, KnownOne))
5441     return &I;
5442   
5443   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5444   // of a signed value.
5445   //
5446   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5447   if (Op1->getZExtValue() >= TypeBits) {
5448     if (isUnsignedShift || isLeftShift)
5449       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5450     else {
5451       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5452       return &I;
5453     }
5454   }
5455   
5456   // ((X*C1) << C2) == (X * (C1 << C2))
5457   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5458     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5459       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5460         return BinaryOperator::createMul(BO->getOperand(0),
5461                                          ConstantExpr::getShl(BOOp, Op1));
5462   
5463   // Try to fold constant and into select arguments.
5464   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5465     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5466       return R;
5467   if (isa<PHINode>(Op0))
5468     if (Instruction *NV = FoldOpIntoPhi(I))
5469       return NV;
5470   
5471   if (Op0->hasOneUse()) {
5472     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5473       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5474       Value *V1, *V2;
5475       ConstantInt *CC;
5476       switch (Op0BO->getOpcode()) {
5477         default: break;
5478         case Instruction::Add:
5479         case Instruction::And:
5480         case Instruction::Or:
5481         case Instruction::Xor:
5482           // These operators commute.
5483           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5484           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5485               match(Op0BO->getOperand(1),
5486                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5487             Instruction *YS = new ShiftInst(Instruction::Shl, 
5488                                             Op0BO->getOperand(0), Op1,
5489                                             Op0BO->getName());
5490             InsertNewInstBefore(YS, I); // (Y << C)
5491             Instruction *X = 
5492               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5493                                      Op0BO->getOperand(1)->getName());
5494             InsertNewInstBefore(X, I);  // (X + (Y << C))
5495             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5496             C2 = ConstantExpr::getShl(C2, Op1);
5497             return BinaryOperator::createAnd(X, C2);
5498           }
5499           
5500           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5501           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5502               match(Op0BO->getOperand(1),
5503                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5504                           m_ConstantInt(CC))) && V2 == Op1 &&
5505       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5506             Instruction *YS = new ShiftInst(Instruction::Shl, 
5507                                             Op0BO->getOperand(0), Op1,
5508                                             Op0BO->getName());
5509             InsertNewInstBefore(YS, I); // (Y << C)
5510             Instruction *XM =
5511               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5512                                         V1->getName()+".mask");
5513             InsertNewInstBefore(XM, I); // X & (CC << C)
5514             
5515             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5516           }
5517           
5518           // FALL THROUGH.
5519         case Instruction::Sub:
5520           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5521           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5522               match(Op0BO->getOperand(0),
5523                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5524             Instruction *YS = new ShiftInst(Instruction::Shl, 
5525                                             Op0BO->getOperand(1), Op1,
5526                                             Op0BO->getName());
5527             InsertNewInstBefore(YS, I); // (Y << C)
5528             Instruction *X =
5529               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5530                                      Op0BO->getOperand(0)->getName());
5531             InsertNewInstBefore(X, I);  // (X + (Y << C))
5532             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5533             C2 = ConstantExpr::getShl(C2, Op1);
5534             return BinaryOperator::createAnd(X, C2);
5535           }
5536           
5537           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5538           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5539               match(Op0BO->getOperand(0),
5540                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5541                           m_ConstantInt(CC))) && V2 == Op1 &&
5542               cast<BinaryOperator>(Op0BO->getOperand(0))
5543                   ->getOperand(0)->hasOneUse()) {
5544             Instruction *YS = new ShiftInst(Instruction::Shl, 
5545                                             Op0BO->getOperand(1), Op1,
5546                                             Op0BO->getName());
5547             InsertNewInstBefore(YS, I); // (Y << C)
5548             Instruction *XM =
5549               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5550                                         V1->getName()+".mask");
5551             InsertNewInstBefore(XM, I); // X & (CC << C)
5552             
5553             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5554           }
5555           
5556           break;
5557       }
5558       
5559       
5560       // If the operand is an bitwise operator with a constant RHS, and the
5561       // shift is the only use, we can pull it out of the shift.
5562       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5563         bool isValid = true;     // Valid only for And, Or, Xor
5564         bool highBitSet = false; // Transform if high bit of constant set?
5565         
5566         switch (Op0BO->getOpcode()) {
5567           default: isValid = false; break;   // Do not perform transform!
5568           case Instruction::Add:
5569             isValid = isLeftShift;
5570             break;
5571           case Instruction::Or:
5572           case Instruction::Xor:
5573             highBitSet = false;
5574             break;
5575           case Instruction::And:
5576             highBitSet = true;
5577             break;
5578         }
5579         
5580         // If this is a signed shift right, and the high bit is modified
5581         // by the logical operation, do not perform the transformation.
5582         // The highBitSet boolean indicates the value of the high bit of
5583         // the constant which would cause it to be modified for this
5584         // operation.
5585         //
5586         if (isValid && !isLeftShift && isSignedShift) {
5587           uint64_t Val = Op0C->getZExtValue();
5588           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5589         }
5590         
5591         if (isValid) {
5592           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5593           
5594           Instruction *NewShift =
5595             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5596                           Op0BO->getName());
5597           Op0BO->setName("");
5598           InsertNewInstBefore(NewShift, I);
5599           
5600           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5601                                         NewRHS);
5602         }
5603       }
5604     }
5605   }
5606   
5607   // Find out if this is a shift of a shift by a constant.
5608   ShiftInst *ShiftOp = 0;
5609   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5610     ShiftOp = Op0SI;
5611   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5612     // If this is a noop-integer cast of a shift instruction, use the shift.
5613     if (isa<ShiftInst>(CI->getOperand(0))) {
5614       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5615     }
5616   }
5617   
5618   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5619     // Find the operands and properties of the input shift.  Note that the
5620     // signedness of the input shift may differ from the current shift if there
5621     // is a noop cast between the two.
5622     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5623     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5624     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5625     
5626     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5627
5628     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5629     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5630     
5631     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5632     if (isLeftShift == isShiftOfLeftShift) {
5633       // Do not fold these shifts if the first one is signed and the second one
5634       // is unsigned and this is a right shift.  Further, don't do any folding
5635       // on them.
5636       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5637         return 0;
5638       
5639       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5640       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5641         Amt = Op0->getType()->getPrimitiveSizeInBits();
5642       
5643       Value *Op = ShiftOp->getOperand(0);
5644       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5645                                           ConstantInt::get(Type::Int8Ty, Amt));
5646       if (I.getType() == ShiftResult->getType())
5647         return ShiftResult;
5648       InsertNewInstBefore(ShiftResult, I);
5649       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5650     }
5651     
5652     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5653     // signed types, we can only support the (A >> c1) << c2 configuration,
5654     // because it can not turn an arbitrary bit of A into a sign bit.
5655     if (isUnsignedShift || isLeftShift) {
5656       // Calculate bitmask for what gets shifted off the edge.
5657       Constant *C = ConstantInt::getAllOnesValue(I.getType());
5658       if (isLeftShift)
5659         C = ConstantExpr::getShl(C, ShiftAmt1C);
5660       else
5661         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5662       
5663       Value *Op = ShiftOp->getOperand(0);
5664       
5665       Instruction *Mask =
5666         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5667       InsertNewInstBefore(Mask, I);
5668       
5669       // Figure out what flavor of shift we should use...
5670       if (ShiftAmt1 == ShiftAmt2) {
5671         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5672       } else if (ShiftAmt1 < ShiftAmt2) {
5673         return new ShiftInst(I.getOpcode(), Mask,
5674                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5675       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5676         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5677           return new ShiftInst(Instruction::LShr, Mask, 
5678             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5679         } else {
5680           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5681                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5682         }
5683       } else {
5684         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5685         Instruction *Shift =
5686           new ShiftInst(ShiftOp->getOpcode(), Mask,
5687                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5688         InsertNewInstBefore(Shift, I);
5689         
5690         C = ConstantInt::getAllOnesValue(Shift->getType());
5691         C = ConstantExpr::getShl(C, Op1);
5692         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5693       }
5694     } else {
5695       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5696       // this case, C1 == C2 and C1 is 8, 16, or 32.
5697       if (ShiftAmt1 == ShiftAmt2) {
5698         const Type *SExtType = 0;
5699         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5700         case 8 : SExtType = Type::Int8Ty; break;
5701         case 16: SExtType = Type::Int16Ty; break;
5702         case 32: SExtType = Type::Int32Ty; break;
5703         }
5704         
5705         if (SExtType) {
5706           Instruction *NewTrunc = 
5707             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5708           InsertNewInstBefore(NewTrunc, I);
5709           return new SExtInst(NewTrunc, I.getType());
5710         }
5711       }
5712     }
5713   }
5714   return 0;
5715 }
5716
5717
5718 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5719 /// expression.  If so, decompose it, returning some value X, such that Val is
5720 /// X*Scale+Offset.
5721 ///
5722 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5723                                         unsigned &Offset) {
5724   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5725   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5726     Offset = CI->getZExtValue();
5727     Scale  = 1;
5728     return ConstantInt::get(Type::Int32Ty, 0);
5729   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5730     if (I->getNumOperands() == 2) {
5731       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5732         if (I->getOpcode() == Instruction::Shl) {
5733           // This is a value scaled by '1 << the shift amt'.
5734           Scale = 1U << CUI->getZExtValue();
5735           Offset = 0;
5736           return I->getOperand(0);
5737         } else if (I->getOpcode() == Instruction::Mul) {
5738           // This value is scaled by 'CUI'.
5739           Scale = CUI->getZExtValue();
5740           Offset = 0;
5741           return I->getOperand(0);
5742         } else if (I->getOpcode() == Instruction::Add) {
5743           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5744           // where C1 is divisible by C2.
5745           unsigned SubScale;
5746           Value *SubVal = 
5747             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5748           Offset += CUI->getZExtValue();
5749           if (SubScale > 1 && (Offset % SubScale == 0)) {
5750             Scale = SubScale;
5751             return SubVal;
5752           }
5753         }
5754       }
5755     }
5756   }
5757
5758   // Otherwise, we can't look past this.
5759   Scale = 1;
5760   Offset = 0;
5761   return Val;
5762 }
5763
5764
5765 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5766 /// try to eliminate the cast by moving the type information into the alloc.
5767 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5768                                                    AllocationInst &AI) {
5769   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5770   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5771   
5772   // Remove any uses of AI that are dead.
5773   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5774   std::vector<Instruction*> DeadUsers;
5775   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5776     Instruction *User = cast<Instruction>(*UI++);
5777     if (isInstructionTriviallyDead(User)) {
5778       while (UI != E && *UI == User)
5779         ++UI; // If this instruction uses AI more than once, don't break UI.
5780       
5781       // Add operands to the worklist.
5782       AddUsesToWorkList(*User);
5783       ++NumDeadInst;
5784       DOUT << "IC: DCE: " << *User;
5785       
5786       User->eraseFromParent();
5787       removeFromWorkList(User);
5788     }
5789   }
5790   
5791   // Get the type really allocated and the type casted to.
5792   const Type *AllocElTy = AI.getAllocatedType();
5793   const Type *CastElTy = PTy->getElementType();
5794   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5795
5796   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5797   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5798   if (CastElTyAlign < AllocElTyAlign) return 0;
5799
5800   // If the allocation has multiple uses, only promote it if we are strictly
5801   // increasing the alignment of the resultant allocation.  If we keep it the
5802   // same, we open the door to infinite loops of various kinds.
5803   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5804
5805   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5806   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5807   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5808
5809   // See if we can satisfy the modulus by pulling a scale out of the array
5810   // size argument.
5811   unsigned ArraySizeScale, ArrayOffset;
5812   Value *NumElements = // See if the array size is a decomposable linear expr.
5813     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5814  
5815   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5816   // do the xform.
5817   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5818       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5819
5820   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5821   Value *Amt = 0;
5822   if (Scale == 1) {
5823     Amt = NumElements;
5824   } else {
5825     // If the allocation size is constant, form a constant mul expression
5826     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5827     if (isa<ConstantInt>(NumElements))
5828       Amt = ConstantExpr::getMul(
5829               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5830     // otherwise multiply the amount and the number of elements
5831     else if (Scale != 1) {
5832       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5833       Amt = InsertNewInstBefore(Tmp, AI);
5834     }
5835   }
5836   
5837   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5838     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5839     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5840     Amt = InsertNewInstBefore(Tmp, AI);
5841   }
5842   
5843   std::string Name = AI.getName(); AI.setName("");
5844   AllocationInst *New;
5845   if (isa<MallocInst>(AI))
5846     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5847   else
5848     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5849   InsertNewInstBefore(New, AI);
5850   
5851   // If the allocation has multiple uses, insert a cast and change all things
5852   // that used it to use the new cast.  This will also hack on CI, but it will
5853   // die soon.
5854   if (!AI.hasOneUse()) {
5855     AddUsesToWorkList(AI);
5856     // New is the allocation instruction, pointer typed. AI is the original
5857     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5858     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5859     InsertNewInstBefore(NewCast, AI);
5860     AI.replaceAllUsesWith(NewCast);
5861   }
5862   return ReplaceInstUsesWith(CI, New);
5863 }
5864
5865 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5866 /// and return it without inserting any new casts.  This is used by code that
5867 /// tries to decide whether promoting or shrinking integer operations to wider
5868 /// or smaller types will allow us to eliminate a truncate or extend.
5869 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5870                                        int &NumCastsRemoved) {
5871   if (isa<Constant>(V)) return true;
5872   
5873   Instruction *I = dyn_cast<Instruction>(V);
5874   if (!I || !I->hasOneUse()) return false;
5875   
5876   switch (I->getOpcode()) {
5877   case Instruction::And:
5878   case Instruction::Or:
5879   case Instruction::Xor:
5880     // These operators can all arbitrarily be extended or truncated.
5881     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5882            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5883   case Instruction::AShr:
5884   case Instruction::LShr:
5885   case Instruction::Shl:
5886     // If this is just a bitcast changing the sign of the operation, we can
5887     // convert if the operand can be converted.
5888     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5889       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5890     break;
5891   case Instruction::Trunc:
5892   case Instruction::ZExt:
5893   case Instruction::SExt:
5894   case Instruction::BitCast:
5895     // If this is a cast from the destination type, we can trivially eliminate
5896     // it, and this will remove a cast overall.
5897     if (I->getOperand(0)->getType() == Ty) {
5898       // If the first operand is itself a cast, and is eliminable, do not count
5899       // this as an eliminable cast.  We would prefer to eliminate those two
5900       // casts first.
5901       if (isa<CastInst>(I->getOperand(0)))
5902         return true;
5903       
5904       ++NumCastsRemoved;
5905       return true;
5906     }
5907     break;
5908   default:
5909     // TODO: Can handle more cases here.
5910     break;
5911   }
5912   
5913   return false;
5914 }
5915
5916 /// EvaluateInDifferentType - Given an expression that 
5917 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5918 /// evaluate the expression.
5919 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5920                                              bool isSigned ) {
5921   if (Constant *C = dyn_cast<Constant>(V))
5922     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5923
5924   // Otherwise, it must be an instruction.
5925   Instruction *I = cast<Instruction>(V);
5926   Instruction *Res = 0;
5927   switch (I->getOpcode()) {
5928   case Instruction::And:
5929   case Instruction::Or:
5930   case Instruction::Xor: {
5931     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5932     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5933     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5934                                  LHS, RHS, I->getName());
5935     break;
5936   }
5937   case Instruction::AShr:
5938   case Instruction::LShr:
5939   case Instruction::Shl: {
5940     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5941     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5942                         I->getOperand(1), I->getName());
5943     break;
5944   }    
5945   case Instruction::Trunc:
5946   case Instruction::ZExt:
5947   case Instruction::SExt:
5948   case Instruction::BitCast:
5949     // If the source type of the cast is the type we're trying for then we can
5950     // just return the source. There's no need to insert it because its not new.
5951     if (I->getOperand(0)->getType() == Ty)
5952       return I->getOperand(0);
5953     
5954     // Some other kind of cast, which shouldn't happen, so just ..
5955     // FALL THROUGH
5956   default: 
5957     // TODO: Can handle more cases here.
5958     assert(0 && "Unreachable!");
5959     break;
5960   }
5961   
5962   return InsertNewInstBefore(Res, *I);
5963 }
5964
5965 /// @brief Implement the transforms common to all CastInst visitors.
5966 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5967   Value *Src = CI.getOperand(0);
5968
5969   // Casting undef to anything results in undef so might as just replace it and
5970   // get rid of the cast.
5971   if (isa<UndefValue>(Src))   // cast undef -> undef
5972     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5973
5974   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5975   // eliminate it now.
5976   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5977     if (Instruction::CastOps opc = 
5978         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5979       // The first cast (CSrc) is eliminable so we need to fix up or replace
5980       // the second cast (CI). CSrc will then have a good chance of being dead.
5981       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5982     }
5983   }
5984
5985   // If casting the result of a getelementptr instruction with no offset, turn
5986   // this into a cast of the original pointer!
5987   //
5988   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5989     bool AllZeroOperands = true;
5990     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5991       if (!isa<Constant>(GEP->getOperand(i)) ||
5992           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5993         AllZeroOperands = false;
5994         break;
5995       }
5996     if (AllZeroOperands) {
5997       // Changing the cast operand is usually not a good idea but it is safe
5998       // here because the pointer operand is being replaced with another 
5999       // pointer operand so the opcode doesn't need to change.
6000       CI.setOperand(0, GEP->getOperand(0));
6001       return &CI;
6002     }
6003   }
6004     
6005   // If we are casting a malloc or alloca to a pointer to a type of the same
6006   // size, rewrite the allocation instruction to allocate the "right" type.
6007   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6008     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6009       return V;
6010
6011   // If we are casting a select then fold the cast into the select
6012   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6013     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6014       return NV;
6015
6016   // If we are casting a PHI then fold the cast into the PHI
6017   if (isa<PHINode>(Src))
6018     if (Instruction *NV = FoldOpIntoPhi(CI))
6019       return NV;
6020   
6021   return 0;
6022 }
6023
6024 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6025 /// integers. This function implements the common transforms for all those
6026 /// cases.
6027 /// @brief Implement the transforms common to CastInst with integer operands
6028 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6029   if (Instruction *Result = commonCastTransforms(CI))
6030     return Result;
6031
6032   Value *Src = CI.getOperand(0);
6033   const Type *SrcTy = Src->getType();
6034   const Type *DestTy = CI.getType();
6035   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6036   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6037
6038   // See if we can simplify any instructions used by the LHS whose sole 
6039   // purpose is to compute bits we don't care about.
6040   uint64_t KnownZero = 0, KnownOne = 0;
6041   if (SimplifyDemandedBits(&CI, DestTy->getIntegerTypeMask(),
6042                            KnownZero, KnownOne))
6043     return &CI;
6044
6045   // If the source isn't an instruction or has more than one use then we
6046   // can't do anything more. 
6047   Instruction *SrcI = dyn_cast<Instruction>(Src);
6048   if (!SrcI || !Src->hasOneUse())
6049     return 0;
6050
6051   // Attempt to propagate the cast into the instruction.
6052   int NumCastsRemoved = 0;
6053   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6054     // If this cast is a truncate, evaluting in a different type always
6055     // eliminates the cast, so it is always a win.  If this is a noop-cast
6056     // this just removes a noop cast which isn't pointful, but simplifies
6057     // the code.  If this is a zero-extension, we need to do an AND to
6058     // maintain the clear top-part of the computation, so we require that
6059     // the input have eliminated at least one cast.  If this is a sign
6060     // extension, we insert two new casts (to do the extension) so we
6061     // require that two casts have been eliminated.
6062     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6063     if (!DoXForm) {
6064       switch (CI.getOpcode()) {
6065         case Instruction::Trunc:
6066           DoXForm = true;
6067           break;
6068         case Instruction::ZExt:
6069           DoXForm = NumCastsRemoved >= 1;
6070           break;
6071         case Instruction::SExt:
6072           DoXForm = NumCastsRemoved >= 2;
6073           break;
6074         case Instruction::BitCast:
6075           DoXForm = false;
6076           break;
6077         default:
6078           // All the others use floating point so we shouldn't actually 
6079           // get here because of the check above.
6080           assert(!"Unknown cast type .. unreachable");
6081           break;
6082       }
6083     }
6084     
6085     if (DoXForm) {
6086       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6087                                            CI.getOpcode() == Instruction::SExt);
6088       assert(Res->getType() == DestTy);
6089       switch (CI.getOpcode()) {
6090       default: assert(0 && "Unknown cast type!");
6091       case Instruction::Trunc:
6092       case Instruction::BitCast:
6093         // Just replace this cast with the result.
6094         return ReplaceInstUsesWith(CI, Res);
6095       case Instruction::ZExt: {
6096         // We need to emit an AND to clear the high bits.
6097         assert(SrcBitSize < DestBitSize && "Not a zext?");
6098         Constant *C = 
6099           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6100         if (DestBitSize < 64)
6101           C = ConstantExpr::getTrunc(C, DestTy);
6102         return BinaryOperator::createAnd(Res, C);
6103       }
6104       case Instruction::SExt:
6105         // We need to emit a cast to truncate, then a cast to sext.
6106         return CastInst::create(Instruction::SExt,
6107             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6108                              CI), DestTy);
6109       }
6110     }
6111   }
6112   
6113   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6114   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6115
6116   switch (SrcI->getOpcode()) {
6117   case Instruction::Add:
6118   case Instruction::Mul:
6119   case Instruction::And:
6120   case Instruction::Or:
6121   case Instruction::Xor:
6122     // If we are discarding information, or just changing the sign, 
6123     // rewrite.
6124     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6125       // Don't insert two casts if they cannot be eliminated.  We allow 
6126       // two casts to be inserted if the sizes are the same.  This could 
6127       // only be converting signedness, which is a noop.
6128       if (DestBitSize == SrcBitSize || 
6129           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6130           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6131         Instruction::CastOps opcode = CI.getOpcode();
6132         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6133         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6134         return BinaryOperator::create(
6135             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6136       }
6137     }
6138
6139     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6140     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6141         SrcI->getOpcode() == Instruction::Xor &&
6142         Op1 == ConstantInt::getTrue() &&
6143         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6144       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6145       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6146     }
6147     break;
6148   case Instruction::SDiv:
6149   case Instruction::UDiv:
6150   case Instruction::SRem:
6151   case Instruction::URem:
6152     // If we are just changing the sign, rewrite.
6153     if (DestBitSize == SrcBitSize) {
6154       // Don't insert two casts if they cannot be eliminated.  We allow 
6155       // two casts to be inserted if the sizes are the same.  This could 
6156       // only be converting signedness, which is a noop.
6157       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6158           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6159         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6160                                               Op0, DestTy, SrcI);
6161         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6162                                               Op1, DestTy, SrcI);
6163         return BinaryOperator::create(
6164           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6165       }
6166     }
6167     break;
6168
6169   case Instruction::Shl:
6170     // Allow changing the sign of the source operand.  Do not allow 
6171     // changing the size of the shift, UNLESS the shift amount is a 
6172     // constant.  We must not change variable sized shifts to a smaller 
6173     // size, because it is undefined to shift more bits out than exist 
6174     // in the value.
6175     if (DestBitSize == SrcBitSize ||
6176         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6177       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6178           Instruction::BitCast : Instruction::Trunc);
6179       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6180       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6181     }
6182     break;
6183   case Instruction::AShr:
6184     // If this is a signed shr, and if all bits shifted in are about to be
6185     // truncated off, turn it into an unsigned shr to allow greater
6186     // simplifications.
6187     if (DestBitSize < SrcBitSize &&
6188         isa<ConstantInt>(Op1)) {
6189       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6190       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6191         // Insert the new logical shift right.
6192         return new ShiftInst(Instruction::LShr, Op0, Op1);
6193       }
6194     }
6195     break;
6196
6197   case Instruction::ICmp:
6198     // If we are just checking for a icmp eq of a single bit and casting it
6199     // to an integer, then shift the bit to the appropriate place and then
6200     // cast to integer to avoid the comparison.
6201     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6202       uint64_t Op1CV = Op1C->getZExtValue();
6203       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6204       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6205       // cast (X == 1) to int --> X        iff X has only the low bit set.
6206       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6207       // cast (X != 0) to int --> X        iff X has only the low bit set.
6208       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6209       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6210       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6211       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6212         // If Op1C some other power of two, convert:
6213         uint64_t KnownZero, KnownOne;
6214         uint64_t TypeMask = Op1->getType()->getIntegerTypeMask();
6215         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6216
6217         // This only works for EQ and NE
6218         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6219         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6220           break;
6221         
6222         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6223           bool isNE = pred == ICmpInst::ICMP_NE;
6224           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6225             // (X&4) == 2 --> false
6226             // (X&4) != 2 --> true
6227             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6228             Res = ConstantExpr::getZExt(Res, CI.getType());
6229             return ReplaceInstUsesWith(CI, Res);
6230           }
6231           
6232           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6233           Value *In = Op0;
6234           if (ShiftAmt) {
6235             // Perform a logical shr by shiftamt.
6236             // Insert the shift to put the result in the low bit.
6237             In = InsertNewInstBefore(
6238               new ShiftInst(Instruction::LShr, In,
6239                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6240                             In->getName()+".lobit"), CI);
6241           }
6242           
6243           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6244             Constant *One = ConstantInt::get(In->getType(), 1);
6245             In = BinaryOperator::createXor(In, One, "tmp");
6246             InsertNewInstBefore(cast<Instruction>(In), CI);
6247           }
6248           
6249           if (CI.getType() == In->getType())
6250             return ReplaceInstUsesWith(CI, In);
6251           else
6252             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6253         }
6254       }
6255     }
6256     break;
6257   }
6258   return 0;
6259 }
6260
6261 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6262   if (Instruction *Result = commonIntCastTransforms(CI))
6263     return Result;
6264   
6265   Value *Src = CI.getOperand(0);
6266   const Type *Ty = CI.getType();
6267   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6268   
6269   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6270     switch (SrcI->getOpcode()) {
6271     default: break;
6272     case Instruction::LShr:
6273       // We can shrink lshr to something smaller if we know the bits shifted in
6274       // are already zeros.
6275       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6276         unsigned ShAmt = ShAmtV->getZExtValue();
6277         
6278         // Get a mask for the bits shifting in.
6279         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6280         Value* SrcIOp0 = SrcI->getOperand(0);
6281         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6282           if (ShAmt >= DestBitWidth)        // All zeros.
6283             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6284
6285           // Okay, we can shrink this.  Truncate the input, then return a new
6286           // shift.
6287           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6288           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6289         }
6290       } else {     // This is a variable shr.
6291         
6292         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6293         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6294         // loop-invariant and CSE'd.
6295         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6296           Value *One = ConstantInt::get(SrcI->getType(), 1);
6297
6298           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6299                                                        SrcI->getOperand(1),
6300                                                        "tmp"), CI);
6301           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6302                                                             SrcI->getOperand(0),
6303                                                             "tmp"), CI);
6304           Value *Zero = Constant::getNullValue(V->getType());
6305           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6306         }
6307       }
6308       break;
6309     }
6310   }
6311   
6312   return 0;
6313 }
6314
6315 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6316   // If one of the common conversion will work ..
6317   if (Instruction *Result = commonIntCastTransforms(CI))
6318     return Result;
6319
6320   Value *Src = CI.getOperand(0);
6321
6322   // If this is a cast of a cast
6323   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6324     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6325     // types and if the sizes are just right we can convert this into a logical
6326     // 'and' which will be much cheaper than the pair of casts.
6327     if (isa<TruncInst>(CSrc)) {
6328       // Get the sizes of the types involved
6329       Value *A = CSrc->getOperand(0);
6330       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6331       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6332       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6333       // If we're actually extending zero bits and the trunc is a no-op
6334       if (MidSize < DstSize && SrcSize == DstSize) {
6335         // Replace both of the casts with an And of the type mask.
6336         uint64_t AndValue = CSrc->getType()->getIntegerTypeMask();
6337         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6338         Instruction *And = 
6339           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6340         // Unfortunately, if the type changed, we need to cast it back.
6341         if (And->getType() != CI.getType()) {
6342           And->setName(CSrc->getName()+".mask");
6343           InsertNewInstBefore(And, CI);
6344           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6345         }
6346         return And;
6347       }
6348     }
6349   }
6350
6351   return 0;
6352 }
6353
6354 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6355   return commonIntCastTransforms(CI);
6356 }
6357
6358 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6359   return commonCastTransforms(CI);
6360 }
6361
6362 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6363   return commonCastTransforms(CI);
6364 }
6365
6366 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6367   return commonCastTransforms(CI);
6368 }
6369
6370 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6371   return commonCastTransforms(CI);
6372 }
6373
6374 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6375   return commonCastTransforms(CI);
6376 }
6377
6378 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6379   return commonCastTransforms(CI);
6380 }
6381
6382 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6383   return commonCastTransforms(CI);
6384 }
6385
6386 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6387   return commonCastTransforms(CI);
6388 }
6389
6390 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6391
6392   // If the operands are integer typed then apply the integer transforms,
6393   // otherwise just apply the common ones.
6394   Value *Src = CI.getOperand(0);
6395   const Type *SrcTy = Src->getType();
6396   const Type *DestTy = CI.getType();
6397
6398   if (SrcTy->isInteger() && DestTy->isInteger()) {
6399     if (Instruction *Result = commonIntCastTransforms(CI))
6400       return Result;
6401   } else {
6402     if (Instruction *Result = commonCastTransforms(CI))
6403       return Result;
6404   }
6405
6406
6407   // Get rid of casts from one type to the same type. These are useless and can
6408   // be replaced by the operand.
6409   if (DestTy == Src->getType())
6410     return ReplaceInstUsesWith(CI, Src);
6411
6412   // If the source and destination are pointers, and this cast is equivalent to
6413   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6414   // This can enhance SROA and other transforms that want type-safe pointers.
6415   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6416     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6417       const Type *DstElTy = DstPTy->getElementType();
6418       const Type *SrcElTy = SrcPTy->getElementType();
6419       
6420       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6421       unsigned NumZeros = 0;
6422       while (SrcElTy != DstElTy && 
6423              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6424              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6425         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6426         ++NumZeros;
6427       }
6428
6429       // If we found a path from the src to dest, create the getelementptr now.
6430       if (SrcElTy == DstElTy) {
6431         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6432         return new GetElementPtrInst(Src, Idxs);
6433       }
6434     }
6435   }
6436
6437   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6438     if (SVI->hasOneUse()) {
6439       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6440       // a bitconvert to a vector with the same # elts.
6441       if (isa<PackedType>(DestTy) && 
6442           cast<PackedType>(DestTy)->getNumElements() == 
6443                 SVI->getType()->getNumElements()) {
6444         CastInst *Tmp;
6445         // If either of the operands is a cast from CI.getType(), then
6446         // evaluating the shuffle in the casted destination's type will allow
6447         // us to eliminate at least one cast.
6448         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6449              Tmp->getOperand(0)->getType() == DestTy) ||
6450             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6451              Tmp->getOperand(0)->getType() == DestTy)) {
6452           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6453                                                SVI->getOperand(0), DestTy, &CI);
6454           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6455                                                SVI->getOperand(1), DestTy, &CI);
6456           // Return a new shuffle vector.  Use the same element ID's, as we
6457           // know the vector types match #elts.
6458           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6459         }
6460       }
6461     }
6462   }
6463   return 0;
6464 }
6465
6466 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6467 ///   %C = or %A, %B
6468 ///   %D = select %cond, %C, %A
6469 /// into:
6470 ///   %C = select %cond, %B, 0
6471 ///   %D = or %A, %C
6472 ///
6473 /// Assuming that the specified instruction is an operand to the select, return
6474 /// a bitmask indicating which operands of this instruction are foldable if they
6475 /// equal the other incoming value of the select.
6476 ///
6477 static unsigned GetSelectFoldableOperands(Instruction *I) {
6478   switch (I->getOpcode()) {
6479   case Instruction::Add:
6480   case Instruction::Mul:
6481   case Instruction::And:
6482   case Instruction::Or:
6483   case Instruction::Xor:
6484     return 3;              // Can fold through either operand.
6485   case Instruction::Sub:   // Can only fold on the amount subtracted.
6486   case Instruction::Shl:   // Can only fold on the shift amount.
6487   case Instruction::LShr:
6488   case Instruction::AShr:
6489     return 1;
6490   default:
6491     return 0;              // Cannot fold
6492   }
6493 }
6494
6495 /// GetSelectFoldableConstant - For the same transformation as the previous
6496 /// function, return the identity constant that goes into the select.
6497 static Constant *GetSelectFoldableConstant(Instruction *I) {
6498   switch (I->getOpcode()) {
6499   default: assert(0 && "This cannot happen!"); abort();
6500   case Instruction::Add:
6501   case Instruction::Sub:
6502   case Instruction::Or:
6503   case Instruction::Xor:
6504     return Constant::getNullValue(I->getType());
6505   case Instruction::Shl:
6506   case Instruction::LShr:
6507   case Instruction::AShr:
6508     return Constant::getNullValue(Type::Int8Ty);
6509   case Instruction::And:
6510     return ConstantInt::getAllOnesValue(I->getType());
6511   case Instruction::Mul:
6512     return ConstantInt::get(I->getType(), 1);
6513   }
6514 }
6515
6516 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6517 /// have the same opcode and only one use each.  Try to simplify this.
6518 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6519                                           Instruction *FI) {
6520   if (TI->getNumOperands() == 1) {
6521     // If this is a non-volatile load or a cast from the same type,
6522     // merge.
6523     if (TI->isCast()) {
6524       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6525         return 0;
6526     } else {
6527       return 0;  // unknown unary op.
6528     }
6529
6530     // Fold this by inserting a select from the input values.
6531     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6532                                        FI->getOperand(0), SI.getName()+".v");
6533     InsertNewInstBefore(NewSI, SI);
6534     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6535                             TI->getType());
6536   }
6537
6538   // Only handle binary, compare and shift operators here.
6539   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6540     return 0;
6541
6542   // Figure out if the operations have any operands in common.
6543   Value *MatchOp, *OtherOpT, *OtherOpF;
6544   bool MatchIsOpZero;
6545   if (TI->getOperand(0) == FI->getOperand(0)) {
6546     MatchOp  = TI->getOperand(0);
6547     OtherOpT = TI->getOperand(1);
6548     OtherOpF = FI->getOperand(1);
6549     MatchIsOpZero = true;
6550   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6551     MatchOp  = TI->getOperand(1);
6552     OtherOpT = TI->getOperand(0);
6553     OtherOpF = FI->getOperand(0);
6554     MatchIsOpZero = false;
6555   } else if (!TI->isCommutative()) {
6556     return 0;
6557   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6558     MatchOp  = TI->getOperand(0);
6559     OtherOpT = TI->getOperand(1);
6560     OtherOpF = FI->getOperand(0);
6561     MatchIsOpZero = true;
6562   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6563     MatchOp  = TI->getOperand(1);
6564     OtherOpT = TI->getOperand(0);
6565     OtherOpF = FI->getOperand(1);
6566     MatchIsOpZero = true;
6567   } else {
6568     return 0;
6569   }
6570
6571   // If we reach here, they do have operations in common.
6572   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6573                                      OtherOpF, SI.getName()+".v");
6574   InsertNewInstBefore(NewSI, SI);
6575
6576   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6577     if (MatchIsOpZero)
6578       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6579     else
6580       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6581   }
6582
6583   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6584   if (MatchIsOpZero)
6585     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6586   else
6587     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6588 }
6589
6590 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6591   Value *CondVal = SI.getCondition();
6592   Value *TrueVal = SI.getTrueValue();
6593   Value *FalseVal = SI.getFalseValue();
6594
6595   // select true, X, Y  -> X
6596   // select false, X, Y -> Y
6597   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6598     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6599
6600   // select C, X, X -> X
6601   if (TrueVal == FalseVal)
6602     return ReplaceInstUsesWith(SI, TrueVal);
6603
6604   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6605     return ReplaceInstUsesWith(SI, FalseVal);
6606   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6607     return ReplaceInstUsesWith(SI, TrueVal);
6608   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6609     if (isa<Constant>(TrueVal))
6610       return ReplaceInstUsesWith(SI, TrueVal);
6611     else
6612       return ReplaceInstUsesWith(SI, FalseVal);
6613   }
6614
6615   if (SI.getType() == Type::Int1Ty) {
6616     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6617       if (C->getZExtValue()) {
6618         // Change: A = select B, true, C --> A = or B, C
6619         return BinaryOperator::createOr(CondVal, FalseVal);
6620       } else {
6621         // Change: A = select B, false, C --> A = and !B, C
6622         Value *NotCond =
6623           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6624                                              "not."+CondVal->getName()), SI);
6625         return BinaryOperator::createAnd(NotCond, FalseVal);
6626       }
6627     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6628       if (C->getZExtValue() == false) {
6629         // Change: A = select B, C, false --> A = and B, C
6630         return BinaryOperator::createAnd(CondVal, TrueVal);
6631       } else {
6632         // Change: A = select B, C, true --> A = or !B, C
6633         Value *NotCond =
6634           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6635                                              "not."+CondVal->getName()), SI);
6636         return BinaryOperator::createOr(NotCond, TrueVal);
6637       }
6638     }
6639   }
6640
6641   // Selecting between two integer constants?
6642   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6643     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6644       // select C, 1, 0 -> cast C to int
6645       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6646         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6647       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6648         // select C, 0, 1 -> cast !C to int
6649         Value *NotCond =
6650           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6651                                                "not."+CondVal->getName()), SI);
6652         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6653       }
6654
6655       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6656
6657         // (x <s 0) ? -1 : 0 -> ashr x, 31
6658         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6659         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6660           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6661             bool CanXForm = false;
6662             if (IC->isSignedPredicate())
6663               CanXForm = CmpCst->isNullValue() && 
6664                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6665             else {
6666               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6667               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6668                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6669             }
6670             
6671             if (CanXForm) {
6672               // The comparison constant and the result are not neccessarily the
6673               // same width. Make an all-ones value by inserting a AShr.
6674               Value *X = IC->getOperand(0);
6675               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6676               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6677               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6678                                                ShAmt, "ones");
6679               InsertNewInstBefore(SRA, SI);
6680               
6681               // Finally, convert to the type of the select RHS.  We figure out
6682               // if this requires a SExt, Trunc or BitCast based on the sizes.
6683               Instruction::CastOps opc = Instruction::BitCast;
6684               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6685               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6686               if (SRASize < SISize)
6687                 opc = Instruction::SExt;
6688               else if (SRASize > SISize)
6689                 opc = Instruction::Trunc;
6690               return CastInst::create(opc, SRA, SI.getType());
6691             }
6692           }
6693
6694
6695         // If one of the constants is zero (we know they can't both be) and we
6696         // have a fcmp instruction with zero, and we have an 'and' with the
6697         // non-constant value, eliminate this whole mess.  This corresponds to
6698         // cases like this: ((X & 27) ? 27 : 0)
6699         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6700           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6701               cast<Constant>(IC->getOperand(1))->isNullValue())
6702             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6703               if (ICA->getOpcode() == Instruction::And &&
6704                   isa<ConstantInt>(ICA->getOperand(1)) &&
6705                   (ICA->getOperand(1) == TrueValC ||
6706                    ICA->getOperand(1) == FalseValC) &&
6707                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6708                 // Okay, now we know that everything is set up, we just don't
6709                 // know whether we have a icmp_ne or icmp_eq and whether the 
6710                 // true or false val is the zero.
6711                 bool ShouldNotVal = !TrueValC->isNullValue();
6712                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6713                 Value *V = ICA;
6714                 if (ShouldNotVal)
6715                   V = InsertNewInstBefore(BinaryOperator::create(
6716                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6717                 return ReplaceInstUsesWith(SI, V);
6718               }
6719       }
6720     }
6721
6722   // See if we are selecting two values based on a comparison of the two values.
6723   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6724     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6725       // Transform (X == Y) ? X : Y  -> Y
6726       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6727         return ReplaceInstUsesWith(SI, FalseVal);
6728       // Transform (X != Y) ? X : Y  -> X
6729       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6730         return ReplaceInstUsesWith(SI, TrueVal);
6731       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6732
6733     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6734       // Transform (X == Y) ? Y : X  -> X
6735       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6736         return ReplaceInstUsesWith(SI, FalseVal);
6737       // Transform (X != Y) ? Y : X  -> Y
6738       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6739         return ReplaceInstUsesWith(SI, TrueVal);
6740       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6741     }
6742   }
6743
6744   // See if we are selecting two values based on a comparison of the two values.
6745   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6746     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6747       // Transform (X == Y) ? X : Y  -> Y
6748       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6749         return ReplaceInstUsesWith(SI, FalseVal);
6750       // Transform (X != Y) ? X : Y  -> X
6751       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6752         return ReplaceInstUsesWith(SI, TrueVal);
6753       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6754
6755     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6756       // Transform (X == Y) ? Y : X  -> X
6757       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6758         return ReplaceInstUsesWith(SI, FalseVal);
6759       // Transform (X != Y) ? Y : X  -> Y
6760       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6761         return ReplaceInstUsesWith(SI, TrueVal);
6762       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6763     }
6764   }
6765
6766   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6767     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6768       if (TI->hasOneUse() && FI->hasOneUse()) {
6769         Instruction *AddOp = 0, *SubOp = 0;
6770
6771         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6772         if (TI->getOpcode() == FI->getOpcode())
6773           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6774             return IV;
6775
6776         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6777         // even legal for FP.
6778         if (TI->getOpcode() == Instruction::Sub &&
6779             FI->getOpcode() == Instruction::Add) {
6780           AddOp = FI; SubOp = TI;
6781         } else if (FI->getOpcode() == Instruction::Sub &&
6782                    TI->getOpcode() == Instruction::Add) {
6783           AddOp = TI; SubOp = FI;
6784         }
6785
6786         if (AddOp) {
6787           Value *OtherAddOp = 0;
6788           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6789             OtherAddOp = AddOp->getOperand(1);
6790           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6791             OtherAddOp = AddOp->getOperand(0);
6792           }
6793
6794           if (OtherAddOp) {
6795             // So at this point we know we have (Y -> OtherAddOp):
6796             //        select C, (add X, Y), (sub X, Z)
6797             Value *NegVal;  // Compute -Z
6798             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6799               NegVal = ConstantExpr::getNeg(C);
6800             } else {
6801               NegVal = InsertNewInstBefore(
6802                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6803             }
6804
6805             Value *NewTrueOp = OtherAddOp;
6806             Value *NewFalseOp = NegVal;
6807             if (AddOp != TI)
6808               std::swap(NewTrueOp, NewFalseOp);
6809             Instruction *NewSel =
6810               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6811
6812             NewSel = InsertNewInstBefore(NewSel, SI);
6813             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6814           }
6815         }
6816       }
6817
6818   // See if we can fold the select into one of our operands.
6819   if (SI.getType()->isInteger()) {
6820     // See the comment above GetSelectFoldableOperands for a description of the
6821     // transformation we are doing here.
6822     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6823       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6824           !isa<Constant>(FalseVal))
6825         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6826           unsigned OpToFold = 0;
6827           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6828             OpToFold = 1;
6829           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6830             OpToFold = 2;
6831           }
6832
6833           if (OpToFold) {
6834             Constant *C = GetSelectFoldableConstant(TVI);
6835             std::string Name = TVI->getName(); TVI->setName("");
6836             Instruction *NewSel =
6837               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6838                              Name);
6839             InsertNewInstBefore(NewSel, SI);
6840             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6841               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6842             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6843               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6844             else {
6845               assert(0 && "Unknown instruction!!");
6846             }
6847           }
6848         }
6849
6850     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6851       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6852           !isa<Constant>(TrueVal))
6853         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6854           unsigned OpToFold = 0;
6855           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6856             OpToFold = 1;
6857           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6858             OpToFold = 2;
6859           }
6860
6861           if (OpToFold) {
6862             Constant *C = GetSelectFoldableConstant(FVI);
6863             std::string Name = FVI->getName(); FVI->setName("");
6864             Instruction *NewSel =
6865               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6866                              Name);
6867             InsertNewInstBefore(NewSel, SI);
6868             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6869               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6870             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6871               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6872             else {
6873               assert(0 && "Unknown instruction!!");
6874             }
6875           }
6876         }
6877   }
6878
6879   if (BinaryOperator::isNot(CondVal)) {
6880     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6881     SI.setOperand(1, FalseVal);
6882     SI.setOperand(2, TrueVal);
6883     return &SI;
6884   }
6885
6886   return 0;
6887 }
6888
6889 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6890 /// determine, return it, otherwise return 0.
6891 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6892   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6893     unsigned Align = GV->getAlignment();
6894     if (Align == 0 && TD) 
6895       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6896     return Align;
6897   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6898     unsigned Align = AI->getAlignment();
6899     if (Align == 0 && TD) {
6900       if (isa<AllocaInst>(AI))
6901         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6902       else if (isa<MallocInst>(AI)) {
6903         // Malloc returns maximally aligned memory.
6904         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6905         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6906         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6907       }
6908     }
6909     return Align;
6910   } else if (isa<BitCastInst>(V) ||
6911              (isa<ConstantExpr>(V) && 
6912               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6913     User *CI = cast<User>(V);
6914     if (isa<PointerType>(CI->getOperand(0)->getType()))
6915       return GetKnownAlignment(CI->getOperand(0), TD);
6916     return 0;
6917   } else if (isa<GetElementPtrInst>(V) ||
6918              (isa<ConstantExpr>(V) && 
6919               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6920     User *GEPI = cast<User>(V);
6921     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6922     if (BaseAlignment == 0) return 0;
6923     
6924     // If all indexes are zero, it is just the alignment of the base pointer.
6925     bool AllZeroOperands = true;
6926     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6927       if (!isa<Constant>(GEPI->getOperand(i)) ||
6928           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6929         AllZeroOperands = false;
6930         break;
6931       }
6932     if (AllZeroOperands)
6933       return BaseAlignment;
6934     
6935     // Otherwise, if the base alignment is >= the alignment we expect for the
6936     // base pointer type, then we know that the resultant pointer is aligned at
6937     // least as much as its type requires.
6938     if (!TD) return 0;
6939
6940     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6941     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6942         <= BaseAlignment) {
6943       const Type *GEPTy = GEPI->getType();
6944       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6945     }
6946     return 0;
6947   }
6948   return 0;
6949 }
6950
6951
6952 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6953 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6954 /// the heavy lifting.
6955 ///
6956 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6957   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6958   if (!II) return visitCallSite(&CI);
6959   
6960   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6961   // visitCallSite.
6962   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6963     bool Changed = false;
6964
6965     // memmove/cpy/set of zero bytes is a noop.
6966     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6967       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6968
6969       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6970         if (CI->getZExtValue() == 1) {
6971           // Replace the instruction with just byte operations.  We would
6972           // transform other cases to loads/stores, but we don't know if
6973           // alignment is sufficient.
6974         }
6975     }
6976
6977     // If we have a memmove and the source operation is a constant global,
6978     // then the source and dest pointers can't alias, so we can change this
6979     // into a call to memcpy.
6980     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6981       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6982         if (GVSrc->isConstant()) {
6983           Module *M = CI.getParent()->getParent()->getParent();
6984           const char *Name;
6985           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6986               Type::Int32Ty)
6987             Name = "llvm.memcpy.i32";
6988           else
6989             Name = "llvm.memcpy.i64";
6990           Constant *MemCpy = M->getOrInsertFunction(Name,
6991                                      CI.getCalledFunction()->getFunctionType());
6992           CI.setOperand(0, MemCpy);
6993           Changed = true;
6994         }
6995     }
6996
6997     // If we can determine a pointer alignment that is bigger than currently
6998     // set, update the alignment.
6999     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7000       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7001       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7002       unsigned Align = std::min(Alignment1, Alignment2);
7003       if (MI->getAlignment()->getZExtValue() < Align) {
7004         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7005         Changed = true;
7006       }
7007     } else if (isa<MemSetInst>(MI)) {
7008       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7009       if (MI->getAlignment()->getZExtValue() < Alignment) {
7010         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7011         Changed = true;
7012       }
7013     }
7014           
7015     if (Changed) return II;
7016   } else {
7017     switch (II->getIntrinsicID()) {
7018     default: break;
7019     case Intrinsic::ppc_altivec_lvx:
7020     case Intrinsic::ppc_altivec_lvxl:
7021     case Intrinsic::x86_sse_loadu_ps:
7022     case Intrinsic::x86_sse2_loadu_pd:
7023     case Intrinsic::x86_sse2_loadu_dq:
7024       // Turn PPC lvx     -> load if the pointer is known aligned.
7025       // Turn X86 loadups -> load if the pointer is known aligned.
7026       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7027         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7028                                       PointerType::get(II->getType()), CI);
7029         return new LoadInst(Ptr);
7030       }
7031       break;
7032     case Intrinsic::ppc_altivec_stvx:
7033     case Intrinsic::ppc_altivec_stvxl:
7034       // Turn stvx -> store if the pointer is known aligned.
7035       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7036         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7037         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7038                                       OpPtrTy, CI);
7039         return new StoreInst(II->getOperand(1), Ptr);
7040       }
7041       break;
7042     case Intrinsic::x86_sse_storeu_ps:
7043     case Intrinsic::x86_sse2_storeu_pd:
7044     case Intrinsic::x86_sse2_storeu_dq:
7045     case Intrinsic::x86_sse2_storel_dq:
7046       // Turn X86 storeu -> store if the pointer is known aligned.
7047       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7048         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7049         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7050                                       OpPtrTy, CI);
7051         return new StoreInst(II->getOperand(2), Ptr);
7052       }
7053       break;
7054       
7055     case Intrinsic::x86_sse_cvttss2si: {
7056       // These intrinsics only demands the 0th element of its input vector.  If
7057       // we can simplify the input based on that, do so now.
7058       uint64_t UndefElts;
7059       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7060                                                 UndefElts)) {
7061         II->setOperand(1, V);
7062         return II;
7063       }
7064       break;
7065     }
7066       
7067     case Intrinsic::ppc_altivec_vperm:
7068       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7069       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7070         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7071         
7072         // Check that all of the elements are integer constants or undefs.
7073         bool AllEltsOk = true;
7074         for (unsigned i = 0; i != 16; ++i) {
7075           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7076               !isa<UndefValue>(Mask->getOperand(i))) {
7077             AllEltsOk = false;
7078             break;
7079           }
7080         }
7081         
7082         if (AllEltsOk) {
7083           // Cast the input vectors to byte vectors.
7084           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7085                                         II->getOperand(1), Mask->getType(), CI);
7086           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7087                                         II->getOperand(2), Mask->getType(), CI);
7088           Value *Result = UndefValue::get(Op0->getType());
7089           
7090           // Only extract each element once.
7091           Value *ExtractedElts[32];
7092           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7093           
7094           for (unsigned i = 0; i != 16; ++i) {
7095             if (isa<UndefValue>(Mask->getOperand(i)))
7096               continue;
7097             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7098             Idx &= 31;  // Match the hardware behavior.
7099             
7100             if (ExtractedElts[Idx] == 0) {
7101               Instruction *Elt = 
7102                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7103               InsertNewInstBefore(Elt, CI);
7104               ExtractedElts[Idx] = Elt;
7105             }
7106           
7107             // Insert this value into the result vector.
7108             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7109             InsertNewInstBefore(cast<Instruction>(Result), CI);
7110           }
7111           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7112         }
7113       }
7114       break;
7115
7116     case Intrinsic::stackrestore: {
7117       // If the save is right next to the restore, remove the restore.  This can
7118       // happen when variable allocas are DCE'd.
7119       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7120         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7121           BasicBlock::iterator BI = SS;
7122           if (&*++BI == II)
7123             return EraseInstFromFunction(CI);
7124         }
7125       }
7126       
7127       // If the stack restore is in a return/unwind block and if there are no
7128       // allocas or calls between the restore and the return, nuke the restore.
7129       TerminatorInst *TI = II->getParent()->getTerminator();
7130       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7131         BasicBlock::iterator BI = II;
7132         bool CannotRemove = false;
7133         for (++BI; &*BI != TI; ++BI) {
7134           if (isa<AllocaInst>(BI) ||
7135               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7136             CannotRemove = true;
7137             break;
7138           }
7139         }
7140         if (!CannotRemove)
7141           return EraseInstFromFunction(CI);
7142       }
7143       break;
7144     }
7145     }
7146   }
7147
7148   return visitCallSite(II);
7149 }
7150
7151 // InvokeInst simplification
7152 //
7153 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7154   return visitCallSite(&II);
7155 }
7156
7157 // visitCallSite - Improvements for call and invoke instructions.
7158 //
7159 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7160   bool Changed = false;
7161
7162   // If the callee is a constexpr cast of a function, attempt to move the cast
7163   // to the arguments of the call/invoke.
7164   if (transformConstExprCastCall(CS)) return 0;
7165
7166   Value *Callee = CS.getCalledValue();
7167
7168   if (Function *CalleeF = dyn_cast<Function>(Callee))
7169     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7170       Instruction *OldCall = CS.getInstruction();
7171       // If the call and callee calling conventions don't match, this call must
7172       // be unreachable, as the call is undefined.
7173       new StoreInst(ConstantInt::getTrue(),
7174                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7175       if (!OldCall->use_empty())
7176         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7177       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7178         return EraseInstFromFunction(*OldCall);
7179       return 0;
7180     }
7181
7182   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7183     // This instruction is not reachable, just remove it.  We insert a store to
7184     // undef so that we know that this code is not reachable, despite the fact
7185     // that we can't modify the CFG here.
7186     new StoreInst(ConstantInt::getTrue(),
7187                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7188                   CS.getInstruction());
7189
7190     if (!CS.getInstruction()->use_empty())
7191       CS.getInstruction()->
7192         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7193
7194     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7195       // Don't break the CFG, insert a dummy cond branch.
7196       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7197                      ConstantInt::getTrue(), II);
7198     }
7199     return EraseInstFromFunction(*CS.getInstruction());
7200   }
7201
7202   const PointerType *PTy = cast<PointerType>(Callee->getType());
7203   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7204   if (FTy->isVarArg()) {
7205     // See if we can optimize any arguments passed through the varargs area of
7206     // the call.
7207     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7208            E = CS.arg_end(); I != E; ++I)
7209       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7210         // If this cast does not effect the value passed through the varargs
7211         // area, we can eliminate the use of the cast.
7212         Value *Op = CI->getOperand(0);
7213         if (CI->isLosslessCast()) {
7214           *I = Op;
7215           Changed = true;
7216         }
7217       }
7218   }
7219
7220   return Changed ? CS.getInstruction() : 0;
7221 }
7222
7223 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7224 // attempt to move the cast to the arguments of the call/invoke.
7225 //
7226 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7227   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7228   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7229   if (CE->getOpcode() != Instruction::BitCast || 
7230       !isa<Function>(CE->getOperand(0)))
7231     return false;
7232   Function *Callee = cast<Function>(CE->getOperand(0));
7233   Instruction *Caller = CS.getInstruction();
7234
7235   // Okay, this is a cast from a function to a different type.  Unless doing so
7236   // would cause a type conversion of one of our arguments, change this call to
7237   // be a direct call with arguments casted to the appropriate types.
7238   //
7239   const FunctionType *FT = Callee->getFunctionType();
7240   const Type *OldRetTy = Caller->getType();
7241
7242   // Check to see if we are changing the return type...
7243   if (OldRetTy != FT->getReturnType()) {
7244     if (Callee->isExternal() && !Caller->use_empty() && 
7245         OldRetTy != FT->getReturnType() &&
7246         // Conversion is ok if changing from pointer to int of same size.
7247         !(isa<PointerType>(FT->getReturnType()) &&
7248           TD->getIntPtrType() == OldRetTy))
7249       return false;   // Cannot transform this return value.
7250
7251     // If the callsite is an invoke instruction, and the return value is used by
7252     // a PHI node in a successor, we cannot change the return type of the call
7253     // because there is no place to put the cast instruction (without breaking
7254     // the critical edge).  Bail out in this case.
7255     if (!Caller->use_empty())
7256       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7257         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7258              UI != E; ++UI)
7259           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7260             if (PN->getParent() == II->getNormalDest() ||
7261                 PN->getParent() == II->getUnwindDest())
7262               return false;
7263   }
7264
7265   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7266   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7267
7268   CallSite::arg_iterator AI = CS.arg_begin();
7269   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7270     const Type *ParamTy = FT->getParamType(i);
7271     const Type *ActTy = (*AI)->getType();
7272     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7273     //Either we can cast directly, or we can upconvert the argument
7274     bool isConvertible = ActTy == ParamTy ||
7275       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7276       (ParamTy->isInteger() && ActTy->isInteger() &&
7277        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7278       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7279        && c->getSExtValue() > 0);
7280     if (Callee->isExternal() && !isConvertible) return false;
7281   }
7282
7283   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7284       Callee->isExternal())
7285     return false;   // Do not delete arguments unless we have a function body...
7286
7287   // Okay, we decided that this is a safe thing to do: go ahead and start
7288   // inserting cast instructions as necessary...
7289   std::vector<Value*> Args;
7290   Args.reserve(NumActualArgs);
7291
7292   AI = CS.arg_begin();
7293   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7294     const Type *ParamTy = FT->getParamType(i);
7295     if ((*AI)->getType() == ParamTy) {
7296       Args.push_back(*AI);
7297     } else {
7298       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7299           false, ParamTy, false);
7300       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7301       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7302     }
7303   }
7304
7305   // If the function takes more arguments than the call was taking, add them
7306   // now...
7307   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7308     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7309
7310   // If we are removing arguments to the function, emit an obnoxious warning...
7311   if (FT->getNumParams() < NumActualArgs)
7312     if (!FT->isVarArg()) {
7313       cerr << "WARNING: While resolving call to function '"
7314            << Callee->getName() << "' arguments were dropped!\n";
7315     } else {
7316       // Add all of the arguments in their promoted form to the arg list...
7317       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7318         const Type *PTy = getPromotedType((*AI)->getType());
7319         if (PTy != (*AI)->getType()) {
7320           // Must promote to pass through va_arg area!
7321           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7322                                                                 PTy, false);
7323           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7324           InsertNewInstBefore(Cast, *Caller);
7325           Args.push_back(Cast);
7326         } else {
7327           Args.push_back(*AI);
7328         }
7329       }
7330     }
7331
7332   if (FT->getReturnType() == Type::VoidTy)
7333     Caller->setName("");   // Void type should not have a name...
7334
7335   Instruction *NC;
7336   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7337     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7338                         Args, Caller->getName(), Caller);
7339     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7340   } else {
7341     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7342     if (cast<CallInst>(Caller)->isTailCall())
7343       cast<CallInst>(NC)->setTailCall();
7344    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7345   }
7346
7347   // Insert a cast of the return type as necessary...
7348   Value *NV = NC;
7349   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7350     if (NV->getType() != Type::VoidTy) {
7351       const Type *CallerTy = Caller->getType();
7352       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7353                                                             CallerTy, false);
7354       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7355
7356       // If this is an invoke instruction, we should insert it after the first
7357       // non-phi, instruction in the normal successor block.
7358       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7359         BasicBlock::iterator I = II->getNormalDest()->begin();
7360         while (isa<PHINode>(I)) ++I;
7361         InsertNewInstBefore(NC, *I);
7362       } else {
7363         // Otherwise, it's a call, just insert cast right after the call instr
7364         InsertNewInstBefore(NC, *Caller);
7365       }
7366       AddUsersToWorkList(*Caller);
7367     } else {
7368       NV = UndefValue::get(Caller->getType());
7369     }
7370   }
7371
7372   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7373     Caller->replaceAllUsesWith(NV);
7374   Caller->getParent()->getInstList().erase(Caller);
7375   removeFromWorkList(Caller);
7376   return true;
7377 }
7378
7379 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7380 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7381 /// and a single binop.
7382 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7383   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7384   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7385          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7386   unsigned Opc = FirstInst->getOpcode();
7387   Value *LHSVal = FirstInst->getOperand(0);
7388   Value *RHSVal = FirstInst->getOperand(1);
7389     
7390   const Type *LHSType = LHSVal->getType();
7391   const Type *RHSType = RHSVal->getType();
7392   
7393   // Scan to see if all operands are the same opcode, all have one use, and all
7394   // kill their operands (i.e. the operands have one use).
7395   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7396     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7397     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7398         // Verify type of the LHS matches so we don't fold cmp's of different
7399         // types or GEP's with different index types.
7400         I->getOperand(0)->getType() != LHSType ||
7401         I->getOperand(1)->getType() != RHSType)
7402       return 0;
7403
7404     // If they are CmpInst instructions, check their predicates
7405     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7406       if (cast<CmpInst>(I)->getPredicate() !=
7407           cast<CmpInst>(FirstInst)->getPredicate())
7408         return 0;
7409     
7410     // Keep track of which operand needs a phi node.
7411     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7412     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7413   }
7414   
7415   // Otherwise, this is safe to transform, determine if it is profitable.
7416
7417   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7418   // Indexes are often folded into load/store instructions, so we don't want to
7419   // hide them behind a phi.
7420   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7421     return 0;
7422   
7423   Value *InLHS = FirstInst->getOperand(0);
7424   Value *InRHS = FirstInst->getOperand(1);
7425   PHINode *NewLHS = 0, *NewRHS = 0;
7426   if (LHSVal == 0) {
7427     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7428     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7429     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7430     InsertNewInstBefore(NewLHS, PN);
7431     LHSVal = NewLHS;
7432   }
7433   
7434   if (RHSVal == 0) {
7435     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7436     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7437     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7438     InsertNewInstBefore(NewRHS, PN);
7439     RHSVal = NewRHS;
7440   }
7441   
7442   // Add all operands to the new PHIs.
7443   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7444     if (NewLHS) {
7445       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7446       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7447     }
7448     if (NewRHS) {
7449       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7450       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7451     }
7452   }
7453     
7454   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7455     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7456   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7457     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7458                            RHSVal);
7459   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7460     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7461   else {
7462     assert(isa<GetElementPtrInst>(FirstInst));
7463     return new GetElementPtrInst(LHSVal, RHSVal);
7464   }
7465 }
7466
7467 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7468 /// of the block that defines it.  This means that it must be obvious the value
7469 /// of the load is not changed from the point of the load to the end of the
7470 /// block it is in.
7471 static bool isSafeToSinkLoad(LoadInst *L) {
7472   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7473   
7474   for (++BBI; BBI != E; ++BBI)
7475     if (BBI->mayWriteToMemory())
7476       return false;
7477   return true;
7478 }
7479
7480
7481 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7482 // operator and they all are only used by the PHI, PHI together their
7483 // inputs, and do the operation once, to the result of the PHI.
7484 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7485   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7486
7487   // Scan the instruction, looking for input operations that can be folded away.
7488   // If all input operands to the phi are the same instruction (e.g. a cast from
7489   // the same type or "+42") we can pull the operation through the PHI, reducing
7490   // code size and simplifying code.
7491   Constant *ConstantOp = 0;
7492   const Type *CastSrcTy = 0;
7493   bool isVolatile = false;
7494   if (isa<CastInst>(FirstInst)) {
7495     CastSrcTy = FirstInst->getOperand(0)->getType();
7496   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7497              isa<CmpInst>(FirstInst)) {
7498     // Can fold binop, compare or shift here if the RHS is a constant, 
7499     // otherwise call FoldPHIArgBinOpIntoPHI.
7500     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7501     if (ConstantOp == 0)
7502       return FoldPHIArgBinOpIntoPHI(PN);
7503   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7504     isVolatile = LI->isVolatile();
7505     // We can't sink the load if the loaded value could be modified between the
7506     // load and the PHI.
7507     if (LI->getParent() != PN.getIncomingBlock(0) ||
7508         !isSafeToSinkLoad(LI))
7509       return 0;
7510   } else if (isa<GetElementPtrInst>(FirstInst)) {
7511     if (FirstInst->getNumOperands() == 2)
7512       return FoldPHIArgBinOpIntoPHI(PN);
7513     // Can't handle general GEPs yet.
7514     return 0;
7515   } else {
7516     return 0;  // Cannot fold this operation.
7517   }
7518
7519   // Check to see if all arguments are the same operation.
7520   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7521     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7522     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7523     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7524       return 0;
7525     if (CastSrcTy) {
7526       if (I->getOperand(0)->getType() != CastSrcTy)
7527         return 0;  // Cast operation must match.
7528     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7529       // We can't sink the load if the loaded value could be modified between 
7530       // the load and the PHI.
7531       if (LI->isVolatile() != isVolatile ||
7532           LI->getParent() != PN.getIncomingBlock(i) ||
7533           !isSafeToSinkLoad(LI))
7534         return 0;
7535     } else if (I->getOperand(1) != ConstantOp) {
7536       return 0;
7537     }
7538   }
7539
7540   // Okay, they are all the same operation.  Create a new PHI node of the
7541   // correct type, and PHI together all of the LHS's of the instructions.
7542   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7543                                PN.getName()+".in");
7544   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7545
7546   Value *InVal = FirstInst->getOperand(0);
7547   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7548
7549   // Add all operands to the new PHI.
7550   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7551     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7552     if (NewInVal != InVal)
7553       InVal = 0;
7554     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7555   }
7556
7557   Value *PhiVal;
7558   if (InVal) {
7559     // The new PHI unions all of the same values together.  This is really
7560     // common, so we handle it intelligently here for compile-time speed.
7561     PhiVal = InVal;
7562     delete NewPN;
7563   } else {
7564     InsertNewInstBefore(NewPN, PN);
7565     PhiVal = NewPN;
7566   }
7567
7568   // Insert and return the new operation.
7569   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7570     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7571   else if (isa<LoadInst>(FirstInst))
7572     return new LoadInst(PhiVal, "", isVolatile);
7573   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7574     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7575   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7576     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7577                            PhiVal, ConstantOp);
7578   else
7579     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7580                          PhiVal, ConstantOp);
7581 }
7582
7583 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7584 /// that is dead.
7585 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7586   if (PN->use_empty()) return true;
7587   if (!PN->hasOneUse()) return false;
7588
7589   // Remember this node, and if we find the cycle, return.
7590   if (!PotentiallyDeadPHIs.insert(PN).second)
7591     return true;
7592
7593   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7594     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7595
7596   return false;
7597 }
7598
7599 // PHINode simplification
7600 //
7601 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7602   // If LCSSA is around, don't mess with Phi nodes
7603   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7604   
7605   if (Value *V = PN.hasConstantValue())
7606     return ReplaceInstUsesWith(PN, V);
7607
7608   // If all PHI operands are the same operation, pull them through the PHI,
7609   // reducing code size.
7610   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7611       PN.getIncomingValue(0)->hasOneUse())
7612     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7613       return Result;
7614
7615   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7616   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7617   // PHI)... break the cycle.
7618   if (PN.hasOneUse())
7619     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7620       std::set<PHINode*> PotentiallyDeadPHIs;
7621       PotentiallyDeadPHIs.insert(&PN);
7622       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7623         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7624     }
7625
7626   return 0;
7627 }
7628
7629 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7630                                    Instruction *InsertPoint,
7631                                    InstCombiner *IC) {
7632   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7633   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7634   // We must cast correctly to the pointer type. Ensure that we
7635   // sign extend the integer value if it is smaller as this is
7636   // used for address computation.
7637   Instruction::CastOps opcode = 
7638      (VTySize < PtrSize ? Instruction::SExt :
7639       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7640   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7641 }
7642
7643
7644 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7645   Value *PtrOp = GEP.getOperand(0);
7646   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7647   // If so, eliminate the noop.
7648   if (GEP.getNumOperands() == 1)
7649     return ReplaceInstUsesWith(GEP, PtrOp);
7650
7651   if (isa<UndefValue>(GEP.getOperand(0)))
7652     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7653
7654   bool HasZeroPointerIndex = false;
7655   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7656     HasZeroPointerIndex = C->isNullValue();
7657
7658   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7659     return ReplaceInstUsesWith(GEP, PtrOp);
7660
7661   // Eliminate unneeded casts for indices.
7662   bool MadeChange = false;
7663   gep_type_iterator GTI = gep_type_begin(GEP);
7664   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7665     if (isa<SequentialType>(*GTI)) {
7666       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7667         Value *Src = CI->getOperand(0);
7668         const Type *SrcTy = Src->getType();
7669         const Type *DestTy = CI->getType();
7670         if (Src->getType()->isInteger()) {
7671           if (SrcTy->getPrimitiveSizeInBits() ==
7672                        DestTy->getPrimitiveSizeInBits()) {
7673             // We can always eliminate a cast from ulong or long to the other.
7674             // We can always eliminate a cast from uint to int or the other on
7675             // 32-bit pointer platforms.
7676             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7677               MadeChange = true;
7678               GEP.setOperand(i, Src);
7679             }
7680           } else if (SrcTy->getPrimitiveSizeInBits() < 
7681                      DestTy->getPrimitiveSizeInBits() &&
7682                      SrcTy->getPrimitiveSizeInBits() == 32) {
7683             // We can eliminate a cast from [u]int to [u]long iff the target 
7684             // is a 32-bit pointer target.
7685             if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7686               MadeChange = true;
7687               GEP.setOperand(i, Src);
7688             }
7689           }
7690         }
7691       }
7692       // If we are using a wider index than needed for this platform, shrink it
7693       // to what we need.  If the incoming value needs a cast instruction,
7694       // insert it.  This explicit cast can make subsequent optimizations more
7695       // obvious.
7696       Value *Op = GEP.getOperand(i);
7697       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7698         if (Constant *C = dyn_cast<Constant>(Op)) {
7699           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7700           MadeChange = true;
7701         } else {
7702           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7703                                 GEP);
7704           GEP.setOperand(i, Op);
7705           MadeChange = true;
7706         }
7707     }
7708   if (MadeChange) return &GEP;
7709
7710   // Combine Indices - If the source pointer to this getelementptr instruction
7711   // is a getelementptr instruction, combine the indices of the two
7712   // getelementptr instructions into a single instruction.
7713   //
7714   std::vector<Value*> SrcGEPOperands;
7715   if (User *Src = dyn_castGetElementPtr(PtrOp))
7716     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7717
7718   if (!SrcGEPOperands.empty()) {
7719     // Note that if our source is a gep chain itself that we wait for that
7720     // chain to be resolved before we perform this transformation.  This
7721     // avoids us creating a TON of code in some cases.
7722     //
7723     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7724         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7725       return 0;   // Wait until our source is folded to completion.
7726
7727     std::vector<Value *> Indices;
7728
7729     // Find out whether the last index in the source GEP is a sequential idx.
7730     bool EndsWithSequential = false;
7731     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7732            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7733       EndsWithSequential = !isa<StructType>(*I);
7734
7735     // Can we combine the two pointer arithmetics offsets?
7736     if (EndsWithSequential) {
7737       // Replace: gep (gep %P, long B), long A, ...
7738       // With:    T = long A+B; gep %P, T, ...
7739       //
7740       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7741       if (SO1 == Constant::getNullValue(SO1->getType())) {
7742         Sum = GO1;
7743       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7744         Sum = SO1;
7745       } else {
7746         // If they aren't the same type, convert both to an integer of the
7747         // target's pointer size.
7748         if (SO1->getType() != GO1->getType()) {
7749           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7750             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7751           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7752             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7753           } else {
7754             unsigned PS = TD->getPointerSize();
7755             if (TD->getTypeSize(SO1->getType()) == PS) {
7756               // Convert GO1 to SO1's type.
7757               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7758
7759             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7760               // Convert SO1 to GO1's type.
7761               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7762             } else {
7763               const Type *PT = TD->getIntPtrType();
7764               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7765               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7766             }
7767           }
7768         }
7769         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7770           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7771         else {
7772           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7773           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7774         }
7775       }
7776
7777       // Recycle the GEP we already have if possible.
7778       if (SrcGEPOperands.size() == 2) {
7779         GEP.setOperand(0, SrcGEPOperands[0]);
7780         GEP.setOperand(1, Sum);
7781         return &GEP;
7782       } else {
7783         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7784                        SrcGEPOperands.end()-1);
7785         Indices.push_back(Sum);
7786         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7787       }
7788     } else if (isa<Constant>(*GEP.idx_begin()) &&
7789                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7790                SrcGEPOperands.size() != 1) {
7791       // Otherwise we can do the fold if the first index of the GEP is a zero
7792       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7793                      SrcGEPOperands.end());
7794       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7795     }
7796
7797     if (!Indices.empty())
7798       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7799
7800   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7801     // GEP of global variable.  If all of the indices for this GEP are
7802     // constants, we can promote this to a constexpr instead of an instruction.
7803
7804     // Scan for nonconstants...
7805     std::vector<Constant*> Indices;
7806     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7807     for (; I != E && isa<Constant>(*I); ++I)
7808       Indices.push_back(cast<Constant>(*I));
7809
7810     if (I == E) {  // If they are all constants...
7811       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7812
7813       // Replace all uses of the GEP with the new constexpr...
7814       return ReplaceInstUsesWith(GEP, CE);
7815     }
7816   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7817     if (!isa<PointerType>(X->getType())) {
7818       // Not interesting.  Source pointer must be a cast from pointer.
7819     } else if (HasZeroPointerIndex) {
7820       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7821       // into     : GEP [10 x ubyte]* X, long 0, ...
7822       //
7823       // This occurs when the program declares an array extern like "int X[];"
7824       //
7825       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7826       const PointerType *XTy = cast<PointerType>(X->getType());
7827       if (const ArrayType *XATy =
7828           dyn_cast<ArrayType>(XTy->getElementType()))
7829         if (const ArrayType *CATy =
7830             dyn_cast<ArrayType>(CPTy->getElementType()))
7831           if (CATy->getElementType() == XATy->getElementType()) {
7832             // At this point, we know that the cast source type is a pointer
7833             // to an array of the same type as the destination pointer
7834             // array.  Because the array type is never stepped over (there
7835             // is a leading zero) we can fold the cast into this GEP.
7836             GEP.setOperand(0, X);
7837             return &GEP;
7838           }
7839     } else if (GEP.getNumOperands() == 2) {
7840       // Transform things like:
7841       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7842       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7843       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7844       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7845       if (isa<ArrayType>(SrcElTy) &&
7846           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7847           TD->getTypeSize(ResElTy)) {
7848         Value *V = InsertNewInstBefore(
7849                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7850                                      GEP.getOperand(1), GEP.getName()), GEP);
7851         // V and GEP are both pointer types --> BitCast
7852         return new BitCastInst(V, GEP.getType());
7853       }
7854       
7855       // Transform things like:
7856       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7857       //   (where tmp = 8*tmp2) into:
7858       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7859       
7860       if (isa<ArrayType>(SrcElTy) &&
7861           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7862         uint64_t ArrayEltSize =
7863             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7864         
7865         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7866         // allow either a mul, shift, or constant here.
7867         Value *NewIdx = 0;
7868         ConstantInt *Scale = 0;
7869         if (ArrayEltSize == 1) {
7870           NewIdx = GEP.getOperand(1);
7871           Scale = ConstantInt::get(NewIdx->getType(), 1);
7872         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7873           NewIdx = ConstantInt::get(CI->getType(), 1);
7874           Scale = CI;
7875         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7876           if (Inst->getOpcode() == Instruction::Shl &&
7877               isa<ConstantInt>(Inst->getOperand(1))) {
7878             unsigned ShAmt =
7879               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7880             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7881             NewIdx = Inst->getOperand(0);
7882           } else if (Inst->getOpcode() == Instruction::Mul &&
7883                      isa<ConstantInt>(Inst->getOperand(1))) {
7884             Scale = cast<ConstantInt>(Inst->getOperand(1));
7885             NewIdx = Inst->getOperand(0);
7886           }
7887         }
7888
7889         // If the index will be to exactly the right offset with the scale taken
7890         // out, perform the transformation.
7891         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7892           if (isa<ConstantInt>(Scale))
7893             Scale = ConstantInt::get(Scale->getType(),
7894                                       Scale->getZExtValue() / ArrayEltSize);
7895           if (Scale->getZExtValue() != 1) {
7896             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7897                                                        true /*SExt*/);
7898             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7899             NewIdx = InsertNewInstBefore(Sc, GEP);
7900           }
7901
7902           // Insert the new GEP instruction.
7903           Instruction *NewGEP =
7904             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7905                                   NewIdx, GEP.getName());
7906           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7907           // The NewGEP must be pointer typed, so must the old one -> BitCast
7908           return new BitCastInst(NewGEP, GEP.getType());
7909         }
7910       }
7911     }
7912   }
7913
7914   return 0;
7915 }
7916
7917 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7918   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7919   if (AI.isArrayAllocation())    // Check C != 1
7920     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7921       const Type *NewTy = 
7922         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7923       AllocationInst *New = 0;
7924
7925       // Create and insert the replacement instruction...
7926       if (isa<MallocInst>(AI))
7927         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7928       else {
7929         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7930         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7931       }
7932
7933       InsertNewInstBefore(New, AI);
7934
7935       // Scan to the end of the allocation instructions, to skip over a block of
7936       // allocas if possible...
7937       //
7938       BasicBlock::iterator It = New;
7939       while (isa<AllocationInst>(*It)) ++It;
7940
7941       // Now that I is pointing to the first non-allocation-inst in the block,
7942       // insert our getelementptr instruction...
7943       //
7944       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7945       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7946                                        New->getName()+".sub", It);
7947
7948       // Now make everything use the getelementptr instead of the original
7949       // allocation.
7950       return ReplaceInstUsesWith(AI, V);
7951     } else if (isa<UndefValue>(AI.getArraySize())) {
7952       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7953     }
7954
7955   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7956   // Note that we only do this for alloca's, because malloc should allocate and
7957   // return a unique pointer, even for a zero byte allocation.
7958   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7959       TD->getTypeSize(AI.getAllocatedType()) == 0)
7960     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7961
7962   return 0;
7963 }
7964
7965 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7966   Value *Op = FI.getOperand(0);
7967
7968   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7969   if (CastInst *CI = dyn_cast<CastInst>(Op))
7970     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7971       FI.setOperand(0, CI->getOperand(0));
7972       return &FI;
7973     }
7974
7975   // free undef -> unreachable.
7976   if (isa<UndefValue>(Op)) {
7977     // Insert a new store to null because we cannot modify the CFG here.
7978     new StoreInst(ConstantInt::getTrue(),
7979                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
7980     return EraseInstFromFunction(FI);
7981   }
7982
7983   // If we have 'free null' delete the instruction.  This can happen in stl code
7984   // when lots of inlining happens.
7985   if (isa<ConstantPointerNull>(Op))
7986     return EraseInstFromFunction(FI);
7987
7988   return 0;
7989 }
7990
7991
7992 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7993 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7994   User *CI = cast<User>(LI.getOperand(0));
7995   Value *CastOp = CI->getOperand(0);
7996
7997   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7998   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7999     const Type *SrcPTy = SrcTy->getElementType();
8000
8001     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8002         isa<PackedType>(DestPTy)) {
8003       // If the source is an array, the code below will not succeed.  Check to
8004       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8005       // constants.
8006       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8007         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8008           if (ASrcTy->getNumElements() != 0) {
8009             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8010             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8011             SrcTy = cast<PointerType>(CastOp->getType());
8012             SrcPTy = SrcTy->getElementType();
8013           }
8014
8015       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8016            isa<PackedType>(SrcPTy)) &&
8017           // Do not allow turning this into a load of an integer, which is then
8018           // casted to a pointer, this pessimizes pointer analysis a lot.
8019           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8020           IC.getTargetData().getTypeSize(SrcPTy) ==
8021                IC.getTargetData().getTypeSize(DestPTy)) {
8022
8023         // Okay, we are casting from one integer or pointer type to another of
8024         // the same size.  Instead of casting the pointer before the load, cast
8025         // the result of the loaded value.
8026         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8027                                                              CI->getName(),
8028                                                          LI.isVolatile()),LI);
8029         // Now cast the result of the load.
8030         return new BitCastInst(NewLoad, LI.getType());
8031       }
8032     }
8033   }
8034   return 0;
8035 }
8036
8037 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8038 /// from this value cannot trap.  If it is not obviously safe to load from the
8039 /// specified pointer, we do a quick local scan of the basic block containing
8040 /// ScanFrom, to determine if the address is already accessed.
8041 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8042   // If it is an alloca or global variable, it is always safe to load from.
8043   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8044
8045   // Otherwise, be a little bit agressive by scanning the local block where we
8046   // want to check to see if the pointer is already being loaded or stored
8047   // from/to.  If so, the previous load or store would have already trapped,
8048   // so there is no harm doing an extra load (also, CSE will later eliminate
8049   // the load entirely).
8050   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8051
8052   while (BBI != E) {
8053     --BBI;
8054
8055     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8056       if (LI->getOperand(0) == V) return true;
8057     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8058       if (SI->getOperand(1) == V) return true;
8059
8060   }
8061   return false;
8062 }
8063
8064 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8065   Value *Op = LI.getOperand(0);
8066
8067   // load (cast X) --> cast (load X) iff safe
8068   if (isa<CastInst>(Op))
8069     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8070       return Res;
8071
8072   // None of the following transforms are legal for volatile loads.
8073   if (LI.isVolatile()) return 0;
8074   
8075   if (&LI.getParent()->front() != &LI) {
8076     BasicBlock::iterator BBI = &LI; --BBI;
8077     // If the instruction immediately before this is a store to the same
8078     // address, do a simple form of store->load forwarding.
8079     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8080       if (SI->getOperand(1) == LI.getOperand(0))
8081         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8082     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8083       if (LIB->getOperand(0) == LI.getOperand(0))
8084         return ReplaceInstUsesWith(LI, LIB);
8085   }
8086
8087   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8088     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8089         isa<UndefValue>(GEPI->getOperand(0))) {
8090       // Insert a new store to null instruction before the load to indicate
8091       // that this code is not reachable.  We do this instead of inserting
8092       // an unreachable instruction directly because we cannot modify the
8093       // CFG.
8094       new StoreInst(UndefValue::get(LI.getType()),
8095                     Constant::getNullValue(Op->getType()), &LI);
8096       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8097     }
8098
8099   if (Constant *C = dyn_cast<Constant>(Op)) {
8100     // load null/undef -> undef
8101     if ((C->isNullValue() || isa<UndefValue>(C))) {
8102       // Insert a new store to null instruction before the load to indicate that
8103       // this code is not reachable.  We do this instead of inserting an
8104       // unreachable instruction directly because we cannot modify the CFG.
8105       new StoreInst(UndefValue::get(LI.getType()),
8106                     Constant::getNullValue(Op->getType()), &LI);
8107       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8108     }
8109
8110     // Instcombine load (constant global) into the value loaded.
8111     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8112       if (GV->isConstant() && !GV->isExternal())
8113         return ReplaceInstUsesWith(LI, GV->getInitializer());
8114
8115     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8116     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8117       if (CE->getOpcode() == Instruction::GetElementPtr) {
8118         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8119           if (GV->isConstant() && !GV->isExternal())
8120             if (Constant *V = 
8121                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8122               return ReplaceInstUsesWith(LI, V);
8123         if (CE->getOperand(0)->isNullValue()) {
8124           // Insert a new store to null instruction before the load to indicate
8125           // that this code is not reachable.  We do this instead of inserting
8126           // an unreachable instruction directly because we cannot modify the
8127           // CFG.
8128           new StoreInst(UndefValue::get(LI.getType()),
8129                         Constant::getNullValue(Op->getType()), &LI);
8130           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8131         }
8132
8133       } else if (CE->isCast()) {
8134         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8135           return Res;
8136       }
8137   }
8138
8139   if (Op->hasOneUse()) {
8140     // Change select and PHI nodes to select values instead of addresses: this
8141     // helps alias analysis out a lot, allows many others simplifications, and
8142     // exposes redundancy in the code.
8143     //
8144     // Note that we cannot do the transformation unless we know that the
8145     // introduced loads cannot trap!  Something like this is valid as long as
8146     // the condition is always false: load (select bool %C, int* null, int* %G),
8147     // but it would not be valid if we transformed it to load from null
8148     // unconditionally.
8149     //
8150     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8151       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8152       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8153           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8154         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8155                                      SI->getOperand(1)->getName()+".val"), LI);
8156         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8157                                      SI->getOperand(2)->getName()+".val"), LI);
8158         return new SelectInst(SI->getCondition(), V1, V2);
8159       }
8160
8161       // load (select (cond, null, P)) -> load P
8162       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8163         if (C->isNullValue()) {
8164           LI.setOperand(0, SI->getOperand(2));
8165           return &LI;
8166         }
8167
8168       // load (select (cond, P, null)) -> load P
8169       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8170         if (C->isNullValue()) {
8171           LI.setOperand(0, SI->getOperand(1));
8172           return &LI;
8173         }
8174     }
8175   }
8176   return 0;
8177 }
8178
8179 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8180 /// when possible.
8181 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8182   User *CI = cast<User>(SI.getOperand(1));
8183   Value *CastOp = CI->getOperand(0);
8184
8185   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8186   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8187     const Type *SrcPTy = SrcTy->getElementType();
8188
8189     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8190       // If the source is an array, the code below will not succeed.  Check to
8191       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8192       // constants.
8193       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8194         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8195           if (ASrcTy->getNumElements() != 0) {
8196             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8197             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8198             SrcTy = cast<PointerType>(CastOp->getType());
8199             SrcPTy = SrcTy->getElementType();
8200           }
8201
8202       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8203           IC.getTargetData().getTypeSize(SrcPTy) ==
8204                IC.getTargetData().getTypeSize(DestPTy)) {
8205
8206         // Okay, we are casting from one integer or pointer type to another of
8207         // the same size.  Instead of casting the pointer before the store, cast
8208         // the value to be stored.
8209         Value *NewCast;
8210         Instruction::CastOps opcode = Instruction::BitCast;
8211         Value *SIOp0 = SI.getOperand(0);
8212         if (isa<PointerType>(SrcPTy)) {
8213           if (SIOp0->getType()->isInteger())
8214             opcode = Instruction::IntToPtr;
8215         } else if (SrcPTy->isInteger()) {
8216           if (isa<PointerType>(SIOp0->getType()))
8217             opcode = Instruction::PtrToInt;
8218         }
8219         if (Constant *C = dyn_cast<Constant>(SIOp0))
8220           NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
8221         else
8222           NewCast = IC.InsertNewInstBefore(
8223             CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
8224         return new StoreInst(NewCast, CastOp);
8225       }
8226     }
8227   }
8228   return 0;
8229 }
8230
8231 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8232   Value *Val = SI.getOperand(0);
8233   Value *Ptr = SI.getOperand(1);
8234
8235   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8236     EraseInstFromFunction(SI);
8237     ++NumCombined;
8238     return 0;
8239   }
8240
8241   // Do really simple DSE, to catch cases where there are several consequtive
8242   // stores to the same location, separated by a few arithmetic operations. This
8243   // situation often occurs with bitfield accesses.
8244   BasicBlock::iterator BBI = &SI;
8245   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8246        --ScanInsts) {
8247     --BBI;
8248     
8249     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8250       // Prev store isn't volatile, and stores to the same location?
8251       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8252         ++NumDeadStore;
8253         ++BBI;
8254         EraseInstFromFunction(*PrevSI);
8255         continue;
8256       }
8257       break;
8258     }
8259     
8260     // If this is a load, we have to stop.  However, if the loaded value is from
8261     // the pointer we're loading and is producing the pointer we're storing,
8262     // then *this* store is dead (X = load P; store X -> P).
8263     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8264       if (LI == Val && LI->getOperand(0) == Ptr) {
8265         EraseInstFromFunction(SI);
8266         ++NumCombined;
8267         return 0;
8268       }
8269       // Otherwise, this is a load from some other location.  Stores before it
8270       // may not be dead.
8271       break;
8272     }
8273     
8274     // Don't skip over loads or things that can modify memory.
8275     if (BBI->mayWriteToMemory())
8276       break;
8277   }
8278   
8279   
8280   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8281
8282   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8283   if (isa<ConstantPointerNull>(Ptr)) {
8284     if (!isa<UndefValue>(Val)) {
8285       SI.setOperand(0, UndefValue::get(Val->getType()));
8286       if (Instruction *U = dyn_cast<Instruction>(Val))
8287         WorkList.push_back(U);  // Dropped a use.
8288       ++NumCombined;
8289     }
8290     return 0;  // Do not modify these!
8291   }
8292
8293   // store undef, Ptr -> noop
8294   if (isa<UndefValue>(Val)) {
8295     EraseInstFromFunction(SI);
8296     ++NumCombined;
8297     return 0;
8298   }
8299
8300   // If the pointer destination is a cast, see if we can fold the cast into the
8301   // source instead.
8302   if (isa<CastInst>(Ptr))
8303     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8304       return Res;
8305   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8306     if (CE->isCast())
8307       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8308         return Res;
8309
8310   
8311   // If this store is the last instruction in the basic block, and if the block
8312   // ends with an unconditional branch, try to move it to the successor block.
8313   BBI = &SI; ++BBI;
8314   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8315     if (BI->isUnconditional()) {
8316       // Check to see if the successor block has exactly two incoming edges.  If
8317       // so, see if the other predecessor contains a store to the same location.
8318       // if so, insert a PHI node (if needed) and move the stores down.
8319       BasicBlock *Dest = BI->getSuccessor(0);
8320
8321       pred_iterator PI = pred_begin(Dest);
8322       BasicBlock *Other = 0;
8323       if (*PI != BI->getParent())
8324         Other = *PI;
8325       ++PI;
8326       if (PI != pred_end(Dest)) {
8327         if (*PI != BI->getParent())
8328           if (Other)
8329             Other = 0;
8330           else
8331             Other = *PI;
8332         if (++PI != pred_end(Dest))
8333           Other = 0;
8334       }
8335       if (Other) {  // If only one other pred...
8336         BBI = Other->getTerminator();
8337         // Make sure this other block ends in an unconditional branch and that
8338         // there is an instruction before the branch.
8339         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8340             BBI != Other->begin()) {
8341           --BBI;
8342           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8343           
8344           // If this instruction is a store to the same location.
8345           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8346             // Okay, we know we can perform this transformation.  Insert a PHI
8347             // node now if we need it.
8348             Value *MergedVal = OtherStore->getOperand(0);
8349             if (MergedVal != SI.getOperand(0)) {
8350               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8351               PN->reserveOperandSpace(2);
8352               PN->addIncoming(SI.getOperand(0), SI.getParent());
8353               PN->addIncoming(OtherStore->getOperand(0), Other);
8354               MergedVal = InsertNewInstBefore(PN, Dest->front());
8355             }
8356             
8357             // Advance to a place where it is safe to insert the new store and
8358             // insert it.
8359             BBI = Dest->begin();
8360             while (isa<PHINode>(BBI)) ++BBI;
8361             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8362                                               OtherStore->isVolatile()), *BBI);
8363
8364             // Nuke the old stores.
8365             EraseInstFromFunction(SI);
8366             EraseInstFromFunction(*OtherStore);
8367             ++NumCombined;
8368             return 0;
8369           }
8370         }
8371       }
8372     }
8373   
8374   return 0;
8375 }
8376
8377
8378 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8379   // Change br (not X), label True, label False to: br X, label False, True
8380   Value *X = 0;
8381   BasicBlock *TrueDest;
8382   BasicBlock *FalseDest;
8383   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8384       !isa<Constant>(X)) {
8385     // Swap Destinations and condition...
8386     BI.setCondition(X);
8387     BI.setSuccessor(0, FalseDest);
8388     BI.setSuccessor(1, TrueDest);
8389     return &BI;
8390   }
8391
8392   // Cannonicalize fcmp_one -> fcmp_oeq
8393   FCmpInst::Predicate FPred; Value *Y;
8394   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8395                              TrueDest, FalseDest)))
8396     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8397          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8398       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8399       std::string Name = I->getName(); I->setName("");
8400       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8401       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8402       // Swap Destinations and condition...
8403       BI.setCondition(NewSCC);
8404       BI.setSuccessor(0, FalseDest);
8405       BI.setSuccessor(1, TrueDest);
8406       removeFromWorkList(I);
8407       I->getParent()->getInstList().erase(I);
8408       WorkList.push_back(cast<Instruction>(NewSCC));
8409       return &BI;
8410     }
8411
8412   // Cannonicalize icmp_ne -> icmp_eq
8413   ICmpInst::Predicate IPred;
8414   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8415                       TrueDest, FalseDest)))
8416     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8417          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8418          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8419       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8420       std::string Name = I->getName(); I->setName("");
8421       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8422       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8423       // Swap Destinations and condition...
8424       BI.setCondition(NewSCC);
8425       BI.setSuccessor(0, FalseDest);
8426       BI.setSuccessor(1, TrueDest);
8427       removeFromWorkList(I);
8428       I->getParent()->getInstList().erase(I);
8429       WorkList.push_back(cast<Instruction>(NewSCC));
8430       return &BI;
8431     }
8432
8433   return 0;
8434 }
8435
8436 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8437   Value *Cond = SI.getCondition();
8438   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8439     if (I->getOpcode() == Instruction::Add)
8440       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8441         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8442         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8443           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8444                                                 AddRHS));
8445         SI.setOperand(0, I->getOperand(0));
8446         WorkList.push_back(I);
8447         return &SI;
8448       }
8449   }
8450   return 0;
8451 }
8452
8453 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8454 /// is to leave as a vector operation.
8455 static bool CheapToScalarize(Value *V, bool isConstant) {
8456   if (isa<ConstantAggregateZero>(V)) 
8457     return true;
8458   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8459     if (isConstant) return true;
8460     // If all elts are the same, we can extract.
8461     Constant *Op0 = C->getOperand(0);
8462     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8463       if (C->getOperand(i) != Op0)
8464         return false;
8465     return true;
8466   }
8467   Instruction *I = dyn_cast<Instruction>(V);
8468   if (!I) return false;
8469   
8470   // Insert element gets simplified to the inserted element or is deleted if
8471   // this is constant idx extract element and its a constant idx insertelt.
8472   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8473       isa<ConstantInt>(I->getOperand(2)))
8474     return true;
8475   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8476     return true;
8477   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8478     if (BO->hasOneUse() &&
8479         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8480          CheapToScalarize(BO->getOperand(1), isConstant)))
8481       return true;
8482   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8483     if (CI->hasOneUse() &&
8484         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8485          CheapToScalarize(CI->getOperand(1), isConstant)))
8486       return true;
8487   
8488   return false;
8489 }
8490
8491 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8492 /// elements into values that are larger than the #elts in the input.
8493 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8494   unsigned NElts = SVI->getType()->getNumElements();
8495   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8496     return std::vector<unsigned>(NElts, 0);
8497   if (isa<UndefValue>(SVI->getOperand(2)))
8498     return std::vector<unsigned>(NElts, 2*NElts);
8499
8500   std::vector<unsigned> Result;
8501   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8502   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8503     if (isa<UndefValue>(CP->getOperand(i)))
8504       Result.push_back(NElts*2);  // undef -> 8
8505     else
8506       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8507   return Result;
8508 }
8509
8510 /// FindScalarElement - Given a vector and an element number, see if the scalar
8511 /// value is already around as a register, for example if it were inserted then
8512 /// extracted from the vector.
8513 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8514   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8515   const PackedType *PTy = cast<PackedType>(V->getType());
8516   unsigned Width = PTy->getNumElements();
8517   if (EltNo >= Width)  // Out of range access.
8518     return UndefValue::get(PTy->getElementType());
8519   
8520   if (isa<UndefValue>(V))
8521     return UndefValue::get(PTy->getElementType());
8522   else if (isa<ConstantAggregateZero>(V))
8523     return Constant::getNullValue(PTy->getElementType());
8524   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8525     return CP->getOperand(EltNo);
8526   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8527     // If this is an insert to a variable element, we don't know what it is.
8528     if (!isa<ConstantInt>(III->getOperand(2))) 
8529       return 0;
8530     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8531     
8532     // If this is an insert to the element we are looking for, return the
8533     // inserted value.
8534     if (EltNo == IIElt) 
8535       return III->getOperand(1);
8536     
8537     // Otherwise, the insertelement doesn't modify the value, recurse on its
8538     // vector input.
8539     return FindScalarElement(III->getOperand(0), EltNo);
8540   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8541     unsigned InEl = getShuffleMask(SVI)[EltNo];
8542     if (InEl < Width)
8543       return FindScalarElement(SVI->getOperand(0), InEl);
8544     else if (InEl < Width*2)
8545       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8546     else
8547       return UndefValue::get(PTy->getElementType());
8548   }
8549   
8550   // Otherwise, we don't know.
8551   return 0;
8552 }
8553
8554 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8555
8556   // If packed val is undef, replace extract with scalar undef.
8557   if (isa<UndefValue>(EI.getOperand(0)))
8558     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8559
8560   // If packed val is constant 0, replace extract with scalar 0.
8561   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8562     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8563   
8564   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8565     // If packed val is constant with uniform operands, replace EI
8566     // with that operand
8567     Constant *op0 = C->getOperand(0);
8568     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8569       if (C->getOperand(i) != op0) {
8570         op0 = 0; 
8571         break;
8572       }
8573     if (op0)
8574       return ReplaceInstUsesWith(EI, op0);
8575   }
8576   
8577   // If extracting a specified index from the vector, see if we can recursively
8578   // find a previously computed scalar that was inserted into the vector.
8579   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8580     // This instruction only demands the single element from the input vector.
8581     // If the input vector has a single use, simplify it based on this use
8582     // property.
8583     uint64_t IndexVal = IdxC->getZExtValue();
8584     if (EI.getOperand(0)->hasOneUse()) {
8585       uint64_t UndefElts;
8586       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8587                                                 1 << IndexVal,
8588                                                 UndefElts)) {
8589         EI.setOperand(0, V);
8590         return &EI;
8591       }
8592     }
8593     
8594     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8595       return ReplaceInstUsesWith(EI, Elt);
8596   }
8597   
8598   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8599     if (I->hasOneUse()) {
8600       // Push extractelement into predecessor operation if legal and
8601       // profitable to do so
8602       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8603         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8604         if (CheapToScalarize(BO, isConstantElt)) {
8605           ExtractElementInst *newEI0 = 
8606             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8607                                    EI.getName()+".lhs");
8608           ExtractElementInst *newEI1 =
8609             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8610                                    EI.getName()+".rhs");
8611           InsertNewInstBefore(newEI0, EI);
8612           InsertNewInstBefore(newEI1, EI);
8613           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8614         }
8615       } else if (isa<LoadInst>(I)) {
8616         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8617                                       PointerType::get(EI.getType()), EI);
8618         GetElementPtrInst *GEP = 
8619           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8620         InsertNewInstBefore(GEP, EI);
8621         return new LoadInst(GEP);
8622       }
8623     }
8624     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8625       // Extracting the inserted element?
8626       if (IE->getOperand(2) == EI.getOperand(1))
8627         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8628       // If the inserted and extracted elements are constants, they must not
8629       // be the same value, extract from the pre-inserted value instead.
8630       if (isa<Constant>(IE->getOperand(2)) &&
8631           isa<Constant>(EI.getOperand(1))) {
8632         AddUsesToWorkList(EI);
8633         EI.setOperand(0, IE->getOperand(0));
8634         return &EI;
8635       }
8636     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8637       // If this is extracting an element from a shufflevector, figure out where
8638       // it came from and extract from the appropriate input element instead.
8639       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8640         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8641         Value *Src;
8642         if (SrcIdx < SVI->getType()->getNumElements())
8643           Src = SVI->getOperand(0);
8644         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8645           SrcIdx -= SVI->getType()->getNumElements();
8646           Src = SVI->getOperand(1);
8647         } else {
8648           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8649         }
8650         return new ExtractElementInst(Src, SrcIdx);
8651       }
8652     }
8653   }
8654   return 0;
8655 }
8656
8657 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8658 /// elements from either LHS or RHS, return the shuffle mask and true. 
8659 /// Otherwise, return false.
8660 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8661                                          std::vector<Constant*> &Mask) {
8662   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8663          "Invalid CollectSingleShuffleElements");
8664   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8665
8666   if (isa<UndefValue>(V)) {
8667     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8668     return true;
8669   } else if (V == LHS) {
8670     for (unsigned i = 0; i != NumElts; ++i)
8671       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8672     return true;
8673   } else if (V == RHS) {
8674     for (unsigned i = 0; i != NumElts; ++i)
8675       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8676     return true;
8677   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8678     // If this is an insert of an extract from some other vector, include it.
8679     Value *VecOp    = IEI->getOperand(0);
8680     Value *ScalarOp = IEI->getOperand(1);
8681     Value *IdxOp    = IEI->getOperand(2);
8682     
8683     if (!isa<ConstantInt>(IdxOp))
8684       return false;
8685     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8686     
8687     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8688       // Okay, we can handle this if the vector we are insertinting into is
8689       // transitively ok.
8690       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8691         // If so, update the mask to reflect the inserted undef.
8692         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8693         return true;
8694       }      
8695     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8696       if (isa<ConstantInt>(EI->getOperand(1)) &&
8697           EI->getOperand(0)->getType() == V->getType()) {
8698         unsigned ExtractedIdx =
8699           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8700         
8701         // This must be extracting from either LHS or RHS.
8702         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8703           // Okay, we can handle this if the vector we are insertinting into is
8704           // transitively ok.
8705           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8706             // If so, update the mask to reflect the inserted value.
8707             if (EI->getOperand(0) == LHS) {
8708               Mask[InsertedIdx & (NumElts-1)] = 
8709                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8710             } else {
8711               assert(EI->getOperand(0) == RHS);
8712               Mask[InsertedIdx & (NumElts-1)] = 
8713                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8714               
8715             }
8716             return true;
8717           }
8718         }
8719       }
8720     }
8721   }
8722   // TODO: Handle shufflevector here!
8723   
8724   return false;
8725 }
8726
8727 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8728 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8729 /// that computes V and the LHS value of the shuffle.
8730 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8731                                      Value *&RHS) {
8732   assert(isa<PackedType>(V->getType()) && 
8733          (RHS == 0 || V->getType() == RHS->getType()) &&
8734          "Invalid shuffle!");
8735   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8736
8737   if (isa<UndefValue>(V)) {
8738     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8739     return V;
8740   } else if (isa<ConstantAggregateZero>(V)) {
8741     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8742     return V;
8743   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8744     // If this is an insert of an extract from some other vector, include it.
8745     Value *VecOp    = IEI->getOperand(0);
8746     Value *ScalarOp = IEI->getOperand(1);
8747     Value *IdxOp    = IEI->getOperand(2);
8748     
8749     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8750       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8751           EI->getOperand(0)->getType() == V->getType()) {
8752         unsigned ExtractedIdx =
8753           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8754         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8755         
8756         // Either the extracted from or inserted into vector must be RHSVec,
8757         // otherwise we'd end up with a shuffle of three inputs.
8758         if (EI->getOperand(0) == RHS || RHS == 0) {
8759           RHS = EI->getOperand(0);
8760           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8761           Mask[InsertedIdx & (NumElts-1)] = 
8762             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8763           return V;
8764         }
8765         
8766         if (VecOp == RHS) {
8767           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8768           // Everything but the extracted element is replaced with the RHS.
8769           for (unsigned i = 0; i != NumElts; ++i) {
8770             if (i != InsertedIdx)
8771               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8772           }
8773           return V;
8774         }
8775         
8776         // If this insertelement is a chain that comes from exactly these two
8777         // vectors, return the vector and the effective shuffle.
8778         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8779           return EI->getOperand(0);
8780         
8781       }
8782     }
8783   }
8784   // TODO: Handle shufflevector here!
8785   
8786   // Otherwise, can't do anything fancy.  Return an identity vector.
8787   for (unsigned i = 0; i != NumElts; ++i)
8788     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8789   return V;
8790 }
8791
8792 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8793   Value *VecOp    = IE.getOperand(0);
8794   Value *ScalarOp = IE.getOperand(1);
8795   Value *IdxOp    = IE.getOperand(2);
8796   
8797   // If the inserted element was extracted from some other vector, and if the 
8798   // indexes are constant, try to turn this into a shufflevector operation.
8799   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8800     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8801         EI->getOperand(0)->getType() == IE.getType()) {
8802       unsigned NumVectorElts = IE.getType()->getNumElements();
8803       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8804       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8805       
8806       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8807         return ReplaceInstUsesWith(IE, VecOp);
8808       
8809       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8810         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8811       
8812       // If we are extracting a value from a vector, then inserting it right
8813       // back into the same place, just use the input vector.
8814       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8815         return ReplaceInstUsesWith(IE, VecOp);      
8816       
8817       // We could theoretically do this for ANY input.  However, doing so could
8818       // turn chains of insertelement instructions into a chain of shufflevector
8819       // instructions, and right now we do not merge shufflevectors.  As such,
8820       // only do this in a situation where it is clear that there is benefit.
8821       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8822         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8823         // the values of VecOp, except then one read from EIOp0.
8824         // Build a new shuffle mask.
8825         std::vector<Constant*> Mask;
8826         if (isa<UndefValue>(VecOp))
8827           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8828         else {
8829           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8830           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8831                                                        NumVectorElts));
8832         } 
8833         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8834         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8835                                      ConstantPacked::get(Mask));
8836       }
8837       
8838       // If this insertelement isn't used by some other insertelement, turn it
8839       // (and any insertelements it points to), into one big shuffle.
8840       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8841         std::vector<Constant*> Mask;
8842         Value *RHS = 0;
8843         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8844         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8845         // We now have a shuffle of LHS, RHS, Mask.
8846         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8847       }
8848     }
8849   }
8850
8851   return 0;
8852 }
8853
8854
8855 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8856   Value *LHS = SVI.getOperand(0);
8857   Value *RHS = SVI.getOperand(1);
8858   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8859
8860   bool MadeChange = false;
8861   
8862   // Undefined shuffle mask -> undefined value.
8863   if (isa<UndefValue>(SVI.getOperand(2)))
8864     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8865   
8866   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8867   // the undef, change them to undefs.
8868   if (isa<UndefValue>(SVI.getOperand(1))) {
8869     // Scan to see if there are any references to the RHS.  If so, replace them
8870     // with undef element refs and set MadeChange to true.
8871     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8872       if (Mask[i] >= e && Mask[i] != 2*e) {
8873         Mask[i] = 2*e;
8874         MadeChange = true;
8875       }
8876     }
8877     
8878     if (MadeChange) {
8879       // Remap any references to RHS to use LHS.
8880       std::vector<Constant*> Elts;
8881       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8882         if (Mask[i] == 2*e)
8883           Elts.push_back(UndefValue::get(Type::Int32Ty));
8884         else
8885           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8886       }
8887       SVI.setOperand(2, ConstantPacked::get(Elts));
8888     }
8889   }
8890   
8891   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8892   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8893   if (LHS == RHS || isa<UndefValue>(LHS)) {
8894     if (isa<UndefValue>(LHS) && LHS == RHS) {
8895       // shuffle(undef,undef,mask) -> undef.
8896       return ReplaceInstUsesWith(SVI, LHS);
8897     }
8898     
8899     // Remap any references to RHS to use LHS.
8900     std::vector<Constant*> Elts;
8901     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8902       if (Mask[i] >= 2*e)
8903         Elts.push_back(UndefValue::get(Type::Int32Ty));
8904       else {
8905         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8906             (Mask[i] <  e && isa<UndefValue>(LHS)))
8907           Mask[i] = 2*e;     // Turn into undef.
8908         else
8909           Mask[i] &= (e-1);  // Force to LHS.
8910         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8911       }
8912     }
8913     SVI.setOperand(0, SVI.getOperand(1));
8914     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8915     SVI.setOperand(2, ConstantPacked::get(Elts));
8916     LHS = SVI.getOperand(0);
8917     RHS = SVI.getOperand(1);
8918     MadeChange = true;
8919   }
8920   
8921   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8922   bool isLHSID = true, isRHSID = true;
8923     
8924   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8925     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8926     // Is this an identity shuffle of the LHS value?
8927     isLHSID &= (Mask[i] == i);
8928       
8929     // Is this an identity shuffle of the RHS value?
8930     isRHSID &= (Mask[i]-e == i);
8931   }
8932
8933   // Eliminate identity shuffles.
8934   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8935   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8936   
8937   // If the LHS is a shufflevector itself, see if we can combine it with this
8938   // one without producing an unusual shuffle.  Here we are really conservative:
8939   // we are absolutely afraid of producing a shuffle mask not in the input
8940   // program, because the code gen may not be smart enough to turn a merged
8941   // shuffle into two specific shuffles: it may produce worse code.  As such,
8942   // we only merge two shuffles if the result is one of the two input shuffle
8943   // masks.  In this case, merging the shuffles just removes one instruction,
8944   // which we know is safe.  This is good for things like turning:
8945   // (splat(splat)) -> splat.
8946   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8947     if (isa<UndefValue>(RHS)) {
8948       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8949
8950       std::vector<unsigned> NewMask;
8951       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8952         if (Mask[i] >= 2*e)
8953           NewMask.push_back(2*e);
8954         else
8955           NewMask.push_back(LHSMask[Mask[i]]);
8956       
8957       // If the result mask is equal to the src shuffle or this shuffle mask, do
8958       // the replacement.
8959       if (NewMask == LHSMask || NewMask == Mask) {
8960         std::vector<Constant*> Elts;
8961         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8962           if (NewMask[i] >= e*2) {
8963             Elts.push_back(UndefValue::get(Type::Int32Ty));
8964           } else {
8965             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8966           }
8967         }
8968         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8969                                      LHSSVI->getOperand(1),
8970                                      ConstantPacked::get(Elts));
8971       }
8972     }
8973   }
8974   
8975   return MadeChange ? &SVI : 0;
8976 }
8977
8978
8979
8980 void InstCombiner::removeFromWorkList(Instruction *I) {
8981   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8982                  WorkList.end());
8983 }
8984
8985
8986 /// TryToSinkInstruction - Try to move the specified instruction from its
8987 /// current block into the beginning of DestBlock, which can only happen if it's
8988 /// safe to move the instruction past all of the instructions between it and the
8989 /// end of its block.
8990 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8991   assert(I->hasOneUse() && "Invariants didn't hold!");
8992
8993   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8994   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8995
8996   // Do not sink alloca instructions out of the entry block.
8997   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8998     return false;
8999
9000   // We can only sink load instructions if there is nothing between the load and
9001   // the end of block that could change the value.
9002   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9003     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9004          Scan != E; ++Scan)
9005       if (Scan->mayWriteToMemory())
9006         return false;
9007   }
9008
9009   BasicBlock::iterator InsertPos = DestBlock->begin();
9010   while (isa<PHINode>(InsertPos)) ++InsertPos;
9011
9012   I->moveBefore(InsertPos);
9013   ++NumSunkInst;
9014   return true;
9015 }
9016
9017 /// OptimizeConstantExpr - Given a constant expression and target data layout
9018 /// information, symbolically evaluate the constant expr to something simpler
9019 /// if possible.
9020 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9021   if (!TD) return CE;
9022   
9023   Constant *Ptr = CE->getOperand(0);
9024   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9025       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9026     // If this is a constant expr gep that is effectively computing an
9027     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9028     bool isFoldableGEP = true;
9029     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9030       if (!isa<ConstantInt>(CE->getOperand(i)))
9031         isFoldableGEP = false;
9032     if (isFoldableGEP) {
9033       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9034       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
9035       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
9036       return ConstantExpr::getIntToPtr(C, CE->getType());
9037     }
9038   }
9039   
9040   return CE;
9041 }
9042
9043
9044 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9045 /// all reachable code to the worklist.
9046 ///
9047 /// This has a couple of tricks to make the code faster and more powerful.  In
9048 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9049 /// them to the worklist (this significantly speeds up instcombine on code where
9050 /// many instructions are dead or constant).  Additionally, if we find a branch
9051 /// whose condition is a known constant, we only visit the reachable successors.
9052 ///
9053 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9054                                        std::set<BasicBlock*> &Visited,
9055                                        std::vector<Instruction*> &WorkList,
9056                                        const TargetData *TD) {
9057   // We have now visited this block!  If we've already been here, bail out.
9058   if (!Visited.insert(BB).second) return;
9059     
9060   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9061     Instruction *Inst = BBI++;
9062     
9063     // DCE instruction if trivially dead.
9064     if (isInstructionTriviallyDead(Inst)) {
9065       ++NumDeadInst;
9066       DOUT << "IC: DCE: " << *Inst;
9067       Inst->eraseFromParent();
9068       continue;
9069     }
9070     
9071     // ConstantProp instruction if trivially constant.
9072     if (Constant *C = ConstantFoldInstruction(Inst)) {
9073       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9074         C = OptimizeConstantExpr(CE, TD);
9075       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9076       Inst->replaceAllUsesWith(C);
9077       ++NumConstProp;
9078       Inst->eraseFromParent();
9079       continue;
9080     }
9081     
9082     WorkList.push_back(Inst);
9083   }
9084
9085   // Recursively visit successors.  If this is a branch or switch on a constant,
9086   // only visit the reachable successor.
9087   TerminatorInst *TI = BB->getTerminator();
9088   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9089     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9090       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9091       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9092                                  TD);
9093       return;
9094     }
9095   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9096     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9097       // See if this is an explicit destination.
9098       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9099         if (SI->getCaseValue(i) == Cond) {
9100           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9101           return;
9102         }
9103       
9104       // Otherwise it is the default destination.
9105       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9106       return;
9107     }
9108   }
9109   
9110   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9111     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9112 }
9113
9114 bool InstCombiner::runOnFunction(Function &F) {
9115   bool Changed = false;
9116   TD = &getAnalysis<TargetData>();
9117
9118   {
9119     // Do a depth-first traversal of the function, populate the worklist with
9120     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9121     // track of which blocks we visit.
9122     std::set<BasicBlock*> Visited;
9123     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9124
9125     // Do a quick scan over the function.  If we find any blocks that are
9126     // unreachable, remove any instructions inside of them.  This prevents
9127     // the instcombine code from having to deal with some bad special cases.
9128     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9129       if (!Visited.count(BB)) {
9130         Instruction *Term = BB->getTerminator();
9131         while (Term != BB->begin()) {   // Remove instrs bottom-up
9132           BasicBlock::iterator I = Term; --I;
9133
9134           DOUT << "IC: DCE: " << *I;
9135           ++NumDeadInst;
9136
9137           if (!I->use_empty())
9138             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9139           I->eraseFromParent();
9140         }
9141       }
9142   }
9143
9144   while (!WorkList.empty()) {
9145     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9146     WorkList.pop_back();
9147
9148     // Check to see if we can DCE the instruction.
9149     if (isInstructionTriviallyDead(I)) {
9150       // Add operands to the worklist.
9151       if (I->getNumOperands() < 4)
9152         AddUsesToWorkList(*I);
9153       ++NumDeadInst;
9154
9155       DOUT << "IC: DCE: " << *I;
9156
9157       I->eraseFromParent();
9158       removeFromWorkList(I);
9159       continue;
9160     }
9161
9162     // Instruction isn't dead, see if we can constant propagate it.
9163     if (Constant *C = ConstantFoldInstruction(I)) {
9164       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9165         C = OptimizeConstantExpr(CE, TD);
9166       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9167
9168       // Add operands to the worklist.
9169       AddUsesToWorkList(*I);
9170       ReplaceInstUsesWith(*I, C);
9171
9172       ++NumConstProp;
9173       I->eraseFromParent();
9174       removeFromWorkList(I);
9175       continue;
9176     }
9177
9178     // See if we can trivially sink this instruction to a successor basic block.
9179     if (I->hasOneUse()) {
9180       BasicBlock *BB = I->getParent();
9181       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9182       if (UserParent != BB) {
9183         bool UserIsSuccessor = false;
9184         // See if the user is one of our successors.
9185         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9186           if (*SI == UserParent) {
9187             UserIsSuccessor = true;
9188             break;
9189           }
9190
9191         // If the user is one of our immediate successors, and if that successor
9192         // only has us as a predecessors (we'd have to split the critical edge
9193         // otherwise), we can keep going.
9194         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9195             next(pred_begin(UserParent)) == pred_end(UserParent))
9196           // Okay, the CFG is simple enough, try to sink this instruction.
9197           Changed |= TryToSinkInstruction(I, UserParent);
9198       }
9199     }
9200
9201     // Now that we have an instruction, try combining it to simplify it...
9202     if (Instruction *Result = visit(*I)) {
9203       ++NumCombined;
9204       // Should we replace the old instruction with a new one?
9205       if (Result != I) {
9206         DOUT << "IC: Old = " << *I
9207              << "    New = " << *Result;
9208
9209         // Everything uses the new instruction now.
9210         I->replaceAllUsesWith(Result);
9211
9212         // Push the new instruction and any users onto the worklist.
9213         WorkList.push_back(Result);
9214         AddUsersToWorkList(*Result);
9215
9216         // Move the name to the new instruction first...
9217         std::string OldName = I->getName(); I->setName("");
9218         Result->setName(OldName);
9219
9220         // Insert the new instruction into the basic block...
9221         BasicBlock *InstParent = I->getParent();
9222         BasicBlock::iterator InsertPos = I;
9223
9224         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9225           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9226             ++InsertPos;
9227
9228         InstParent->getInstList().insert(InsertPos, Result);
9229
9230         // Make sure that we reprocess all operands now that we reduced their
9231         // use counts.
9232         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9233           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9234             WorkList.push_back(OpI);
9235
9236         // Instructions can end up on the worklist more than once.  Make sure
9237         // we do not process an instruction that has been deleted.
9238         removeFromWorkList(I);
9239
9240         // Erase the old instruction.
9241         InstParent->getInstList().erase(I);
9242       } else {
9243         DOUT << "IC: MOD = " << *I;
9244
9245         // If the instruction was modified, it's possible that it is now dead.
9246         // if so, remove it.
9247         if (isInstructionTriviallyDead(I)) {
9248           // Make sure we process all operands now that we are reducing their
9249           // use counts.
9250           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9251             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9252               WorkList.push_back(OpI);
9253
9254           // Instructions may end up in the worklist more than once.  Erase all
9255           // occurrences of this instruction.
9256           removeFromWorkList(I);
9257           I->eraseFromParent();
9258         } else {
9259           WorkList.push_back(Result);
9260           AddUsersToWorkList(*Result);
9261         }
9262       }
9263       Changed = true;
9264     }
9265   }
9266
9267   return Changed;
9268 }
9269
9270 FunctionPass *llvm::createInstructionCombiningPass() {
9271   return new InstCombiner();
9272 }
9273