Fix typos.
[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 i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %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/ParameterAttributes.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include <algorithm>
60 #include <sstream>
61 using namespace llvm;
62 using namespace llvm::PatternMatch;
63
64 STATISTIC(NumCombined , "Number of insts combined");
65 STATISTIC(NumConstProp, "Number of constant folds");
66 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68 STATISTIC(NumSunkInst , "Number of instructions sunk");
69
70 namespace {
71   class VISIBILITY_HIDDEN InstCombiner
72     : public FunctionPass,
73       public InstVisitor<InstCombiner, Instruction*> {
74     // Worklist of all of the instructions that need to be simplified.
75     std::vector<Instruction*> Worklist;
76     DenseMap<Instruction*, unsigned> WorklistMap;
77     TargetData *TD;
78     bool MustPreserveLCSSA;
79   public:
80     static char ID; // Pass identification, replacement for typeid
81     InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
83     /// AddToWorkList - Add the specified instruction to the worklist if it
84     /// isn't already in it.
85     void AddToWorkList(Instruction *I) {
86       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87         Worklist.push_back(I);
88     }
89     
90     // RemoveFromWorkList - remove I from the worklist if it exists.
91     void RemoveFromWorkList(Instruction *I) {
92       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93       if (It == WorklistMap.end()) return; // Not in worklist.
94       
95       // Don't bother moving everything down, just null out the slot.
96       Worklist[It->second] = 0;
97       
98       WorklistMap.erase(It);
99     }
100     
101     Instruction *RemoveOneFromWorkList() {
102       Instruction *I = Worklist.back();
103       Worklist.pop_back();
104       WorklistMap.erase(I);
105       return I;
106     }
107
108     
109     /// AddUsersToWorkList - When an instruction is simplified, add all users of
110     /// the instruction to the work lists because they might get more simplified
111     /// now.
112     ///
113     void AddUsersToWorkList(Value &I) {
114       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
115            UI != UE; ++UI)
116         AddToWorkList(cast<Instruction>(*UI));
117     }
118
119     /// AddUsesToWorkList - When an instruction is simplified, add operands to
120     /// the work lists because they might get more simplified now.
121     ///
122     void AddUsesToWorkList(Instruction &I) {
123       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
125           AddToWorkList(Op);
126     }
127     
128     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129     /// dead.  Add all of its operands to the worklist, turning them into
130     /// undef's to reduce the number of uses of those instructions.
131     ///
132     /// Return the specified operand before it is turned into an undef.
133     ///
134     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135       Value *R = I.getOperand(op);
136       
137       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
139           AddToWorkList(Op);
140           // Set the operand to undef to drop the use.
141           I.setOperand(i, UndefValue::get(Op->getType()));
142         }
143       
144       return R;
145     }
146
147   public:
148     virtual bool runOnFunction(Function &F);
149     
150     bool DoOneIteration(Function &F, unsigned ItNum);
151
152     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153       AU.addRequired<TargetData>();
154       AU.addPreservedID(LCSSAID);
155       AU.setPreservesCFG();
156     }
157
158     TargetData &getTargetData() const { return *TD; }
159
160     // Visitation implementation - Implement instruction combining for different
161     // instruction types.  The semantics are as follows:
162     // Return Value:
163     //    null        - No change was made
164     //     I          - Change was made, I is still valid, I may be dead though
165     //   otherwise    - Change was made, replace I with returned instruction
166     //
167     Instruction *visitAdd(BinaryOperator &I);
168     Instruction *visitSub(BinaryOperator &I);
169     Instruction *visitMul(BinaryOperator &I);
170     Instruction *visitURem(BinaryOperator &I);
171     Instruction *visitSRem(BinaryOperator &I);
172     Instruction *visitFRem(BinaryOperator &I);
173     Instruction *commonRemTransforms(BinaryOperator &I);
174     Instruction *commonIRemTransforms(BinaryOperator &I);
175     Instruction *commonDivTransforms(BinaryOperator &I);
176     Instruction *commonIDivTransforms(BinaryOperator &I);
177     Instruction *visitUDiv(BinaryOperator &I);
178     Instruction *visitSDiv(BinaryOperator &I);
179     Instruction *visitFDiv(BinaryOperator &I);
180     Instruction *visitAnd(BinaryOperator &I);
181     Instruction *visitOr (BinaryOperator &I);
182     Instruction *visitXor(BinaryOperator &I);
183     Instruction *visitShl(BinaryOperator &I);
184     Instruction *visitAShr(BinaryOperator &I);
185     Instruction *visitLShr(BinaryOperator &I);
186     Instruction *commonShiftTransforms(BinaryOperator &I);
187     Instruction *visitFCmpInst(FCmpInst &I);
188     Instruction *visitICmpInst(ICmpInst &I);
189     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
190     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191                                                 Instruction *LHS,
192                                                 ConstantInt *RHS);
193     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194                                 ConstantInt *DivRHS);
195
196     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197                              ICmpInst::Predicate Cond, Instruction &I);
198     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
199                                      BinaryOperator &I);
200     Instruction *commonCastTransforms(CastInst &CI);
201     Instruction *commonIntCastTransforms(CastInst &CI);
202     Instruction *commonPointerCastTransforms(CastInst &CI);
203     Instruction *visitTrunc(TruncInst &CI);
204     Instruction *visitZExt(ZExtInst &CI);
205     Instruction *visitSExt(SExtInst &CI);
206     Instruction *visitFPTrunc(CastInst &CI);
207     Instruction *visitFPExt(CastInst &CI);
208     Instruction *visitFPToUI(CastInst &CI);
209     Instruction *visitFPToSI(CastInst &CI);
210     Instruction *visitUIToFP(CastInst &CI);
211     Instruction *visitSIToFP(CastInst &CI);
212     Instruction *visitPtrToInt(CastInst &CI);
213     Instruction *visitIntToPtr(CastInst &CI);
214     Instruction *visitBitCast(BitCastInst &CI);
215     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216                                 Instruction *FI);
217     Instruction *visitSelectInst(SelectInst &CI);
218     Instruction *visitCallInst(CallInst &CI);
219     Instruction *visitInvokeInst(InvokeInst &II);
220     Instruction *visitPHINode(PHINode &PN);
221     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
222     Instruction *visitAllocationInst(AllocationInst &AI);
223     Instruction *visitFreeInst(FreeInst &FI);
224     Instruction *visitLoadInst(LoadInst &LI);
225     Instruction *visitStoreInst(StoreInst &SI);
226     Instruction *visitBranchInst(BranchInst &BI);
227     Instruction *visitSwitchInst(SwitchInst &SI);
228     Instruction *visitInsertElementInst(InsertElementInst &IE);
229     Instruction *visitExtractElementInst(ExtractElementInst &EI);
230     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
231
232     // visitInstruction - Specify what to return for unhandled instructions...
233     Instruction *visitInstruction(Instruction &I) { return 0; }
234
235   private:
236     Instruction *visitCallSite(CallSite CS);
237     bool transformConstExprCastCall(CallSite CS);
238     Instruction *transformCallThroughTrampoline(CallSite CS);
239
240   public:
241     // InsertNewInstBefore - insert an instruction New before instruction Old
242     // in the program.  Add the new instruction to the worklist.
243     //
244     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
245       assert(New && New->getParent() == 0 &&
246              "New instruction already inserted into a basic block!");
247       BasicBlock *BB = Old.getParent();
248       BB->getInstList().insert(&Old, New);  // Insert inst
249       AddToWorkList(New);
250       return New;
251     }
252
253     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254     /// This also adds the cast to the worklist.  Finally, this returns the
255     /// cast.
256     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257                             Instruction &Pos) {
258       if (V->getType() == Ty) return V;
259
260       if (Constant *CV = dyn_cast<Constant>(V))
261         return ConstantExpr::getCast(opc, CV, Ty);
262       
263       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
264       AddToWorkList(C);
265       return C;
266     }
267
268     // ReplaceInstUsesWith - This method is to be used when an instruction is
269     // found to be dead, replacable with another preexisting expression.  Here
270     // we add all uses of I to the worklist, replace all uses of I with the new
271     // value, then return I, so that the inst combiner will know that I was
272     // modified.
273     //
274     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
275       AddUsersToWorkList(I);         // Add all modified instrs to worklist
276       if (&I != V) {
277         I.replaceAllUsesWith(V);
278         return &I;
279       } else {
280         // If we are replacing the instruction with itself, this must be in a
281         // segment of unreachable code, so just clobber the instruction.
282         I.replaceAllUsesWith(UndefValue::get(I.getType()));
283         return &I;
284       }
285     }
286
287     // UpdateValueUsesWith - This method is to be used when an value is
288     // found to be replacable with another preexisting expression or was
289     // updated.  Here we add all uses of I to the worklist, replace all uses of
290     // I with the new value (unless the instruction was just updated), then
291     // return true, so that the inst combiner will know that I was modified.
292     //
293     bool UpdateValueUsesWith(Value *Old, Value *New) {
294       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
295       if (Old != New)
296         Old->replaceAllUsesWith(New);
297       if (Instruction *I = dyn_cast<Instruction>(Old))
298         AddToWorkList(I);
299       if (Instruction *I = dyn_cast<Instruction>(New))
300         AddToWorkList(I);
301       return true;
302     }
303     
304     // EraseInstFromFunction - When dealing with an instruction that has side
305     // effects or produces a void value, we can't rely on DCE to delete the
306     // instruction.  Instead, visit methods should return the value returned by
307     // this function.
308     Instruction *EraseInstFromFunction(Instruction &I) {
309       assert(I.use_empty() && "Cannot erase instruction that is used!");
310       AddUsesToWorkList(I);
311       RemoveFromWorkList(&I);
312       I.eraseFromParent();
313       return 0;  // Don't do anything with FI
314     }
315
316   private:
317     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
318     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
319     /// casts that are known to not do anything...
320     ///
321     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
322                                    Value *V, const Type *DestTy,
323                                    Instruction *InsertBefore);
324
325     /// SimplifyCommutative - This performs a few simplifications for 
326     /// commutative operators.
327     bool SimplifyCommutative(BinaryOperator &I);
328
329     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
330     /// most-complex to least-complex order.
331     bool SimplifyCompare(CmpInst &I);
332
333     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
334     /// on the demanded bits.
335     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
336                               APInt& KnownZero, APInt& KnownOne,
337                               unsigned Depth = 0);
338
339     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
340                                       uint64_t &UndefElts, unsigned Depth = 0);
341       
342     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
343     // PHI node as operand #0, see if we can fold the instruction into the PHI
344     // (which is only possible if all operands to the PHI are constants).
345     Instruction *FoldOpIntoPhi(Instruction &I);
346
347     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
348     // operator and they all are only used by the PHI, PHI together their
349     // inputs, and do the operation once, to the result of the PHI.
350     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
351     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
352     
353     
354     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
355                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
356     
357     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
358                               bool isSub, Instruction &I);
359     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
360                                  bool isSigned, bool Inside, Instruction &IB);
361     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
362     Instruction *MatchBSwap(BinaryOperator &I);
363     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
364
365     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
366   };
367
368   char InstCombiner::ID = 0;
369   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
370 }
371
372 // getComplexity:  Assign a complexity or rank value to LLVM Values...
373 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
374 static unsigned getComplexity(Value *V) {
375   if (isa<Instruction>(V)) {
376     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
377       return 3;
378     return 4;
379   }
380   if (isa<Argument>(V)) return 3;
381   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
382 }
383
384 // isOnlyUse - Return true if this instruction will be deleted if we stop using
385 // it.
386 static bool isOnlyUse(Value *V) {
387   return V->hasOneUse() || isa<Constant>(V);
388 }
389
390 // getPromotedType - Return the specified type promoted as it would be to pass
391 // though a va_arg area...
392 static const Type *getPromotedType(const Type *Ty) {
393   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
394     if (ITy->getBitWidth() < 32)
395       return Type::Int32Ty;
396   }
397   return Ty;
398 }
399
400 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
401 /// expression bitcast,  return the operand value, otherwise return null.
402 static Value *getBitCastOperand(Value *V) {
403   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
404     return I->getOperand(0);
405   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
406     if (CE->getOpcode() == Instruction::BitCast)
407       return CE->getOperand(0);
408   return 0;
409 }
410
411 /// This function is a wrapper around CastInst::isEliminableCastPair. It
412 /// simply extracts arguments and returns what that function returns.
413 static Instruction::CastOps 
414 isEliminableCastPair(
415   const CastInst *CI, ///< The first cast instruction
416   unsigned opcode,       ///< The opcode of the second cast instruction
417   const Type *DstTy,     ///< The target type for the second cast instruction
418   TargetData *TD         ///< The target data for pointer size
419 ) {
420   
421   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
422   const Type *MidTy = CI->getType();                  // B from above
423
424   // Get the opcodes of the two Cast instructions
425   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
426   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
427
428   return Instruction::CastOps(
429       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
430                                      DstTy, TD->getIntPtrType()));
431 }
432
433 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
434 /// in any code being generated.  It does not require codegen if V is simple
435 /// enough or if the cast can be folded into other casts.
436 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
437                               const Type *Ty, TargetData *TD) {
438   if (V->getType() == Ty || isa<Constant>(V)) return false;
439   
440   // If this is another cast that can be eliminated, it isn't codegen either.
441   if (const CastInst *CI = dyn_cast<CastInst>(V))
442     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
443       return false;
444   return true;
445 }
446
447 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
448 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
449 /// casts that are known to not do anything...
450 ///
451 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
452                                              Value *V, const Type *DestTy,
453                                              Instruction *InsertBefore) {
454   if (V->getType() == DestTy) return V;
455   if (Constant *C = dyn_cast<Constant>(V))
456     return ConstantExpr::getCast(opcode, C, DestTy);
457   
458   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
459 }
460
461 // SimplifyCommutative - This performs a few simplifications for commutative
462 // operators:
463 //
464 //  1. Order operands such that they are listed from right (least complex) to
465 //     left (most complex).  This puts constants before unary operators before
466 //     binary operators.
467 //
468 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
469 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
470 //
471 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
472   bool Changed = false;
473   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
474     Changed = !I.swapOperands();
475
476   if (!I.isAssociative()) return Changed;
477   Instruction::BinaryOps Opcode = I.getOpcode();
478   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
479     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
480       if (isa<Constant>(I.getOperand(1))) {
481         Constant *Folded = ConstantExpr::get(I.getOpcode(),
482                                              cast<Constant>(I.getOperand(1)),
483                                              cast<Constant>(Op->getOperand(1)));
484         I.setOperand(0, Op->getOperand(0));
485         I.setOperand(1, Folded);
486         return true;
487       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
488         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
489             isOnlyUse(Op) && isOnlyUse(Op1)) {
490           Constant *C1 = cast<Constant>(Op->getOperand(1));
491           Constant *C2 = cast<Constant>(Op1->getOperand(1));
492
493           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
494           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
495           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
496                                                     Op1->getOperand(0),
497                                                     Op1->getName(), &I);
498           AddToWorkList(New);
499           I.setOperand(0, New);
500           I.setOperand(1, Folded);
501           return true;
502         }
503     }
504   return Changed;
505 }
506
507 /// SimplifyCompare - For a CmpInst this function just orders the operands
508 /// so that theyare listed from right (least complex) to left (most complex).
509 /// This puts constants before unary operators before binary operators.
510 bool InstCombiner::SimplifyCompare(CmpInst &I) {
511   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
512     return false;
513   I.swapOperands();
514   // Compare instructions are not associative so there's nothing else we can do.
515   return true;
516 }
517
518 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
519 // if the LHS is a constant zero (which is the 'negate' form).
520 //
521 static inline Value *dyn_castNegVal(Value *V) {
522   if (BinaryOperator::isNeg(V))
523     return BinaryOperator::getNegArgument(V);
524
525   // Constants can be considered to be negated values if they can be folded.
526   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
527     return ConstantExpr::getNeg(C);
528   return 0;
529 }
530
531 static inline Value *dyn_castNotVal(Value *V) {
532   if (BinaryOperator::isNot(V))
533     return BinaryOperator::getNotArgument(V);
534
535   // Constants can be considered to be not'ed values...
536   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
537     return ConstantInt::get(~C->getValue());
538   return 0;
539 }
540
541 // dyn_castFoldableMul - If this value is a multiply that can be folded into
542 // other computations (because it has a constant operand), return the
543 // non-constant operand of the multiply, and set CST to point to the multiplier.
544 // Otherwise, return null.
545 //
546 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
547   if (V->hasOneUse() && V->getType()->isInteger())
548     if (Instruction *I = dyn_cast<Instruction>(V)) {
549       if (I->getOpcode() == Instruction::Mul)
550         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
551           return I->getOperand(0);
552       if (I->getOpcode() == Instruction::Shl)
553         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
554           // The multiplier is really 1 << CST.
555           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
556           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
557           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
558           return I->getOperand(0);
559         }
560     }
561   return 0;
562 }
563
564 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565 /// expression, return it.
566 static User *dyn_castGetElementPtr(Value *V) {
567   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569     if (CE->getOpcode() == Instruction::GetElementPtr)
570       return cast<User>(V);
571   return false;
572 }
573
574 /// AddOne - Add one to a ConstantInt
575 static ConstantInt *AddOne(ConstantInt *C) {
576   APInt Val(C->getValue());
577   return ConstantInt::get(++Val);
578 }
579 /// SubOne - Subtract one from a ConstantInt
580 static ConstantInt *SubOne(ConstantInt *C) {
581   APInt Val(C->getValue());
582   return ConstantInt::get(--Val);
583 }
584 /// Add - Add two ConstantInts together
585 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
586   return ConstantInt::get(C1->getValue() + C2->getValue());
587 }
588 /// And - Bitwise AND two ConstantInts together
589 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
590   return ConstantInt::get(C1->getValue() & C2->getValue());
591 }
592 /// Subtract - Subtract one ConstantInt from another
593 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
594   return ConstantInt::get(C1->getValue() - C2->getValue());
595 }
596 /// Multiply - Multiply two ConstantInts together
597 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
598   return ConstantInt::get(C1->getValue() * C2->getValue());
599 }
600
601 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
602 /// known to be either zero or one and return them in the KnownZero/KnownOne
603 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
604 /// processing.
605 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
606 /// we cannot optimize based on the assumption that it is zero without changing
607 /// it to be an explicit zero.  If we don't change it to zero, other code could
608 /// optimized based on the contradictory assumption that it is non-zero.
609 /// Because instcombine aggressively folds operations with undef args anyway,
610 /// this won't lose us code quality.
611 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
612                               APInt& KnownOne, unsigned Depth = 0) {
613   assert(V && "No Value?");
614   assert(Depth <= 6 && "Limit Search Depth");
615   uint32_t BitWidth = Mask.getBitWidth();
616   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
617          KnownZero.getBitWidth() == BitWidth && 
618          KnownOne.getBitWidth() == BitWidth &&
619          "V, Mask, KnownOne and KnownZero should have same BitWidth");
620   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
621     // We know all of the bits for a constant!
622     KnownOne = CI->getValue() & Mask;
623     KnownZero = ~KnownOne & Mask;
624     return;
625   }
626
627   if (Depth == 6 || Mask == 0)
628     return;  // Limit search depth.
629
630   Instruction *I = dyn_cast<Instruction>(V);
631   if (!I) return;
632
633   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
634   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
635   
636   switch (I->getOpcode()) {
637   case Instruction::And: {
638     // If either the LHS or the RHS are Zero, the result is zero.
639     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
640     APInt Mask2(Mask & ~KnownZero);
641     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
642     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
643     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
644     
645     // Output known-1 bits are only known if set in both the LHS & RHS.
646     KnownOne &= KnownOne2;
647     // Output known-0 are known to be clear if zero in either the LHS | RHS.
648     KnownZero |= KnownZero2;
649     return;
650   }
651   case Instruction::Or: {
652     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
653     APInt Mask2(Mask & ~KnownOne);
654     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
655     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
656     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
657     
658     // Output known-0 bits are only known if clear in both the LHS & RHS.
659     KnownZero &= KnownZero2;
660     // Output known-1 are known to be set if set in either the LHS | RHS.
661     KnownOne |= KnownOne2;
662     return;
663   }
664   case Instruction::Xor: {
665     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
666     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
667     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
668     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
669     
670     // Output known-0 bits are known if clear or set in both the LHS & RHS.
671     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
672     // Output known-1 are known to be set if set in only one of the LHS, RHS.
673     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
674     KnownZero = KnownZeroOut;
675     return;
676   }
677   case Instruction::Select:
678     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
679     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
680     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
681     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
682
683     // Only known if known in both the LHS and RHS.
684     KnownOne &= KnownOne2;
685     KnownZero &= KnownZero2;
686     return;
687   case Instruction::FPTrunc:
688   case Instruction::FPExt:
689   case Instruction::FPToUI:
690   case Instruction::FPToSI:
691   case Instruction::SIToFP:
692   case Instruction::PtrToInt:
693   case Instruction::UIToFP:
694   case Instruction::IntToPtr:
695     return; // Can't work with floating point or pointers
696   case Instruction::Trunc: {
697     // All these have integer operands
698     uint32_t SrcBitWidth = 
699       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
700     APInt MaskIn(Mask);
701     MaskIn.zext(SrcBitWidth);
702     KnownZero.zext(SrcBitWidth);
703     KnownOne.zext(SrcBitWidth);
704     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
705     KnownZero.trunc(BitWidth);
706     KnownOne.trunc(BitWidth);
707     return;
708   }
709   case Instruction::BitCast: {
710     const Type *SrcTy = I->getOperand(0)->getType();
711     if (SrcTy->isInteger()) {
712       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
713       return;
714     }
715     break;
716   }
717   case Instruction::ZExt:  {
718     // Compute the bits in the result that are not present in the input.
719     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
720     uint32_t SrcBitWidth = SrcTy->getBitWidth();
721       
722     APInt MaskIn(Mask);
723     MaskIn.trunc(SrcBitWidth);
724     KnownZero.trunc(SrcBitWidth);
725     KnownOne.trunc(SrcBitWidth);
726     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
727     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
728     // The top bits are known to be zero.
729     KnownZero.zext(BitWidth);
730     KnownOne.zext(BitWidth);
731     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
732     return;
733   }
734   case Instruction::SExt: {
735     // Compute the bits in the result that are not present in the input.
736     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
737     uint32_t SrcBitWidth = SrcTy->getBitWidth();
738       
739     APInt MaskIn(Mask); 
740     MaskIn.trunc(SrcBitWidth);
741     KnownZero.trunc(SrcBitWidth);
742     KnownOne.trunc(SrcBitWidth);
743     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
744     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
745     KnownZero.zext(BitWidth);
746     KnownOne.zext(BitWidth);
747
748     // If the sign bit of the input is known set or clear, then we know the
749     // top bits of the result.
750     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
751       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
752     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
753       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
754     return;
755   }
756   case Instruction::Shl:
757     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
758     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
759       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
760       APInt Mask2(Mask.lshr(ShiftAmt));
761       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
762       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
763       KnownZero <<= ShiftAmt;
764       KnownOne  <<= ShiftAmt;
765       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
766       return;
767     }
768     break;
769   case Instruction::LShr:
770     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
771     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
772       // Compute the new bits that are at the top now.
773       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
774       
775       // Unsigned shift right.
776       APInt Mask2(Mask.shl(ShiftAmt));
777       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
778       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
779       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
780       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
781       // high bits known zero.
782       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
783       return;
784     }
785     break;
786   case Instruction::AShr:
787     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
788     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
789       // Compute the new bits that are at the top now.
790       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
791       
792       // Signed shift right.
793       APInt Mask2(Mask.shl(ShiftAmt));
794       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
795       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
796       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
797       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
798         
799       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
800       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
801         KnownZero |= HighBits;
802       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
803         KnownOne |= HighBits;
804       return;
805     }
806     break;
807   }
808 }
809
810 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
811 /// this predicate to simplify operations downstream.  Mask is known to be zero
812 /// for bits that V cannot have.
813 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
814   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
815   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
816   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
817   return (KnownZero & Mask) == Mask;
818 }
819
820 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
821 /// specified instruction is a constant integer.  If so, check to see if there
822 /// are any bits set in the constant that are not demanded.  If so, shrink the
823 /// constant and return true.
824 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
825                                    APInt Demanded) {
826   assert(I && "No instruction?");
827   assert(OpNo < I->getNumOperands() && "Operand index too large");
828
829   // If the operand is not a constant integer, nothing to do.
830   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
831   if (!OpC) return false;
832
833   // If there are no bits set that aren't demanded, nothing to do.
834   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
835   if ((~Demanded & OpC->getValue()) == 0)
836     return false;
837
838   // This instruction is producing bits that are not demanded. Shrink the RHS.
839   Demanded &= OpC->getValue();
840   I->setOperand(OpNo, ConstantInt::get(Demanded));
841   return true;
842 }
843
844 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
845 // set of known zero and one bits, compute the maximum and minimum values that
846 // could have the specified known zero and known one bits, returning them in
847 // min/max.
848 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
849                                                    const APInt& KnownZero,
850                                                    const APInt& KnownOne,
851                                                    APInt& Min, APInt& Max) {
852   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
853   assert(KnownZero.getBitWidth() == BitWidth && 
854          KnownOne.getBitWidth() == BitWidth &&
855          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
856          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
857   APInt UnknownBits = ~(KnownZero|KnownOne);
858
859   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
860   // bit if it is unknown.
861   Min = KnownOne;
862   Max = KnownOne|UnknownBits;
863   
864   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
865     Min.set(BitWidth-1);
866     Max.clear(BitWidth-1);
867   }
868 }
869
870 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
871 // a set of known zero and one bits, compute the maximum and minimum values that
872 // could have the specified known zero and known one bits, returning them in
873 // min/max.
874 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
875                                                      const APInt &KnownZero,
876                                                      const APInt &KnownOne,
877                                                      APInt &Min, APInt &Max) {
878   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
879   assert(KnownZero.getBitWidth() == BitWidth && 
880          KnownOne.getBitWidth() == BitWidth &&
881          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
882          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
883   APInt UnknownBits = ~(KnownZero|KnownOne);
884   
885   // The minimum value is when the unknown bits are all zeros.
886   Min = KnownOne;
887   // The maximum value is when the unknown bits are all ones.
888   Max = KnownOne|UnknownBits;
889 }
890
891 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
892 /// value based on the demanded bits. When this function is called, it is known
893 /// that only the bits set in DemandedMask of the result of V are ever used
894 /// downstream. Consequently, depending on the mask and V, it may be possible
895 /// to replace V with a constant or one of its operands. In such cases, this
896 /// function does the replacement and returns true. In all other cases, it
897 /// returns false after analyzing the expression and setting KnownOne and known
898 /// to be one in the expression. KnownZero contains all the bits that are known
899 /// to be zero in the expression. These are provided to potentially allow the
900 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
901 /// the expression. KnownOne and KnownZero always follow the invariant that 
902 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
903 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
904 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
905 /// and KnownOne must all be the same.
906 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
907                                         APInt& KnownZero, APInt& KnownOne,
908                                         unsigned Depth) {
909   assert(V != 0 && "Null pointer of Value???");
910   assert(Depth <= 6 && "Limit Search Depth");
911   uint32_t BitWidth = DemandedMask.getBitWidth();
912   const IntegerType *VTy = cast<IntegerType>(V->getType());
913   assert(VTy->getBitWidth() == BitWidth && 
914          KnownZero.getBitWidth() == BitWidth && 
915          KnownOne.getBitWidth() == BitWidth &&
916          "Value *V, DemandedMask, KnownZero and KnownOne \
917           must have same BitWidth");
918   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
919     // We know all of the bits for a constant!
920     KnownOne = CI->getValue() & DemandedMask;
921     KnownZero = ~KnownOne & DemandedMask;
922     return false;
923   }
924   
925   KnownZero.clear(); 
926   KnownOne.clear();
927   if (!V->hasOneUse()) {    // Other users may use these bits.
928     if (Depth != 0) {       // Not at the root.
929       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
930       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
931       return false;
932     }
933     // If this is the root being simplified, allow it to have multiple uses,
934     // just set the DemandedMask to all bits.
935     DemandedMask = APInt::getAllOnesValue(BitWidth);
936   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
937     if (V != UndefValue::get(VTy))
938       return UpdateValueUsesWith(V, UndefValue::get(VTy));
939     return false;
940   } else if (Depth == 6) {        // Limit search depth.
941     return false;
942   }
943   
944   Instruction *I = dyn_cast<Instruction>(V);
945   if (!I) return false;        // Only analyze instructions.
946
947   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
948   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
949   switch (I->getOpcode()) {
950   default: break;
951   case Instruction::And:
952     // If either the LHS or the RHS are Zero, the result is zero.
953     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
954                              RHSKnownZero, RHSKnownOne, Depth+1))
955       return true;
956     assert((RHSKnownZero & RHSKnownOne) == 0 && 
957            "Bits known to be one AND zero?"); 
958
959     // If something is known zero on the RHS, the bits aren't demanded on the
960     // LHS.
961     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
962                              LHSKnownZero, LHSKnownOne, Depth+1))
963       return true;
964     assert((LHSKnownZero & LHSKnownOne) == 0 && 
965            "Bits known to be one AND zero?"); 
966
967     // If all of the demanded bits are known 1 on one side, return the other.
968     // These bits cannot contribute to the result of the 'and'.
969     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
970         (DemandedMask & ~LHSKnownZero))
971       return UpdateValueUsesWith(I, I->getOperand(0));
972     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
973         (DemandedMask & ~RHSKnownZero))
974       return UpdateValueUsesWith(I, I->getOperand(1));
975     
976     // If all of the demanded bits in the inputs are known zeros, return zero.
977     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
978       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
979       
980     // If the RHS is a constant, see if we can simplify it.
981     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
982       return UpdateValueUsesWith(I, I);
983       
984     // Output known-1 bits are only known if set in both the LHS & RHS.
985     RHSKnownOne &= LHSKnownOne;
986     // Output known-0 are known to be clear if zero in either the LHS | RHS.
987     RHSKnownZero |= LHSKnownZero;
988     break;
989   case Instruction::Or:
990     // If either the LHS or the RHS are One, the result is One.
991     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
992                              RHSKnownZero, RHSKnownOne, Depth+1))
993       return true;
994     assert((RHSKnownZero & RHSKnownOne) == 0 && 
995            "Bits known to be one AND zero?"); 
996     // If something is known one on the RHS, the bits aren't demanded on the
997     // LHS.
998     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
999                              LHSKnownZero, LHSKnownOne, Depth+1))
1000       return true;
1001     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1002            "Bits known to be one AND zero?"); 
1003     
1004     // If all of the demanded bits are known zero on one side, return the other.
1005     // These bits cannot contribute to the result of the 'or'.
1006     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1007         (DemandedMask & ~LHSKnownOne))
1008       return UpdateValueUsesWith(I, I->getOperand(0));
1009     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1010         (DemandedMask & ~RHSKnownOne))
1011       return UpdateValueUsesWith(I, I->getOperand(1));
1012
1013     // If all of the potentially set bits on one side are known to be set on
1014     // the other side, just use the 'other' side.
1015     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1016         (DemandedMask & (~RHSKnownZero)))
1017       return UpdateValueUsesWith(I, I->getOperand(0));
1018     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1019         (DemandedMask & (~LHSKnownZero)))
1020       return UpdateValueUsesWith(I, I->getOperand(1));
1021         
1022     // If the RHS is a constant, see if we can simplify it.
1023     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1024       return UpdateValueUsesWith(I, I);
1025           
1026     // Output known-0 bits are only known if clear in both the LHS & RHS.
1027     RHSKnownZero &= LHSKnownZero;
1028     // Output known-1 are known to be set if set in either the LHS | RHS.
1029     RHSKnownOne |= LHSKnownOne;
1030     break;
1031   case Instruction::Xor: {
1032     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1033                              RHSKnownZero, RHSKnownOne, Depth+1))
1034       return true;
1035     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1036            "Bits known to be one AND zero?"); 
1037     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1038                              LHSKnownZero, LHSKnownOne, Depth+1))
1039       return true;
1040     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1041            "Bits known to be one AND zero?"); 
1042     
1043     // If all of the demanded bits are known zero on one side, return the other.
1044     // These bits cannot contribute to the result of the 'xor'.
1045     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1046       return UpdateValueUsesWith(I, I->getOperand(0));
1047     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1048       return UpdateValueUsesWith(I, I->getOperand(1));
1049     
1050     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1051     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1052                          (RHSKnownOne & LHSKnownOne);
1053     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1054     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1055                         (RHSKnownOne & LHSKnownZero);
1056     
1057     // If all of the demanded bits are known to be zero on one side or the
1058     // other, turn this into an *inclusive* or.
1059     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1060     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1061       Instruction *Or =
1062         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1063                                  I->getName());
1064       InsertNewInstBefore(Or, *I);
1065       return UpdateValueUsesWith(I, Or);
1066     }
1067     
1068     // If all of the demanded bits on one side are known, and all of the set
1069     // bits on that side are also known to be set on the other side, turn this
1070     // into an AND, as we know the bits will be cleared.
1071     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1072     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1073       // all known
1074       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1075         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1076         Instruction *And = 
1077           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1078         InsertNewInstBefore(And, *I);
1079         return UpdateValueUsesWith(I, And);
1080       }
1081     }
1082     
1083     // If the RHS is a constant, see if we can simplify it.
1084     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1085     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1086       return UpdateValueUsesWith(I, I);
1087     
1088     RHSKnownZero = KnownZeroOut;
1089     RHSKnownOne  = KnownOneOut;
1090     break;
1091   }
1092   case Instruction::Select:
1093     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1094                              RHSKnownZero, RHSKnownOne, Depth+1))
1095       return true;
1096     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1097                              LHSKnownZero, LHSKnownOne, Depth+1))
1098       return true;
1099     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1100            "Bits known to be one AND zero?"); 
1101     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1102            "Bits known to be one AND zero?"); 
1103     
1104     // If the operands are constants, see if we can simplify them.
1105     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1106       return UpdateValueUsesWith(I, I);
1107     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1108       return UpdateValueUsesWith(I, I);
1109     
1110     // Only known if known in both the LHS and RHS.
1111     RHSKnownOne &= LHSKnownOne;
1112     RHSKnownZero &= LHSKnownZero;
1113     break;
1114   case Instruction::Trunc: {
1115     uint32_t truncBf = 
1116       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1117     DemandedMask.zext(truncBf);
1118     RHSKnownZero.zext(truncBf);
1119     RHSKnownOne.zext(truncBf);
1120     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1121                              RHSKnownZero, RHSKnownOne, Depth+1))
1122       return true;
1123     DemandedMask.trunc(BitWidth);
1124     RHSKnownZero.trunc(BitWidth);
1125     RHSKnownOne.trunc(BitWidth);
1126     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1127            "Bits known to be one AND zero?"); 
1128     break;
1129   }
1130   case Instruction::BitCast:
1131     if (!I->getOperand(0)->getType()->isInteger())
1132       return false;
1133       
1134     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1135                              RHSKnownZero, RHSKnownOne, Depth+1))
1136       return true;
1137     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1138            "Bits known to be one AND zero?"); 
1139     break;
1140   case Instruction::ZExt: {
1141     // Compute the bits in the result that are not present in the input.
1142     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1143     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1144     
1145     DemandedMask.trunc(SrcBitWidth);
1146     RHSKnownZero.trunc(SrcBitWidth);
1147     RHSKnownOne.trunc(SrcBitWidth);
1148     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1149                              RHSKnownZero, RHSKnownOne, Depth+1))
1150       return true;
1151     DemandedMask.zext(BitWidth);
1152     RHSKnownZero.zext(BitWidth);
1153     RHSKnownOne.zext(BitWidth);
1154     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1155            "Bits known to be one AND zero?"); 
1156     // The top bits are known to be zero.
1157     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1158     break;
1159   }
1160   case Instruction::SExt: {
1161     // Compute the bits in the result that are not present in the input.
1162     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1163     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1164     
1165     APInt InputDemandedBits = DemandedMask & 
1166                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1167
1168     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1169     // If any of the sign extended bits are demanded, we know that the sign
1170     // bit is demanded.
1171     if ((NewBits & DemandedMask) != 0)
1172       InputDemandedBits.set(SrcBitWidth-1);
1173       
1174     InputDemandedBits.trunc(SrcBitWidth);
1175     RHSKnownZero.trunc(SrcBitWidth);
1176     RHSKnownOne.trunc(SrcBitWidth);
1177     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1178                              RHSKnownZero, RHSKnownOne, Depth+1))
1179       return true;
1180     InputDemandedBits.zext(BitWidth);
1181     RHSKnownZero.zext(BitWidth);
1182     RHSKnownOne.zext(BitWidth);
1183     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1184            "Bits known to be one AND zero?"); 
1185       
1186     // If the sign bit of the input is known set or clear, then we know the
1187     // top bits of the result.
1188
1189     // If the input sign bit is known zero, or if the NewBits are not demanded
1190     // convert this into a zero extension.
1191     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1192     {
1193       // Convert to ZExt cast
1194       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1195       return UpdateValueUsesWith(I, NewCast);
1196     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1197       RHSKnownOne |= NewBits;
1198     }
1199     break;
1200   }
1201   case Instruction::Add: {
1202     // Figure out what the input bits are.  If the top bits of the and result
1203     // are not demanded, then the add doesn't demand them from its input
1204     // either.
1205     uint32_t NLZ = DemandedMask.countLeadingZeros();
1206       
1207     // If there is a constant on the RHS, there are a variety of xformations
1208     // we can do.
1209     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1210       // If null, this should be simplified elsewhere.  Some of the xforms here
1211       // won't work if the RHS is zero.
1212       if (RHS->isZero())
1213         break;
1214       
1215       // If the top bit of the output is demanded, demand everything from the
1216       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1217       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1218
1219       // Find information about known zero/one bits in the input.
1220       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1221                                LHSKnownZero, LHSKnownOne, Depth+1))
1222         return true;
1223
1224       // If the RHS of the add has bits set that can't affect the input, reduce
1225       // the constant.
1226       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1227         return UpdateValueUsesWith(I, I);
1228       
1229       // Avoid excess work.
1230       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1231         break;
1232       
1233       // Turn it into OR if input bits are zero.
1234       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1235         Instruction *Or =
1236           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1237                                    I->getName());
1238         InsertNewInstBefore(Or, *I);
1239         return UpdateValueUsesWith(I, Or);
1240       }
1241       
1242       // We can say something about the output known-zero and known-one bits,
1243       // depending on potential carries from the input constant and the
1244       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1245       // bits set and the RHS constant is 0x01001, then we know we have a known
1246       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1247       
1248       // To compute this, we first compute the potential carry bits.  These are
1249       // the bits which may be modified.  I'm not aware of a better way to do
1250       // this scan.
1251       const APInt& RHSVal = RHS->getValue();
1252       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1253       
1254       // Now that we know which bits have carries, compute the known-1/0 sets.
1255       
1256       // Bits are known one if they are known zero in one operand and one in the
1257       // other, and there is no input carry.
1258       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1259                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1260       
1261       // Bits are known zero if they are known zero in both operands and there
1262       // is no input carry.
1263       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1264     } else {
1265       // If the high-bits of this ADD are not demanded, then it does not demand
1266       // the high bits of its LHS or RHS.
1267       if (DemandedMask[BitWidth-1] == 0) {
1268         // Right fill the mask of bits for this ADD to demand the most
1269         // significant bit and all those below it.
1270         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1271         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1272                                  LHSKnownZero, LHSKnownOne, Depth+1))
1273           return true;
1274         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1275                                  LHSKnownZero, LHSKnownOne, Depth+1))
1276           return true;
1277       }
1278     }
1279     break;
1280   }
1281   case Instruction::Sub:
1282     // If the high-bits of this SUB are not demanded, then it does not demand
1283     // the high bits of its LHS or RHS.
1284     if (DemandedMask[BitWidth-1] == 0) {
1285       // Right fill the mask of bits for this SUB to demand the most
1286       // significant bit and all those below it.
1287       uint32_t NLZ = DemandedMask.countLeadingZeros();
1288       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1289       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1290                                LHSKnownZero, LHSKnownOne, Depth+1))
1291         return true;
1292       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1293                                LHSKnownZero, LHSKnownOne, Depth+1))
1294         return true;
1295     }
1296     break;
1297   case Instruction::Shl:
1298     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1299       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1300       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1301       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1302                                RHSKnownZero, RHSKnownOne, Depth+1))
1303         return true;
1304       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1305              "Bits known to be one AND zero?"); 
1306       RHSKnownZero <<= ShiftAmt;
1307       RHSKnownOne  <<= ShiftAmt;
1308       // low bits known zero.
1309       if (ShiftAmt)
1310         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1311     }
1312     break;
1313   case Instruction::LShr:
1314     // For a logical shift right
1315     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1316       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1317       
1318       // Unsigned shift right.
1319       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1320       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1321                                RHSKnownZero, RHSKnownOne, Depth+1))
1322         return true;
1323       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1324              "Bits known to be one AND zero?"); 
1325       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1326       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1327       if (ShiftAmt) {
1328         // Compute the new bits that are at the top now.
1329         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1330         RHSKnownZero |= HighBits;  // high bits known zero.
1331       }
1332     }
1333     break;
1334   case Instruction::AShr:
1335     // If this is an arithmetic shift right and only the low-bit is set, we can
1336     // always convert this into a logical shr, even if the shift amount is
1337     // variable.  The low bit of the shift cannot be an input sign bit unless
1338     // the shift amount is >= the size of the datatype, which is undefined.
1339     if (DemandedMask == 1) {
1340       // Perform the logical shift right.
1341       Value *NewVal = BinaryOperator::createLShr(
1342                         I->getOperand(0), I->getOperand(1), I->getName());
1343       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1344       return UpdateValueUsesWith(I, NewVal);
1345     }    
1346
1347     // If the sign bit is the only bit demanded by this ashr, then there is no
1348     // need to do it, the shift doesn't change the high bit.
1349     if (DemandedMask.isSignBit())
1350       return UpdateValueUsesWith(I, I->getOperand(0));
1351     
1352     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1353       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1354       
1355       // Signed shift right.
1356       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1357       // If any of the "high bits" are demanded, we should set the sign bit as
1358       // demanded.
1359       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1360         DemandedMaskIn.set(BitWidth-1);
1361       if (SimplifyDemandedBits(I->getOperand(0),
1362                                DemandedMaskIn,
1363                                RHSKnownZero, RHSKnownOne, Depth+1))
1364         return true;
1365       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1366              "Bits known to be one AND zero?"); 
1367       // Compute the new bits that are at the top now.
1368       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1369       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1370       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1371         
1372       // Handle the sign bits.
1373       APInt SignBit(APInt::getSignBit(BitWidth));
1374       // Adjust to where it is now in the mask.
1375       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1376         
1377       // If the input sign bit is known to be zero, or if none of the top bits
1378       // are demanded, turn this into an unsigned shift right.
1379       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1380           (HighBits & ~DemandedMask) == HighBits) {
1381         // Perform the logical shift right.
1382         Value *NewVal = BinaryOperator::createLShr(
1383                           I->getOperand(0), SA, I->getName());
1384         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1385         return UpdateValueUsesWith(I, NewVal);
1386       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1387         RHSKnownOne |= HighBits;
1388       }
1389     }
1390     break;
1391   }
1392   
1393   // If the client is only demanding bits that we know, return the known
1394   // constant.
1395   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1396     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1397   return false;
1398 }
1399
1400
1401 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1402 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1403 /// actually used by the caller.  This method analyzes which elements of the
1404 /// operand are undef and returns that information in UndefElts.
1405 ///
1406 /// If the information about demanded elements can be used to simplify the
1407 /// operation, the operation is simplified, then the resultant value is
1408 /// returned.  This returns null if no change was made.
1409 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1410                                                 uint64_t &UndefElts,
1411                                                 unsigned Depth) {
1412   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1413   assert(VWidth <= 64 && "Vector too wide to analyze!");
1414   uint64_t EltMask = ~0ULL >> (64-VWidth);
1415   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1416          "Invalid DemandedElts!");
1417
1418   if (isa<UndefValue>(V)) {
1419     // If the entire vector is undefined, just return this info.
1420     UndefElts = EltMask;
1421     return 0;
1422   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1423     UndefElts = EltMask;
1424     return UndefValue::get(V->getType());
1425   }
1426   
1427   UndefElts = 0;
1428   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1429     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1430     Constant *Undef = UndefValue::get(EltTy);
1431
1432     std::vector<Constant*> Elts;
1433     for (unsigned i = 0; i != VWidth; ++i)
1434       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1435         Elts.push_back(Undef);
1436         UndefElts |= (1ULL << i);
1437       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1438         Elts.push_back(Undef);
1439         UndefElts |= (1ULL << i);
1440       } else {                               // Otherwise, defined.
1441         Elts.push_back(CP->getOperand(i));
1442       }
1443         
1444     // If we changed the constant, return it.
1445     Constant *NewCP = ConstantVector::get(Elts);
1446     return NewCP != CP ? NewCP : 0;
1447   } else if (isa<ConstantAggregateZero>(V)) {
1448     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1449     // set to undef.
1450     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1451     Constant *Zero = Constant::getNullValue(EltTy);
1452     Constant *Undef = UndefValue::get(EltTy);
1453     std::vector<Constant*> Elts;
1454     for (unsigned i = 0; i != VWidth; ++i)
1455       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1456     UndefElts = DemandedElts ^ EltMask;
1457     return ConstantVector::get(Elts);
1458   }
1459   
1460   if (!V->hasOneUse()) {    // Other users may use these bits.
1461     if (Depth != 0) {       // Not at the root.
1462       // TODO: Just compute the UndefElts information recursively.
1463       return false;
1464     }
1465     return false;
1466   } else if (Depth == 10) {        // Limit search depth.
1467     return false;
1468   }
1469   
1470   Instruction *I = dyn_cast<Instruction>(V);
1471   if (!I) return false;        // Only analyze instructions.
1472   
1473   bool MadeChange = false;
1474   uint64_t UndefElts2;
1475   Value *TmpV;
1476   switch (I->getOpcode()) {
1477   default: break;
1478     
1479   case Instruction::InsertElement: {
1480     // If this is a variable index, we don't know which element it overwrites.
1481     // demand exactly the same input as we produce.
1482     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1483     if (Idx == 0) {
1484       // Note that we can't propagate undef elt info, because we don't know
1485       // which elt is getting updated.
1486       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1487                                         UndefElts2, Depth+1);
1488       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1489       break;
1490     }
1491     
1492     // If this is inserting an element that isn't demanded, remove this
1493     // insertelement.
1494     unsigned IdxNo = Idx->getZExtValue();
1495     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1496       return AddSoonDeadInstToWorklist(*I, 0);
1497     
1498     // Otherwise, the element inserted overwrites whatever was there, so the
1499     // input demanded set is simpler than the output set.
1500     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1501                                       DemandedElts & ~(1ULL << IdxNo),
1502                                       UndefElts, Depth+1);
1503     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1504
1505     // The inserted element is defined.
1506     UndefElts |= 1ULL << IdxNo;
1507     break;
1508   }
1509   case Instruction::BitCast: {
1510     // Vector->vector casts only.
1511     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1512     if (!VTy) break;
1513     unsigned InVWidth = VTy->getNumElements();
1514     uint64_t InputDemandedElts = 0;
1515     unsigned Ratio;
1516
1517     if (VWidth == InVWidth) {
1518       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1519       // elements as are demanded of us.
1520       Ratio = 1;
1521       InputDemandedElts = DemandedElts;
1522     } else if (VWidth > InVWidth) {
1523       // Untested so far.
1524       break;
1525       
1526       // If there are more elements in the result than there are in the source,
1527       // then an input element is live if any of the corresponding output
1528       // elements are live.
1529       Ratio = VWidth/InVWidth;
1530       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1531         if (DemandedElts & (1ULL << OutIdx))
1532           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1533       }
1534     } else {
1535       // Untested so far.
1536       break;
1537       
1538       // If there are more elements in the source than there are in the result,
1539       // then an input element is live if the corresponding output element is
1540       // live.
1541       Ratio = InVWidth/VWidth;
1542       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1543         if (DemandedElts & (1ULL << InIdx/Ratio))
1544           InputDemandedElts |= 1ULL << InIdx;
1545     }
1546     
1547     // div/rem demand all inputs, because they don't want divide by zero.
1548     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1549                                       UndefElts2, Depth+1);
1550     if (TmpV) {
1551       I->setOperand(0, TmpV);
1552       MadeChange = true;
1553     }
1554     
1555     UndefElts = UndefElts2;
1556     if (VWidth > InVWidth) {
1557       assert(0 && "Unimp");
1558       // If there are more elements in the result than there are in the source,
1559       // then an output element is undef if the corresponding input element is
1560       // undef.
1561       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1562         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1563           UndefElts |= 1ULL << OutIdx;
1564     } else if (VWidth < InVWidth) {
1565       assert(0 && "Unimp");
1566       // If there are more elements in the source than there are in the result,
1567       // then a result element is undef if all of the corresponding input
1568       // elements are undef.
1569       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1570       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1571         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1572           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1573     }
1574     break;
1575   }
1576   case Instruction::And:
1577   case Instruction::Or:
1578   case Instruction::Xor:
1579   case Instruction::Add:
1580   case Instruction::Sub:
1581   case Instruction::Mul:
1582     // div/rem demand all inputs, because they don't want divide by zero.
1583     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1584                                       UndefElts, Depth+1);
1585     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1586     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1587                                       UndefElts2, Depth+1);
1588     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1589       
1590     // Output elements are undefined if both are undefined.  Consider things
1591     // like undef&0.  The result is known zero, not undef.
1592     UndefElts &= UndefElts2;
1593     break;
1594     
1595   case Instruction::Call: {
1596     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1597     if (!II) break;
1598     switch (II->getIntrinsicID()) {
1599     default: break;
1600       
1601     // Binary vector operations that work column-wise.  A dest element is a
1602     // function of the corresponding input elements from the two inputs.
1603     case Intrinsic::x86_sse_sub_ss:
1604     case Intrinsic::x86_sse_mul_ss:
1605     case Intrinsic::x86_sse_min_ss:
1606     case Intrinsic::x86_sse_max_ss:
1607     case Intrinsic::x86_sse2_sub_sd:
1608     case Intrinsic::x86_sse2_mul_sd:
1609     case Intrinsic::x86_sse2_min_sd:
1610     case Intrinsic::x86_sse2_max_sd:
1611       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1612                                         UndefElts, Depth+1);
1613       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1614       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1615                                         UndefElts2, Depth+1);
1616       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1617
1618       // If only the low elt is demanded and this is a scalarizable intrinsic,
1619       // scalarize it now.
1620       if (DemandedElts == 1) {
1621         switch (II->getIntrinsicID()) {
1622         default: break;
1623         case Intrinsic::x86_sse_sub_ss:
1624         case Intrinsic::x86_sse_mul_ss:
1625         case Intrinsic::x86_sse2_sub_sd:
1626         case Intrinsic::x86_sse2_mul_sd:
1627           // TODO: Lower MIN/MAX/ABS/etc
1628           Value *LHS = II->getOperand(1);
1629           Value *RHS = II->getOperand(2);
1630           // Extract the element as scalars.
1631           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1632           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1633           
1634           switch (II->getIntrinsicID()) {
1635           default: assert(0 && "Case stmts out of sync!");
1636           case Intrinsic::x86_sse_sub_ss:
1637           case Intrinsic::x86_sse2_sub_sd:
1638             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1639                                                         II->getName()), *II);
1640             break;
1641           case Intrinsic::x86_sse_mul_ss:
1642           case Intrinsic::x86_sse2_mul_sd:
1643             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1644                                                          II->getName()), *II);
1645             break;
1646           }
1647           
1648           Instruction *New =
1649             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1650                                   II->getName());
1651           InsertNewInstBefore(New, *II);
1652           AddSoonDeadInstToWorklist(*II, 0);
1653           return New;
1654         }            
1655       }
1656         
1657       // Output elements are undefined if both are undefined.  Consider things
1658       // like undef&0.  The result is known zero, not undef.
1659       UndefElts &= UndefElts2;
1660       break;
1661     }
1662     break;
1663   }
1664   }
1665   return MadeChange ? I : 0;
1666 }
1667
1668 /// @returns true if the specified compare predicate is
1669 /// true when both operands are equal...
1670 /// @brief Determine if the icmp Predicate is true when both operands are equal
1671 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1672   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1673          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1674          pred == ICmpInst::ICMP_SLE;
1675 }
1676
1677 /// @returns true if the specified compare instruction is
1678 /// true when both operands are equal...
1679 /// @brief Determine if the ICmpInst returns true when both operands are equal
1680 static bool isTrueWhenEqual(ICmpInst &ICI) {
1681   return isTrueWhenEqual(ICI.getPredicate());
1682 }
1683
1684 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1685 /// function is designed to check a chain of associative operators for a
1686 /// potential to apply a certain optimization.  Since the optimization may be
1687 /// applicable if the expression was reassociated, this checks the chain, then
1688 /// reassociates the expression as necessary to expose the optimization
1689 /// opportunity.  This makes use of a special Functor, which must define
1690 /// 'shouldApply' and 'apply' methods.
1691 ///
1692 template<typename Functor>
1693 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1694   unsigned Opcode = Root.getOpcode();
1695   Value *LHS = Root.getOperand(0);
1696
1697   // Quick check, see if the immediate LHS matches...
1698   if (F.shouldApply(LHS))
1699     return F.apply(Root);
1700
1701   // Otherwise, if the LHS is not of the same opcode as the root, return.
1702   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1703   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1704     // Should we apply this transform to the RHS?
1705     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1706
1707     // If not to the RHS, check to see if we should apply to the LHS...
1708     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1709       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1710       ShouldApply = true;
1711     }
1712
1713     // If the functor wants to apply the optimization to the RHS of LHSI,
1714     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1715     if (ShouldApply) {
1716       BasicBlock *BB = Root.getParent();
1717
1718       // Now all of the instructions are in the current basic block, go ahead
1719       // and perform the reassociation.
1720       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1721
1722       // First move the selected RHS to the LHS of the root...
1723       Root.setOperand(0, LHSI->getOperand(1));
1724
1725       // Make what used to be the LHS of the root be the user of the root...
1726       Value *ExtraOperand = TmpLHSI->getOperand(1);
1727       if (&Root == TmpLHSI) {
1728         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1729         return 0;
1730       }
1731       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1732       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1733       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1734       BasicBlock::iterator ARI = &Root; ++ARI;
1735       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1736       ARI = Root;
1737
1738       // Now propagate the ExtraOperand down the chain of instructions until we
1739       // get to LHSI.
1740       while (TmpLHSI != LHSI) {
1741         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1742         // Move the instruction to immediately before the chain we are
1743         // constructing to avoid breaking dominance properties.
1744         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1745         BB->getInstList().insert(ARI, NextLHSI);
1746         ARI = NextLHSI;
1747
1748         Value *NextOp = NextLHSI->getOperand(1);
1749         NextLHSI->setOperand(1, ExtraOperand);
1750         TmpLHSI = NextLHSI;
1751         ExtraOperand = NextOp;
1752       }
1753
1754       // Now that the instructions are reassociated, have the functor perform
1755       // the transformation...
1756       return F.apply(Root);
1757     }
1758
1759     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1760   }
1761   return 0;
1762 }
1763
1764
1765 // AddRHS - Implements: X + X --> X << 1
1766 struct AddRHS {
1767   Value *RHS;
1768   AddRHS(Value *rhs) : RHS(rhs) {}
1769   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1770   Instruction *apply(BinaryOperator &Add) const {
1771     return BinaryOperator::createShl(Add.getOperand(0),
1772                                   ConstantInt::get(Add.getType(), 1));
1773   }
1774 };
1775
1776 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1777 //                 iff C1&C2 == 0
1778 struct AddMaskingAnd {
1779   Constant *C2;
1780   AddMaskingAnd(Constant *c) : C2(c) {}
1781   bool shouldApply(Value *LHS) const {
1782     ConstantInt *C1;
1783     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1784            ConstantExpr::getAnd(C1, C2)->isNullValue();
1785   }
1786   Instruction *apply(BinaryOperator &Add) const {
1787     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1788   }
1789 };
1790
1791 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1792                                              InstCombiner *IC) {
1793   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1794     if (Constant *SOC = dyn_cast<Constant>(SO))
1795       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1796
1797     return IC->InsertNewInstBefore(CastInst::create(
1798           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1799   }
1800
1801   // Figure out if the constant is the left or the right argument.
1802   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1803   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1804
1805   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1806     if (ConstIsRHS)
1807       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1808     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1809   }
1810
1811   Value *Op0 = SO, *Op1 = ConstOperand;
1812   if (!ConstIsRHS)
1813     std::swap(Op0, Op1);
1814   Instruction *New;
1815   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1816     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1817   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1818     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1819                           SO->getName()+".cmp");
1820   else {
1821     assert(0 && "Unknown binary instruction type!");
1822     abort();
1823   }
1824   return IC->InsertNewInstBefore(New, I);
1825 }
1826
1827 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1828 // constant as the other operand, try to fold the binary operator into the
1829 // select arguments.  This also works for Cast instructions, which obviously do
1830 // not have a second operand.
1831 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1832                                      InstCombiner *IC) {
1833   // Don't modify shared select instructions
1834   if (!SI->hasOneUse()) return 0;
1835   Value *TV = SI->getOperand(1);
1836   Value *FV = SI->getOperand(2);
1837
1838   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1839     // Bool selects with constant operands can be folded to logical ops.
1840     if (SI->getType() == Type::Int1Ty) return 0;
1841
1842     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1843     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1844
1845     return new SelectInst(SI->getCondition(), SelectTrueVal,
1846                           SelectFalseVal);
1847   }
1848   return 0;
1849 }
1850
1851
1852 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1853 /// node as operand #0, see if we can fold the instruction into the PHI (which
1854 /// is only possible if all operands to the PHI are constants).
1855 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1856   PHINode *PN = cast<PHINode>(I.getOperand(0));
1857   unsigned NumPHIValues = PN->getNumIncomingValues();
1858   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1859
1860   // Check to see if all of the operands of the PHI are constants.  If there is
1861   // one non-constant value, remember the BB it is.  If there is more than one
1862   // or if *it* is a PHI, bail out.
1863   BasicBlock *NonConstBB = 0;
1864   for (unsigned i = 0; i != NumPHIValues; ++i)
1865     if (!isa<Constant>(PN->getIncomingValue(i))) {
1866       if (NonConstBB) return 0;  // More than one non-const value.
1867       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1868       NonConstBB = PN->getIncomingBlock(i);
1869       
1870       // If the incoming non-constant value is in I's block, we have an infinite
1871       // loop.
1872       if (NonConstBB == I.getParent())
1873         return 0;
1874     }
1875   
1876   // If there is exactly one non-constant value, we can insert a copy of the
1877   // operation in that block.  However, if this is a critical edge, we would be
1878   // inserting the computation one some other paths (e.g. inside a loop).  Only
1879   // do this if the pred block is unconditionally branching into the phi block.
1880   if (NonConstBB) {
1881     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1882     if (!BI || !BI->isUnconditional()) return 0;
1883   }
1884
1885   // Okay, we can do the transformation: create the new PHI node.
1886   PHINode *NewPN = new PHINode(I.getType(), "");
1887   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1888   InsertNewInstBefore(NewPN, *PN);
1889   NewPN->takeName(PN);
1890
1891   // Next, add all of the operands to the PHI.
1892   if (I.getNumOperands() == 2) {
1893     Constant *C = cast<Constant>(I.getOperand(1));
1894     for (unsigned i = 0; i != NumPHIValues; ++i) {
1895       Value *InV = 0;
1896       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1897         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1898           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1899         else
1900           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1901       } else {
1902         assert(PN->getIncomingBlock(i) == NonConstBB);
1903         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1904           InV = BinaryOperator::create(BO->getOpcode(),
1905                                        PN->getIncomingValue(i), C, "phitmp",
1906                                        NonConstBB->getTerminator());
1907         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1908           InV = CmpInst::create(CI->getOpcode(), 
1909                                 CI->getPredicate(),
1910                                 PN->getIncomingValue(i), C, "phitmp",
1911                                 NonConstBB->getTerminator());
1912         else
1913           assert(0 && "Unknown binop!");
1914         
1915         AddToWorkList(cast<Instruction>(InV));
1916       }
1917       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1918     }
1919   } else { 
1920     CastInst *CI = cast<CastInst>(&I);
1921     const Type *RetTy = CI->getType();
1922     for (unsigned i = 0; i != NumPHIValues; ++i) {
1923       Value *InV;
1924       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1925         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1926       } else {
1927         assert(PN->getIncomingBlock(i) == NonConstBB);
1928         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1929                                I.getType(), "phitmp", 
1930                                NonConstBB->getTerminator());
1931         AddToWorkList(cast<Instruction>(InV));
1932       }
1933       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1934     }
1935   }
1936   return ReplaceInstUsesWith(I, NewPN);
1937 }
1938
1939 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1940   bool Changed = SimplifyCommutative(I);
1941   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1942
1943   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1944     // X + undef -> undef
1945     if (isa<UndefValue>(RHS))
1946       return ReplaceInstUsesWith(I, RHS);
1947
1948     // X + 0 --> X
1949     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1950       if (RHSC->isNullValue())
1951         return ReplaceInstUsesWith(I, LHS);
1952     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1953       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1954                               (I.getType())->getValueAPF()))
1955         return ReplaceInstUsesWith(I, LHS);
1956     }
1957
1958     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1959       // X + (signbit) --> X ^ signbit
1960       const APInt& Val = CI->getValue();
1961       uint32_t BitWidth = Val.getBitWidth();
1962       if (Val == APInt::getSignBit(BitWidth))
1963         return BinaryOperator::createXor(LHS, RHS);
1964       
1965       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1966       // (X & 254)+1 -> (X&254)|1
1967       if (!isa<VectorType>(I.getType())) {
1968         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1969         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1970                                  KnownZero, KnownOne))
1971           return &I;
1972       }
1973     }
1974
1975     if (isa<PHINode>(LHS))
1976       if (Instruction *NV = FoldOpIntoPhi(I))
1977         return NV;
1978     
1979     ConstantInt *XorRHS = 0;
1980     Value *XorLHS = 0;
1981     if (isa<ConstantInt>(RHSC) &&
1982         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1983       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1984       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1985       
1986       uint32_t Size = TySizeBits / 2;
1987       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1988       APInt CFF80Val(-C0080Val);
1989       do {
1990         if (TySizeBits > Size) {
1991           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1992           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1993           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1994               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1995             // This is a sign extend if the top bits are known zero.
1996             if (!MaskedValueIsZero(XorLHS, 
1997                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1998               Size = 0;  // Not a sign ext, but can't be any others either.
1999             break;
2000           }
2001         }
2002         Size >>= 1;
2003         C0080Val = APIntOps::lshr(C0080Val, Size);
2004         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2005       } while (Size >= 1);
2006       
2007       // FIXME: This shouldn't be necessary. When the backends can handle types
2008       // with funny bit widths then this whole cascade of if statements should
2009       // be removed. It is just here to get the size of the "middle" type back
2010       // up to something that the back ends can handle.
2011       const Type *MiddleType = 0;
2012       switch (Size) {
2013         default: break;
2014         case 32: MiddleType = Type::Int32Ty; break;
2015         case 16: MiddleType = Type::Int16Ty; break;
2016         case  8: MiddleType = Type::Int8Ty; break;
2017       }
2018       if (MiddleType) {
2019         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2020         InsertNewInstBefore(NewTrunc, I);
2021         return new SExtInst(NewTrunc, I.getType(), I.getName());
2022       }
2023     }
2024   }
2025
2026   // X + X --> X << 1
2027   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2028     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2029
2030     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2031       if (RHSI->getOpcode() == Instruction::Sub)
2032         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2033           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2034     }
2035     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2036       if (LHSI->getOpcode() == Instruction::Sub)
2037         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2038           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2039     }
2040   }
2041
2042   // -A + B  -->  B - A
2043   if (Value *V = dyn_castNegVal(LHS))
2044     return BinaryOperator::createSub(RHS, V);
2045
2046   // A + -B  -->  A - B
2047   if (!isa<Constant>(RHS))
2048     if (Value *V = dyn_castNegVal(RHS))
2049       return BinaryOperator::createSub(LHS, V);
2050
2051
2052   ConstantInt *C2;
2053   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2054     if (X == RHS)   // X*C + X --> X * (C+1)
2055       return BinaryOperator::createMul(RHS, AddOne(C2));
2056
2057     // X*C1 + X*C2 --> X * (C1+C2)
2058     ConstantInt *C1;
2059     if (X == dyn_castFoldableMul(RHS, C1))
2060       return BinaryOperator::createMul(X, Add(C1, C2));
2061   }
2062
2063   // X + X*C --> X * (C+1)
2064   if (dyn_castFoldableMul(RHS, C2) == LHS)
2065     return BinaryOperator::createMul(LHS, AddOne(C2));
2066
2067   // X + ~X --> -1   since   ~X = -X-1
2068   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2069     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2070   
2071
2072   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2073   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2074     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2075       return R;
2076
2077   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2078     Value *X = 0;
2079     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2080       return BinaryOperator::createSub(SubOne(CRHS), X);
2081
2082     // (X & FF00) + xx00  -> (X+xx00) & FF00
2083     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2084       Constant *Anded = And(CRHS, C2);
2085       if (Anded == CRHS) {
2086         // See if all bits from the first bit set in the Add RHS up are included
2087         // in the mask.  First, get the rightmost bit.
2088         const APInt& AddRHSV = CRHS->getValue();
2089
2090         // Form a mask of all bits from the lowest bit added through the top.
2091         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2092
2093         // See if the and mask includes all of these bits.
2094         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2095
2096         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2097           // Okay, the xform is safe.  Insert the new add pronto.
2098           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2099                                                             LHS->getName()), I);
2100           return BinaryOperator::createAnd(NewAdd, C2);
2101         }
2102       }
2103     }
2104
2105     // Try to fold constant add into select arguments.
2106     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2107       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2108         return R;
2109   }
2110
2111   // add (cast *A to intptrtype) B -> 
2112   //   cast (GEP (cast *A to sbyte*) B) -> 
2113   //     intptrtype
2114   {
2115     CastInst *CI = dyn_cast<CastInst>(LHS);
2116     Value *Other = RHS;
2117     if (!CI) {
2118       CI = dyn_cast<CastInst>(RHS);
2119       Other = LHS;
2120     }
2121     if (CI && CI->getType()->isSized() && 
2122         (CI->getType()->getPrimitiveSizeInBits() == 
2123          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2124         && isa<PointerType>(CI->getOperand(0)->getType())) {
2125       unsigned AS =
2126         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2127       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2128                                    PointerType::get(Type::Int8Ty, AS), I);
2129       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2130       return new PtrToIntInst(I2, CI->getType());
2131     }
2132   }
2133   
2134   // add (select (icmp 0 (sub m A)) X Y) A ->
2135   //   add (select (icmp A m) X Y) A
2136   // 
2137   // add (select X 0 (sub n A)) A ->
2138   //  select X A n
2139   {
2140     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2141     Value *Other = RHS;
2142     if (!SI) {
2143       SI = dyn_cast<SelectInst>(RHS);
2144       Other = LHS;
2145     }
2146     if (SI) {
2147       Value *TV = SI->getTrueValue();
2148       Value *FV = SI->getFalseValue();
2149       Value *A;
2150             
2151       // Can we fold the add into the argument of the compare?
2152       Value *Cond = SI->getCondition();
2153       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2154         Value *ICOp0 = IC->getOperand(0);
2155         Value *ICOp1 = IC->getOperand(1);
2156         ConstantInt *C3, *C4;
2157         
2158         // Check both arguments of the compare for a matching subtract.
2159         if (match(ICOp0, m_ConstantInt(C3)) && C3->getValue() == 0 &&
2160             match(ICOp1, m_Sub(m_ConstantInt(C4), m_Value(A))) &&
2161             A == Other) {
2162           // We managed to fold the add into the RHS of the select condition.
2163           Cond = new ICmpInst(IC->getPredicate(), A, C4, "asis", SI);
2164         } else if (match(ICOp1, m_ConstantInt(C3)) && C3->getValue() == 0 &&
2165             match(ICOp0, m_Sub(m_ConstantInt(C4), m_Value(A))) &&
2166             A == Other) {
2167           // We managed to fold the add into the LHS of the select condition.
2168           Cond = new ICmpInst(IC->getPredicate(), C4, A, "asis", SI);
2169         }
2170       }
2171
2172       // Can we fold the add into the argument of the select?
2173       // We check both true and false select arguments for a matching subtract.
2174       ConstantInt *C1, *C2;
2175       if (match(FV, m_ConstantInt(C1)) && C1->getValue() == 0 &&
2176           match(TV, m_Sub(m_ConstantInt(C2), m_Value(A))) &&
2177           A == Other) {
2178         // We managed to fold the add into the true select value,
2179         // picking up a simplified condition, if available.
2180         return new SelectInst(Cond, C2, A, "adselsub");
2181       } else if (match(TV, m_ConstantInt(C1)) && C1->getValue() == 0 && 
2182                  match(FV, m_Sub(m_ConstantInt(C2), m_Value(A))) &&
2183                  A == Other) {
2184         // We managed to fold the add into the false select value,
2185         // picking up a simplified condition, if available.
2186         return new SelectInst(Cond, A, C2, "adselsub");
2187       } else if (Cond != SI->getCondition()) {
2188         // We only managed to fold the add into the select condition.
2189         SI->setOperand(0, Cond);
2190         Changed = true;
2191       }
2192     }
2193   }
2194
2195   return Changed ? &I : 0;
2196 }
2197
2198 // isSignBit - Return true if the value represented by the constant only has the
2199 // highest order bit set.
2200 static bool isSignBit(ConstantInt *CI) {
2201   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2202   return CI->getValue() == APInt::getSignBit(NumBits);
2203 }
2204
2205 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2206   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2207
2208   if (Op0 == Op1)         // sub X, X  -> 0
2209     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2210
2211   // If this is a 'B = x-(-A)', change to B = x+A...
2212   if (Value *V = dyn_castNegVal(Op1))
2213     return BinaryOperator::createAdd(Op0, V);
2214
2215   if (isa<UndefValue>(Op0))
2216     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2217   if (isa<UndefValue>(Op1))
2218     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2219
2220   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2221     // Replace (-1 - A) with (~A)...
2222     if (C->isAllOnesValue())
2223       return BinaryOperator::createNot(Op1);
2224
2225     // C - ~X == X + (1+C)
2226     Value *X = 0;
2227     if (match(Op1, m_Not(m_Value(X))))
2228       return BinaryOperator::createAdd(X, AddOne(C));
2229
2230     // -(X >>u 31) -> (X >>s 31)
2231     // -(X >>s 31) -> (X >>u 31)
2232     if (C->isZero()) {
2233       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2234         if (SI->getOpcode() == Instruction::LShr) {
2235           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2236             // Check to see if we are shifting out everything but the sign bit.
2237             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2238                 SI->getType()->getPrimitiveSizeInBits()-1) {
2239               // Ok, the transformation is safe.  Insert AShr.
2240               return BinaryOperator::create(Instruction::AShr, 
2241                                           SI->getOperand(0), CU, SI->getName());
2242             }
2243           }
2244         }
2245         else if (SI->getOpcode() == Instruction::AShr) {
2246           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2247             // Check to see if we are shifting out everything but the sign bit.
2248             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2249                 SI->getType()->getPrimitiveSizeInBits()-1) {
2250               // Ok, the transformation is safe.  Insert LShr. 
2251               return BinaryOperator::createLShr(
2252                                           SI->getOperand(0), CU, SI->getName());
2253             }
2254           }
2255         } 
2256     }
2257
2258     // Try to fold constant sub into select arguments.
2259     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2260       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2261         return R;
2262
2263     if (isa<PHINode>(Op0))
2264       if (Instruction *NV = FoldOpIntoPhi(I))
2265         return NV;
2266   }
2267
2268   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2269     if (Op1I->getOpcode() == Instruction::Add &&
2270         !Op0->getType()->isFPOrFPVector()) {
2271       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2272         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2273       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2274         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2275       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2276         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2277           // C1-(X+C2) --> (C1-C2)-X
2278           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2279                                            Op1I->getOperand(0));
2280       }
2281     }
2282
2283     if (Op1I->hasOneUse()) {
2284       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2285       // is not used by anyone else...
2286       //
2287       if (Op1I->getOpcode() == Instruction::Sub &&
2288           !Op1I->getType()->isFPOrFPVector()) {
2289         // Swap the two operands of the subexpr...
2290         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2291         Op1I->setOperand(0, IIOp1);
2292         Op1I->setOperand(1, IIOp0);
2293
2294         // Create the new top level add instruction...
2295         return BinaryOperator::createAdd(Op0, Op1);
2296       }
2297
2298       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2299       //
2300       if (Op1I->getOpcode() == Instruction::And &&
2301           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2302         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2303
2304         Value *NewNot =
2305           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2306         return BinaryOperator::createAnd(Op0, NewNot);
2307       }
2308
2309       // 0 - (X sdiv C)  -> (X sdiv -C)
2310       if (Op1I->getOpcode() == Instruction::SDiv)
2311         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2312           if (CSI->isZero())
2313             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2314               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2315                                                ConstantExpr::getNeg(DivRHS));
2316
2317       // X - X*C --> X * (1-C)
2318       ConstantInt *C2 = 0;
2319       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2320         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2321         return BinaryOperator::createMul(Op0, CP1);
2322       }
2323
2324       // X - ((X / Y) * Y) --> X % Y
2325       if (Op1I->getOpcode() == Instruction::Mul)
2326         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2327           if (Op0 == I->getOperand(0) &&
2328               Op1I->getOperand(1) == I->getOperand(1)) {
2329             if (I->getOpcode() == Instruction::SDiv)
2330               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2331             if (I->getOpcode() == Instruction::UDiv)
2332               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2333           }
2334     }
2335   }
2336
2337   if (!Op0->getType()->isFPOrFPVector())
2338     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2339       if (Op0I->getOpcode() == Instruction::Add) {
2340         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2341           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2342         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2343           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2344       } else if (Op0I->getOpcode() == Instruction::Sub) {
2345         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2346           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2347       }
2348
2349   ConstantInt *C1;
2350   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2351     if (X == Op1)  // X*C - X --> X * (C-1)
2352       return BinaryOperator::createMul(Op1, SubOne(C1));
2353
2354     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2355     if (X == dyn_castFoldableMul(Op1, C2))
2356       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2357   }
2358   return 0;
2359 }
2360
2361 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2362 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2363 /// TrueIfSigned if the result of the comparison is true when the input value is
2364 /// signed.
2365 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2366                            bool &TrueIfSigned) {
2367   switch (pred) {
2368   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2369     TrueIfSigned = true;
2370     return RHS->isZero();
2371   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2372     TrueIfSigned = true;
2373     return RHS->isAllOnesValue();
2374   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2375     TrueIfSigned = false;
2376     return RHS->isAllOnesValue();
2377   case ICmpInst::ICMP_UGT:
2378     // True if LHS u> RHS and RHS == high-bit-mask - 1
2379     TrueIfSigned = true;
2380     return RHS->getValue() ==
2381       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2382   case ICmpInst::ICMP_UGE: 
2383     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2384     TrueIfSigned = true;
2385     return RHS->getValue() == 
2386       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2387   default:
2388     return false;
2389   }
2390 }
2391
2392 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2393   bool Changed = SimplifyCommutative(I);
2394   Value *Op0 = I.getOperand(0);
2395
2396   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2397     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2398
2399   // Simplify mul instructions with a constant RHS...
2400   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2401     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2402
2403       // ((X << C1)*C2) == (X * (C2 << C1))
2404       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2405         if (SI->getOpcode() == Instruction::Shl)
2406           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2407             return BinaryOperator::createMul(SI->getOperand(0),
2408                                              ConstantExpr::getShl(CI, ShOp));
2409
2410       if (CI->isZero())
2411         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2412       if (CI->equalsInt(1))                  // X * 1  == X
2413         return ReplaceInstUsesWith(I, Op0);
2414       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2415         return BinaryOperator::createNeg(Op0, I.getName());
2416
2417       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2418       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2419         return BinaryOperator::createShl(Op0,
2420                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2421       }
2422     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2423       if (Op1F->isNullValue())
2424         return ReplaceInstUsesWith(I, Op1);
2425
2426       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2427       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2428       // We need a better interface for long double here.
2429       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2430         if (Op1F->isExactlyValue(1.0))
2431           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2432     }
2433     
2434     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2435       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2436           isa<ConstantInt>(Op0I->getOperand(1))) {
2437         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2438         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2439                                                      Op1, "tmp");
2440         InsertNewInstBefore(Add, I);
2441         Value *C1C2 = ConstantExpr::getMul(Op1, 
2442                                            cast<Constant>(Op0I->getOperand(1)));
2443         return BinaryOperator::createAdd(Add, C1C2);
2444         
2445       }
2446
2447     // Try to fold constant mul into select arguments.
2448     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2449       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2450         return R;
2451
2452     if (isa<PHINode>(Op0))
2453       if (Instruction *NV = FoldOpIntoPhi(I))
2454         return NV;
2455   }
2456
2457   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2458     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2459       return BinaryOperator::createMul(Op0v, Op1v);
2460
2461   // If one of the operands of the multiply is a cast from a boolean value, then
2462   // we know the bool is either zero or one, so this is a 'masking' multiply.
2463   // See if we can simplify things based on how the boolean was originally
2464   // formed.
2465   CastInst *BoolCast = 0;
2466   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2467     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2468       BoolCast = CI;
2469   if (!BoolCast)
2470     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2471       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2472         BoolCast = CI;
2473   if (BoolCast) {
2474     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2475       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2476       const Type *SCOpTy = SCIOp0->getType();
2477       bool TIS = false;
2478       
2479       // If the icmp is true iff the sign bit of X is set, then convert this
2480       // multiply into a shift/and combination.
2481       if (isa<ConstantInt>(SCIOp1) &&
2482           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2483           TIS) {
2484         // Shift the X value right to turn it into "all signbits".
2485         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2486                                           SCOpTy->getPrimitiveSizeInBits()-1);
2487         Value *V =
2488           InsertNewInstBefore(
2489             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2490                                             BoolCast->getOperand(0)->getName()+
2491                                             ".mask"), I);
2492
2493         // If the multiply type is not the same as the source type, sign extend
2494         // or truncate to the multiply type.
2495         if (I.getType() != V->getType()) {
2496           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2497           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2498           Instruction::CastOps opcode = 
2499             (SrcBits == DstBits ? Instruction::BitCast : 
2500              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2501           V = InsertCastBefore(opcode, V, I.getType(), I);
2502         }
2503
2504         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2505         return BinaryOperator::createAnd(V, OtherOp);
2506       }
2507     }
2508   }
2509
2510   return Changed ? &I : 0;
2511 }
2512
2513 /// This function implements the transforms on div instructions that work
2514 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2515 /// used by the visitors to those instructions.
2516 /// @brief Transforms common to all three div instructions
2517 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2518   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2519
2520   // undef / X -> 0
2521   if (isa<UndefValue>(Op0))
2522     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2523
2524   // X / undef -> undef
2525   if (isa<UndefValue>(Op1))
2526     return ReplaceInstUsesWith(I, Op1);
2527
2528   // Handle cases involving: div X, (select Cond, Y, Z)
2529   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2530     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2531     // same basic block, then we replace the select with Y, and the condition 
2532     // of the select with false (if the cond value is in the same BB).  If the
2533     // select has uses other than the div, this allows them to be simplified
2534     // also. Note that div X, Y is just as good as div X, 0 (undef)
2535     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2536       if (ST->isNullValue()) {
2537         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2538         if (CondI && CondI->getParent() == I.getParent())
2539           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2540         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2541           I.setOperand(1, SI->getOperand(2));
2542         else
2543           UpdateValueUsesWith(SI, SI->getOperand(2));
2544         return &I;
2545       }
2546
2547     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2548     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2549       if (ST->isNullValue()) {
2550         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2551         if (CondI && CondI->getParent() == I.getParent())
2552           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2553         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2554           I.setOperand(1, SI->getOperand(1));
2555         else
2556           UpdateValueUsesWith(SI, SI->getOperand(1));
2557         return &I;
2558       }
2559   }
2560
2561   return 0;
2562 }
2563
2564 /// This function implements the transforms common to both integer division
2565 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2566 /// division instructions.
2567 /// @brief Common integer divide transforms
2568 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2569   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2570
2571   if (Instruction *Common = commonDivTransforms(I))
2572     return Common;
2573
2574   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2575     // div X, 1 == X
2576     if (RHS->equalsInt(1))
2577       return ReplaceInstUsesWith(I, Op0);
2578
2579     // (X / C1) / C2  -> X / (C1*C2)
2580     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2581       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2582         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2583           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2584                                         Multiply(RHS, LHSRHS));
2585         }
2586
2587     if (!RHS->isZero()) { // avoid X udiv 0
2588       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2589         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2590           return R;
2591       if (isa<PHINode>(Op0))
2592         if (Instruction *NV = FoldOpIntoPhi(I))
2593           return NV;
2594     }
2595   }
2596
2597   // 0 / X == 0, we don't need to preserve faults!
2598   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2599     if (LHS->equalsInt(0))
2600       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2601
2602   return 0;
2603 }
2604
2605 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2606   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2607
2608   // Handle the integer div common cases
2609   if (Instruction *Common = commonIDivTransforms(I))
2610     return Common;
2611
2612   // X udiv C^2 -> X >> C
2613   // Check to see if this is an unsigned division with an exact power of 2,
2614   // if so, convert to a right shift.
2615   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2616     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2617       return BinaryOperator::createLShr(Op0, 
2618                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2619   }
2620
2621   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2622   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2623     if (RHSI->getOpcode() == Instruction::Shl &&
2624         isa<ConstantInt>(RHSI->getOperand(0))) {
2625       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2626       if (C1.isPowerOf2()) {
2627         Value *N = RHSI->getOperand(1);
2628         const Type *NTy = N->getType();
2629         if (uint32_t C2 = C1.logBase2()) {
2630           Constant *C2V = ConstantInt::get(NTy, C2);
2631           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2632         }
2633         return BinaryOperator::createLShr(Op0, N);
2634       }
2635     }
2636   }
2637   
2638   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2639   // where C1&C2 are powers of two.
2640   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2641     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2642       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2643         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2644         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2645           // Compute the shift amounts
2646           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2647           // Construct the "on true" case of the select
2648           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2649           Instruction *TSI = BinaryOperator::createLShr(
2650                                                  Op0, TC, SI->getName()+".t");
2651           TSI = InsertNewInstBefore(TSI, I);
2652   
2653           // Construct the "on false" case of the select
2654           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2655           Instruction *FSI = BinaryOperator::createLShr(
2656                                                  Op0, FC, SI->getName()+".f");
2657           FSI = InsertNewInstBefore(FSI, I);
2658
2659           // construct the select instruction and return it.
2660           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2661         }
2662       }
2663   return 0;
2664 }
2665
2666 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2667   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2668
2669   // Handle the integer div common cases
2670   if (Instruction *Common = commonIDivTransforms(I))
2671     return Common;
2672
2673   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2674     // sdiv X, -1 == -X
2675     if (RHS->isAllOnesValue())
2676       return BinaryOperator::createNeg(Op0);
2677
2678     // -X/C -> X/-C
2679     if (Value *LHSNeg = dyn_castNegVal(Op0))
2680       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2681   }
2682
2683   // If the sign bits of both operands are zero (i.e. we can prove they are
2684   // unsigned inputs), turn this into a udiv.
2685   if (I.getType()->isInteger()) {
2686     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2687     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2688       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2689       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2690     }
2691   }      
2692   
2693   return 0;
2694 }
2695
2696 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2697   return commonDivTransforms(I);
2698 }
2699
2700 /// GetFactor - If we can prove that the specified value is at least a multiple
2701 /// of some factor, return that factor.
2702 static Constant *GetFactor(Value *V) {
2703   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2704     return CI;
2705   
2706   // Unless we can be tricky, we know this is a multiple of 1.
2707   Constant *Result = ConstantInt::get(V->getType(), 1);
2708   
2709   Instruction *I = dyn_cast<Instruction>(V);
2710   if (!I) return Result;
2711   
2712   if (I->getOpcode() == Instruction::Mul) {
2713     // Handle multiplies by a constant, etc.
2714     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2715                                 GetFactor(I->getOperand(1)));
2716   } else if (I->getOpcode() == Instruction::Shl) {
2717     // (X<<C) -> X * (1 << C)
2718     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2719       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2720       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2721     }
2722   } else if (I->getOpcode() == Instruction::And) {
2723     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2724       // X & 0xFFF0 is known to be a multiple of 16.
2725       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2726       if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
2727         return ConstantExpr::getShl(Result, 
2728                                     ConstantInt::get(Result->getType(), Zeros));
2729     }
2730   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2731     // Only handle int->int casts.
2732     if (!CI->isIntegerCast())
2733       return Result;
2734     Value *Op = CI->getOperand(0);
2735     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2736   }    
2737   return Result;
2738 }
2739
2740 /// This function implements the transforms on rem instructions that work
2741 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2742 /// is used by the visitors to those instructions.
2743 /// @brief Transforms common to all three rem instructions
2744 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2745   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2746
2747   // 0 % X == 0, we don't need to preserve faults!
2748   if (Constant *LHS = dyn_cast<Constant>(Op0))
2749     if (LHS->isNullValue())
2750       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2751
2752   if (isa<UndefValue>(Op0))              // undef % X -> 0
2753     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2754   if (isa<UndefValue>(Op1))
2755     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2756
2757   // Handle cases involving: rem X, (select Cond, Y, Z)
2758   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2759     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2760     // the same basic block, then we replace the select with Y, and the
2761     // condition of the select with false (if the cond value is in the same
2762     // BB).  If the select has uses other than the div, this allows them to be
2763     // simplified also.
2764     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2765       if (ST->isNullValue()) {
2766         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2767         if (CondI && CondI->getParent() == I.getParent())
2768           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2769         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2770           I.setOperand(1, SI->getOperand(2));
2771         else
2772           UpdateValueUsesWith(SI, SI->getOperand(2));
2773         return &I;
2774       }
2775     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2776     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2777       if (ST->isNullValue()) {
2778         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2779         if (CondI && CondI->getParent() == I.getParent())
2780           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2781         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2782           I.setOperand(1, SI->getOperand(1));
2783         else
2784           UpdateValueUsesWith(SI, SI->getOperand(1));
2785         return &I;
2786       }
2787   }
2788
2789   return 0;
2790 }
2791
2792 /// This function implements the transforms common to both integer remainder
2793 /// instructions (urem and srem). It is called by the visitors to those integer
2794 /// remainder instructions.
2795 /// @brief Common integer remainder transforms
2796 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2797   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798
2799   if (Instruction *common = commonRemTransforms(I))
2800     return common;
2801
2802   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2803     // X % 0 == undef, we don't need to preserve faults!
2804     if (RHS->equalsInt(0))
2805       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2806     
2807     if (RHS->equalsInt(1))  // X % 1 == 0
2808       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2809
2810     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2811       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2812         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2813           return R;
2814       } else if (isa<PHINode>(Op0I)) {
2815         if (Instruction *NV = FoldOpIntoPhi(I))
2816           return NV;
2817       }
2818       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2819       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2820         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2821     }
2822   }
2823
2824   return 0;
2825 }
2826
2827 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2828   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2829
2830   if (Instruction *common = commonIRemTransforms(I))
2831     return common;
2832   
2833   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2834     // X urem C^2 -> X and C
2835     // Check to see if this is an unsigned remainder with an exact power of 2,
2836     // if so, convert to a bitwise and.
2837     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2838       if (C->getValue().isPowerOf2())
2839         return BinaryOperator::createAnd(Op0, SubOne(C));
2840   }
2841
2842   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2843     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2844     if (RHSI->getOpcode() == Instruction::Shl &&
2845         isa<ConstantInt>(RHSI->getOperand(0))) {
2846       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2847         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2848         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2849                                                                    "tmp"), I);
2850         return BinaryOperator::createAnd(Op0, Add);
2851       }
2852     }
2853   }
2854
2855   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2856   // where C1&C2 are powers of two.
2857   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2858     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2859       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2860         // STO == 0 and SFO == 0 handled above.
2861         if ((STO->getValue().isPowerOf2()) && 
2862             (SFO->getValue().isPowerOf2())) {
2863           Value *TrueAnd = InsertNewInstBefore(
2864             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2865           Value *FalseAnd = InsertNewInstBefore(
2866             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2867           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2868         }
2869       }
2870   }
2871   
2872   return 0;
2873 }
2874
2875 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2876   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2877
2878   // Handle the integer rem common cases
2879   if (Instruction *common = commonIRemTransforms(I))
2880     return common;
2881   
2882   if (Value *RHSNeg = dyn_castNegVal(Op1))
2883     if (!isa<ConstantInt>(RHSNeg) || 
2884         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2885       // X % -Y -> X % Y
2886       AddUsesToWorkList(I);
2887       I.setOperand(1, RHSNeg);
2888       return &I;
2889     }
2890  
2891   // If the sign bits of both operands are zero (i.e. we can prove they are
2892   // unsigned inputs), turn this into a urem.
2893   if (I.getType()->isInteger()) {
2894     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2895     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2896       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2897       return BinaryOperator::createURem(Op0, Op1, I.getName());
2898     }
2899   }
2900
2901   return 0;
2902 }
2903
2904 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2905   return commonRemTransforms(I);
2906 }
2907
2908 // isMaxValueMinusOne - return true if this is Max-1
2909 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2910   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2911   if (!isSigned)
2912     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2913   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2914 }
2915
2916 // isMinValuePlusOne - return true if this is Min+1
2917 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2918   if (!isSigned)
2919     return C->getValue() == 1; // unsigned
2920     
2921   // Calculate 1111111111000000000000
2922   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2923   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2924 }
2925
2926 // isOneBitSet - Return true if there is exactly one bit set in the specified
2927 // constant.
2928 static bool isOneBitSet(const ConstantInt *CI) {
2929   return CI->getValue().isPowerOf2();
2930 }
2931
2932 // isHighOnes - Return true if the constant is of the form 1+0+.
2933 // This is the same as lowones(~X).
2934 static bool isHighOnes(const ConstantInt *CI) {
2935   return (~CI->getValue() + 1).isPowerOf2();
2936 }
2937
2938 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2939 /// are carefully arranged to allow folding of expressions such as:
2940 ///
2941 ///      (A < B) | (A > B) --> (A != B)
2942 ///
2943 /// Note that this is only valid if the first and second predicates have the
2944 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2945 ///
2946 /// Three bits are used to represent the condition, as follows:
2947 ///   0  A > B
2948 ///   1  A == B
2949 ///   2  A < B
2950 ///
2951 /// <=>  Value  Definition
2952 /// 000     0   Always false
2953 /// 001     1   A >  B
2954 /// 010     2   A == B
2955 /// 011     3   A >= B
2956 /// 100     4   A <  B
2957 /// 101     5   A != B
2958 /// 110     6   A <= B
2959 /// 111     7   Always true
2960 ///  
2961 static unsigned getICmpCode(const ICmpInst *ICI) {
2962   switch (ICI->getPredicate()) {
2963     // False -> 0
2964   case ICmpInst::ICMP_UGT: return 1;  // 001
2965   case ICmpInst::ICMP_SGT: return 1;  // 001
2966   case ICmpInst::ICMP_EQ:  return 2;  // 010
2967   case ICmpInst::ICMP_UGE: return 3;  // 011
2968   case ICmpInst::ICMP_SGE: return 3;  // 011
2969   case ICmpInst::ICMP_ULT: return 4;  // 100
2970   case ICmpInst::ICMP_SLT: return 4;  // 100
2971   case ICmpInst::ICMP_NE:  return 5;  // 101
2972   case ICmpInst::ICMP_ULE: return 6;  // 110
2973   case ICmpInst::ICMP_SLE: return 6;  // 110
2974     // True -> 7
2975   default:
2976     assert(0 && "Invalid ICmp predicate!");
2977     return 0;
2978   }
2979 }
2980
2981 /// getICmpValue - This is the complement of getICmpCode, which turns an
2982 /// opcode and two operands into either a constant true or false, or a brand 
2983 /// new ICmp instruction. The sign is passed in to determine which kind
2984 /// of predicate to use in new icmp instructions.
2985 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2986   switch (code) {
2987   default: assert(0 && "Illegal ICmp code!");
2988   case  0: return ConstantInt::getFalse();
2989   case  1: 
2990     if (sign)
2991       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2992     else
2993       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2994   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2995   case  3: 
2996     if (sign)
2997       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2998     else
2999       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3000   case  4: 
3001     if (sign)
3002       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3003     else
3004       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3005   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3006   case  6: 
3007     if (sign)
3008       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3009     else
3010       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3011   case  7: return ConstantInt::getTrue();
3012   }
3013 }
3014
3015 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3016   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3017     (ICmpInst::isSignedPredicate(p1) && 
3018      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3019     (ICmpInst::isSignedPredicate(p2) && 
3020      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3021 }
3022
3023 namespace { 
3024 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3025 struct FoldICmpLogical {
3026   InstCombiner &IC;
3027   Value *LHS, *RHS;
3028   ICmpInst::Predicate pred;
3029   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3030     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3031       pred(ICI->getPredicate()) {}
3032   bool shouldApply(Value *V) const {
3033     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3034       if (PredicatesFoldable(pred, ICI->getPredicate()))
3035         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3036                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3037     return false;
3038   }
3039   Instruction *apply(Instruction &Log) const {
3040     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3041     if (ICI->getOperand(0) != LHS) {
3042       assert(ICI->getOperand(1) == LHS);
3043       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3044     }
3045
3046     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3047     unsigned LHSCode = getICmpCode(ICI);
3048     unsigned RHSCode = getICmpCode(RHSICI);
3049     unsigned Code;
3050     switch (Log.getOpcode()) {
3051     case Instruction::And: Code = LHSCode & RHSCode; break;
3052     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3053     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3054     default: assert(0 && "Illegal logical opcode!"); return 0;
3055     }
3056
3057     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3058                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3059       
3060     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3061     if (Instruction *I = dyn_cast<Instruction>(RV))
3062       return I;
3063     // Otherwise, it's a constant boolean value...
3064     return IC.ReplaceInstUsesWith(Log, RV);
3065   }
3066 };
3067 } // end anonymous namespace
3068
3069 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3070 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3071 // guaranteed to be a binary operator.
3072 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3073                                     ConstantInt *OpRHS,
3074                                     ConstantInt *AndRHS,
3075                                     BinaryOperator &TheAnd) {
3076   Value *X = Op->getOperand(0);
3077   Constant *Together = 0;
3078   if (!Op->isShift())
3079     Together = And(AndRHS, OpRHS);
3080
3081   switch (Op->getOpcode()) {
3082   case Instruction::Xor:
3083     if (Op->hasOneUse()) {
3084       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3085       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3086       InsertNewInstBefore(And, TheAnd);
3087       And->takeName(Op);
3088       return BinaryOperator::createXor(And, Together);
3089     }
3090     break;
3091   case Instruction::Or:
3092     if (Together == AndRHS) // (X | C) & C --> C
3093       return ReplaceInstUsesWith(TheAnd, AndRHS);
3094
3095     if (Op->hasOneUse() && Together != OpRHS) {
3096       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3097       Instruction *Or = BinaryOperator::createOr(X, Together);
3098       InsertNewInstBefore(Or, TheAnd);
3099       Or->takeName(Op);
3100       return BinaryOperator::createAnd(Or, AndRHS);
3101     }
3102     break;
3103   case Instruction::Add:
3104     if (Op->hasOneUse()) {
3105       // Adding a one to a single bit bit-field should be turned into an XOR
3106       // of the bit.  First thing to check is to see if this AND is with a
3107       // single bit constant.
3108       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3109
3110       // If there is only one bit set...
3111       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3112         // Ok, at this point, we know that we are masking the result of the
3113         // ADD down to exactly one bit.  If the constant we are adding has
3114         // no bits set below this bit, then we can eliminate the ADD.
3115         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3116
3117         // Check to see if any bits below the one bit set in AndRHSV are set.
3118         if ((AddRHS & (AndRHSV-1)) == 0) {
3119           // If not, the only thing that can effect the output of the AND is
3120           // the bit specified by AndRHSV.  If that bit is set, the effect of
3121           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3122           // no effect.
3123           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3124             TheAnd.setOperand(0, X);
3125             return &TheAnd;
3126           } else {
3127             // Pull the XOR out of the AND.
3128             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3129             InsertNewInstBefore(NewAnd, TheAnd);
3130             NewAnd->takeName(Op);
3131             return BinaryOperator::createXor(NewAnd, AndRHS);
3132           }
3133         }
3134       }
3135     }
3136     break;
3137
3138   case Instruction::Shl: {
3139     // We know that the AND will not produce any of the bits shifted in, so if
3140     // the anded constant includes them, clear them now!
3141     //
3142     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3143     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3144     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3145     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3146
3147     if (CI->getValue() == ShlMask) { 
3148     // Masking out bits that the shift already masks
3149       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3150     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3151       TheAnd.setOperand(1, CI);
3152       return &TheAnd;
3153     }
3154     break;
3155   }
3156   case Instruction::LShr:
3157   {
3158     // We know that the AND will not produce any of the bits shifted in, so if
3159     // the anded constant includes them, clear them now!  This only applies to
3160     // unsigned shifts, because a signed shr may bring in set bits!
3161     //
3162     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3163     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3164     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3165     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3166
3167     if (CI->getValue() == ShrMask) {   
3168     // Masking out bits that the shift already masks.
3169       return ReplaceInstUsesWith(TheAnd, Op);
3170     } else if (CI != AndRHS) {
3171       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3172       return &TheAnd;
3173     }
3174     break;
3175   }
3176   case Instruction::AShr:
3177     // Signed shr.
3178     // See if this is shifting in some sign extension, then masking it out
3179     // with an and.
3180     if (Op->hasOneUse()) {
3181       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3182       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3183       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3184       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3185       if (C == AndRHS) {          // Masking out bits shifted in.
3186         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3187         // Make the argument unsigned.
3188         Value *ShVal = Op->getOperand(0);
3189         ShVal = InsertNewInstBefore(
3190             BinaryOperator::createLShr(ShVal, OpRHS, 
3191                                    Op->getName()), TheAnd);
3192         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3193       }
3194     }
3195     break;
3196   }
3197   return 0;
3198 }
3199
3200
3201 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3202 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3203 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3204 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3205 /// insert new instructions.
3206 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3207                                            bool isSigned, bool Inside, 
3208                                            Instruction &IB) {
3209   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3210             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3211          "Lo is not <= Hi in range emission code!");
3212     
3213   if (Inside) {
3214     if (Lo == Hi)  // Trivially false.
3215       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3216
3217     // V >= Min && V < Hi --> V < Hi
3218     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3219       ICmpInst::Predicate pred = (isSigned ? 
3220         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3221       return new ICmpInst(pred, V, Hi);
3222     }
3223
3224     // Emit V-Lo <u Hi-Lo
3225     Constant *NegLo = ConstantExpr::getNeg(Lo);
3226     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3227     InsertNewInstBefore(Add, IB);
3228     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3229     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3230   }
3231
3232   if (Lo == Hi)  // Trivially true.
3233     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3234
3235   // V < Min || V >= Hi -> V > Hi-1
3236   Hi = SubOne(cast<ConstantInt>(Hi));
3237   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3238     ICmpInst::Predicate pred = (isSigned ? 
3239         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3240     return new ICmpInst(pred, V, Hi);
3241   }
3242
3243   // Emit V-Lo >u Hi-1-Lo
3244   // Note that Hi has already had one subtracted from it, above.
3245   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3246   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3247   InsertNewInstBefore(Add, IB);
3248   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3249   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3250 }
3251
3252 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3253 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3254 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3255 // not, since all 1s are not contiguous.
3256 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3257   const APInt& V = Val->getValue();
3258   uint32_t BitWidth = Val->getType()->getBitWidth();
3259   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3260
3261   // look for the first zero bit after the run of ones
3262   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3263   // look for the first non-zero bit
3264   ME = V.getActiveBits(); 
3265   return true;
3266 }
3267
3268 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3269 /// where isSub determines whether the operator is a sub.  If we can fold one of
3270 /// the following xforms:
3271 /// 
3272 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3273 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3274 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3275 ///
3276 /// return (A +/- B).
3277 ///
3278 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3279                                         ConstantInt *Mask, bool isSub,
3280                                         Instruction &I) {
3281   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3282   if (!LHSI || LHSI->getNumOperands() != 2 ||
3283       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3284
3285   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3286
3287   switch (LHSI->getOpcode()) {
3288   default: return 0;
3289   case Instruction::And:
3290     if (And(N, Mask) == Mask) {
3291       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3292       if ((Mask->getValue().countLeadingZeros() + 
3293            Mask->getValue().countPopulation()) == 
3294           Mask->getValue().getBitWidth())
3295         break;
3296
3297       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3298       // part, we don't need any explicit masks to take them out of A.  If that
3299       // is all N is, ignore it.
3300       uint32_t MB = 0, ME = 0;
3301       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3302         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3303         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3304         if (MaskedValueIsZero(RHS, Mask))
3305           break;
3306       }
3307     }
3308     return 0;
3309   case Instruction::Or:
3310   case Instruction::Xor:
3311     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3312     if ((Mask->getValue().countLeadingZeros() + 
3313          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3314         && And(N, Mask)->isZero())
3315       break;
3316     return 0;
3317   }
3318   
3319   Instruction *New;
3320   if (isSub)
3321     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3322   else
3323     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3324   return InsertNewInstBefore(New, I);
3325 }
3326
3327 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3328   bool Changed = SimplifyCommutative(I);
3329   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3330
3331   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3332     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3333
3334   // and X, X = X
3335   if (Op0 == Op1)
3336     return ReplaceInstUsesWith(I, Op1);
3337
3338   // See if we can simplify any instructions used by the instruction whose sole 
3339   // purpose is to compute bits we don't care about.
3340   if (!isa<VectorType>(I.getType())) {
3341     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3342     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3343     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3344                              KnownZero, KnownOne))
3345       return &I;
3346   } else {
3347     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3348       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3349         return ReplaceInstUsesWith(I, I.getOperand(0));
3350     } else if (isa<ConstantAggregateZero>(Op1)) {
3351       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3352     }
3353   }
3354   
3355   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3356     const APInt& AndRHSMask = AndRHS->getValue();
3357     APInt NotAndRHS(~AndRHSMask);
3358
3359     // Optimize a variety of ((val OP C1) & C2) combinations...
3360     if (isa<BinaryOperator>(Op0)) {
3361       Instruction *Op0I = cast<Instruction>(Op0);
3362       Value *Op0LHS = Op0I->getOperand(0);
3363       Value *Op0RHS = Op0I->getOperand(1);
3364       switch (Op0I->getOpcode()) {
3365       case Instruction::Xor:
3366       case Instruction::Or:
3367         // If the mask is only needed on one incoming arm, push it up.
3368         if (Op0I->hasOneUse()) {
3369           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3370             // Not masking anything out for the LHS, move to RHS.
3371             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3372                                                    Op0RHS->getName()+".masked");
3373             InsertNewInstBefore(NewRHS, I);
3374             return BinaryOperator::create(
3375                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3376           }
3377           if (!isa<Constant>(Op0RHS) &&
3378               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3379             // Not masking anything out for the RHS, move to LHS.
3380             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3381                                                    Op0LHS->getName()+".masked");
3382             InsertNewInstBefore(NewLHS, I);
3383             return BinaryOperator::create(
3384                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3385           }
3386         }
3387
3388         break;
3389       case Instruction::Add:
3390         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3391         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3392         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3393         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3394           return BinaryOperator::createAnd(V, AndRHS);
3395         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3396           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3397         break;
3398
3399       case Instruction::Sub:
3400         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3401         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3402         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3403         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3404           return BinaryOperator::createAnd(V, AndRHS);
3405         break;
3406       }
3407
3408       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3409         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3410           return Res;
3411     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3412       // If this is an integer truncation or change from signed-to-unsigned, and
3413       // if the source is an and/or with immediate, transform it.  This
3414       // frequently occurs for bitfield accesses.
3415       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3416         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3417             CastOp->getNumOperands() == 2)
3418           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3419             if (CastOp->getOpcode() == Instruction::And) {
3420               // Change: and (cast (and X, C1) to T), C2
3421               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3422               // This will fold the two constants together, which may allow 
3423               // other simplifications.
3424               Instruction *NewCast = CastInst::createTruncOrBitCast(
3425                 CastOp->getOperand(0), I.getType(), 
3426                 CastOp->getName()+".shrunk");
3427               NewCast = InsertNewInstBefore(NewCast, I);
3428               // trunc_or_bitcast(C1)&C2
3429               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3430               C3 = ConstantExpr::getAnd(C3, AndRHS);
3431               return BinaryOperator::createAnd(NewCast, C3);
3432             } else if (CastOp->getOpcode() == Instruction::Or) {
3433               // Change: and (cast (or X, C1) to T), C2
3434               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3435               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3436               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3437                 return ReplaceInstUsesWith(I, AndRHS);
3438             }
3439       }
3440     }
3441
3442     // Try to fold constant and into select arguments.
3443     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3444       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3445         return R;
3446     if (isa<PHINode>(Op0))
3447       if (Instruction *NV = FoldOpIntoPhi(I))
3448         return NV;
3449   }
3450
3451   Value *Op0NotVal = dyn_castNotVal(Op0);
3452   Value *Op1NotVal = dyn_castNotVal(Op1);
3453
3454   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3455     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3456
3457   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3458   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3459     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3460                                                I.getName()+".demorgan");
3461     InsertNewInstBefore(Or, I);
3462     return BinaryOperator::createNot(Or);
3463   }
3464   
3465   {
3466     Value *A = 0, *B = 0, *C = 0, *D = 0;
3467     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3468       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3469         return ReplaceInstUsesWith(I, Op1);
3470     
3471       // (A|B) & ~(A&B) -> A^B
3472       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3473         if ((A == C && B == D) || (A == D && B == C))
3474           return BinaryOperator::createXor(A, B);
3475       }
3476     }
3477     
3478     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3479       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3480         return ReplaceInstUsesWith(I, Op0);
3481
3482       // ~(A&B) & (A|B) -> A^B
3483       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3484         if ((A == C && B == D) || (A == D && B == C))
3485           return BinaryOperator::createXor(A, B);
3486       }
3487     }
3488     
3489     if (Op0->hasOneUse() &&
3490         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3491       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3492         I.swapOperands();     // Simplify below
3493         std::swap(Op0, Op1);
3494       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3495         cast<BinaryOperator>(Op0)->swapOperands();
3496         I.swapOperands();     // Simplify below
3497         std::swap(Op0, Op1);
3498       }
3499     }
3500     if (Op1->hasOneUse() &&
3501         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3502       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3503         cast<BinaryOperator>(Op1)->swapOperands();
3504         std::swap(A, B);
3505       }
3506       if (A == Op0) {                                // A&(A^B) -> A & ~B
3507         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3508         InsertNewInstBefore(NotB, I);
3509         return BinaryOperator::createAnd(A, NotB);
3510       }
3511     }
3512   }
3513   
3514   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3515     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3516     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3517       return R;
3518
3519     Value *LHSVal, *RHSVal;
3520     ConstantInt *LHSCst, *RHSCst;
3521     ICmpInst::Predicate LHSCC, RHSCC;
3522     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3523       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3524         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3525             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3526             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3527             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3528             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3529             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3530             
3531             // Don't try to fold ICMP_SLT + ICMP_ULT.
3532             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3533              ICmpInst::isSignedPredicate(LHSCC) == 
3534                  ICmpInst::isSignedPredicate(RHSCC))) {
3535           // Ensure that the larger constant is on the RHS.
3536           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3537             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3538           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3539           ICmpInst *LHS = cast<ICmpInst>(Op0);
3540           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3541             std::swap(LHS, RHS);
3542             std::swap(LHSCst, RHSCst);
3543             std::swap(LHSCC, RHSCC);
3544           }
3545
3546           // At this point, we know we have have two icmp instructions
3547           // comparing a value against two constants and and'ing the result
3548           // together.  Because of the above check, we know that we only have
3549           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3550           // (from the FoldICmpLogical check above), that the two constants 
3551           // are not equal and that the larger constant is on the RHS
3552           assert(LHSCst != RHSCst && "Compares not folded above?");
3553
3554           switch (LHSCC) {
3555           default: assert(0 && "Unknown integer condition code!");
3556           case ICmpInst::ICMP_EQ:
3557             switch (RHSCC) {
3558             default: assert(0 && "Unknown integer condition code!");
3559             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3560             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3561             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3562               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3563             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3564             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3565             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3566               return ReplaceInstUsesWith(I, LHS);
3567             }
3568           case ICmpInst::ICMP_NE:
3569             switch (RHSCC) {
3570             default: assert(0 && "Unknown integer condition code!");
3571             case ICmpInst::ICMP_ULT:
3572               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3573                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3574               break;                        // (X != 13 & X u< 15) -> no change
3575             case ICmpInst::ICMP_SLT:
3576               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3577                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3578               break;                        // (X != 13 & X s< 15) -> no change
3579             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3580             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3581             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3582               return ReplaceInstUsesWith(I, RHS);
3583             case ICmpInst::ICMP_NE:
3584               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3585                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3586                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3587                                                       LHSVal->getName()+".off");
3588                 InsertNewInstBefore(Add, I);
3589                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3590                                     ConstantInt::get(Add->getType(), 1));
3591               }
3592               break;                        // (X != 13 & X != 15) -> no change
3593             }
3594             break;
3595           case ICmpInst::ICMP_ULT:
3596             switch (RHSCC) {
3597             default: assert(0 && "Unknown integer condition code!");
3598             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3599             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3600               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3601             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3602               break;
3603             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3604             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3605               return ReplaceInstUsesWith(I, LHS);
3606             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3607               break;
3608             }
3609             break;
3610           case ICmpInst::ICMP_SLT:
3611             switch (RHSCC) {
3612             default: assert(0 && "Unknown integer condition code!");
3613             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3614             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3615               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3616             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3617               break;
3618             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3619             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3620               return ReplaceInstUsesWith(I, LHS);
3621             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3622               break;
3623             }
3624             break;
3625           case ICmpInst::ICMP_UGT:
3626             switch (RHSCC) {
3627             default: assert(0 && "Unknown integer condition code!");
3628             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3629               return ReplaceInstUsesWith(I, LHS);
3630             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3631               return ReplaceInstUsesWith(I, RHS);
3632             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3633               break;
3634             case ICmpInst::ICMP_NE:
3635               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3636                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3637               break;                        // (X u> 13 & X != 15) -> no change
3638             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3639               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3640                                      true, I);
3641             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3642               break;
3643             }
3644             break;
3645           case ICmpInst::ICMP_SGT:
3646             switch (RHSCC) {
3647             default: assert(0 && "Unknown integer condition code!");
3648             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3649             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3650               return ReplaceInstUsesWith(I, RHS);
3651             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3652               break;
3653             case ICmpInst::ICMP_NE:
3654               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3655                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3656               break;                        // (X s> 13 & X != 15) -> no change
3657             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3658               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3659                                      true, I);
3660             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3661               break;
3662             }
3663             break;
3664           }
3665         }
3666   }
3667
3668   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3669   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3670     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3671       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3672         const Type *SrcTy = Op0C->getOperand(0)->getType();
3673         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3674             // Only do this if the casts both really cause code to be generated.
3675             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3676                               I.getType(), TD) &&
3677             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3678                               I.getType(), TD)) {
3679           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3680                                                          Op1C->getOperand(0),
3681                                                          I.getName());
3682           InsertNewInstBefore(NewOp, I);
3683           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3684         }
3685       }
3686     
3687   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3688   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3689     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3690       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3691           SI0->getOperand(1) == SI1->getOperand(1) &&
3692           (SI0->hasOneUse() || SI1->hasOneUse())) {
3693         Instruction *NewOp =
3694           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3695                                                         SI1->getOperand(0),
3696                                                         SI0->getName()), I);
3697         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3698                                       SI1->getOperand(1));
3699       }
3700   }
3701
3702   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3703   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3704     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3705       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3706           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3707         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3708           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3709             // If either of the constants are nans, then the whole thing returns
3710             // false.
3711             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3712               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3713             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3714                                 RHS->getOperand(0));
3715           }
3716     }
3717   }
3718       
3719   return Changed ? &I : 0;
3720 }
3721
3722 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3723 /// in the result.  If it does, and if the specified byte hasn't been filled in
3724 /// yet, fill it in and return false.
3725 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3726   Instruction *I = dyn_cast<Instruction>(V);
3727   if (I == 0) return true;
3728
3729   // If this is an or instruction, it is an inner node of the bswap.
3730   if (I->getOpcode() == Instruction::Or)
3731     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3732            CollectBSwapParts(I->getOperand(1), ByteValues);
3733   
3734   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3735   // If this is a shift by a constant int, and it is "24", then its operand
3736   // defines a byte.  We only handle unsigned types here.
3737   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3738     // Not shifting the entire input by N-1 bytes?
3739     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3740         8*(ByteValues.size()-1))
3741       return true;
3742     
3743     unsigned DestNo;
3744     if (I->getOpcode() == Instruction::Shl) {
3745       // X << 24 defines the top byte with the lowest of the input bytes.
3746       DestNo = ByteValues.size()-1;
3747     } else {
3748       // X >>u 24 defines the low byte with the highest of the input bytes.
3749       DestNo = 0;
3750     }
3751     
3752     // If the destination byte value is already defined, the values are or'd
3753     // together, which isn't a bswap (unless it's an or of the same bits).
3754     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3755       return true;
3756     ByteValues[DestNo] = I->getOperand(0);
3757     return false;
3758   }
3759   
3760   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3761   // don't have this.
3762   Value *Shift = 0, *ShiftLHS = 0;
3763   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3764   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3765       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3766     return true;
3767   Instruction *SI = cast<Instruction>(Shift);
3768
3769   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3770   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3771       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3772     return true;
3773   
3774   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3775   unsigned DestByte;
3776   if (AndAmt->getValue().getActiveBits() > 64)
3777     return true;
3778   uint64_t AndAmtVal = AndAmt->getZExtValue();
3779   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3780     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3781       break;
3782   // Unknown mask for bswap.
3783   if (DestByte == ByteValues.size()) return true;
3784   
3785   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3786   unsigned SrcByte;
3787   if (SI->getOpcode() == Instruction::Shl)
3788     SrcByte = DestByte - ShiftBytes;
3789   else
3790     SrcByte = DestByte + ShiftBytes;
3791   
3792   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3793   if (SrcByte != ByteValues.size()-DestByte-1)
3794     return true;
3795   
3796   // If the destination byte value is already defined, the values are or'd
3797   // together, which isn't a bswap (unless it's an or of the same bits).
3798   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3799     return true;
3800   ByteValues[DestByte] = SI->getOperand(0);
3801   return false;
3802 }
3803
3804 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3805 /// If so, insert the new bswap intrinsic and return it.
3806 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3807   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3808   if (!ITy || ITy->getBitWidth() % 16) 
3809     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3810   
3811   /// ByteValues - For each byte of the result, we keep track of which value
3812   /// defines each byte.
3813   SmallVector<Value*, 8> ByteValues;
3814   ByteValues.resize(ITy->getBitWidth()/8);
3815     
3816   // Try to find all the pieces corresponding to the bswap.
3817   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3818       CollectBSwapParts(I.getOperand(1), ByteValues))
3819     return 0;
3820   
3821   // Check to see if all of the bytes come from the same value.
3822   Value *V = ByteValues[0];
3823   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3824   
3825   // Check to make sure that all of the bytes come from the same value.
3826   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3827     if (ByteValues[i] != V)
3828       return 0;
3829   const Type *Tys[] = { ITy };
3830   Module *M = I.getParent()->getParent()->getParent();
3831   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3832   return new CallInst(F, V);
3833 }
3834
3835
3836 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3837   bool Changed = SimplifyCommutative(I);
3838   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3839
3840   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3841     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3842
3843   // or X, X = X
3844   if (Op0 == Op1)
3845     return ReplaceInstUsesWith(I, Op0);
3846
3847   // See if we can simplify any instructions used by the instruction whose sole 
3848   // purpose is to compute bits we don't care about.
3849   if (!isa<VectorType>(I.getType())) {
3850     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3851     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3852     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3853                              KnownZero, KnownOne))
3854       return &I;
3855   } else if (isa<ConstantAggregateZero>(Op1)) {
3856     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3857   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3858     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3859       return ReplaceInstUsesWith(I, I.getOperand(1));
3860   }
3861     
3862
3863   
3864   // or X, -1 == -1
3865   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3866     ConstantInt *C1 = 0; Value *X = 0;
3867     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3868     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3869       Instruction *Or = BinaryOperator::createOr(X, RHS);
3870       InsertNewInstBefore(Or, I);
3871       Or->takeName(Op0);
3872       return BinaryOperator::createAnd(Or, 
3873                ConstantInt::get(RHS->getValue() | C1->getValue()));
3874     }
3875
3876     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3877     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3878       Instruction *Or = BinaryOperator::createOr(X, RHS);
3879       InsertNewInstBefore(Or, I);
3880       Or->takeName(Op0);
3881       return BinaryOperator::createXor(Or,
3882                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3883     }
3884
3885     // Try to fold constant and into select arguments.
3886     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3887       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3888         return R;
3889     if (isa<PHINode>(Op0))
3890       if (Instruction *NV = FoldOpIntoPhi(I))
3891         return NV;
3892   }
3893
3894   Value *A = 0, *B = 0;
3895   ConstantInt *C1 = 0, *C2 = 0;
3896
3897   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3898     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3899       return ReplaceInstUsesWith(I, Op1);
3900   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3901     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3902       return ReplaceInstUsesWith(I, Op0);
3903
3904   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3905   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3906   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3907       match(Op1, m_Or(m_Value(), m_Value())) ||
3908       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3909        match(Op1, m_Shift(m_Value(), m_Value())))) {
3910     if (Instruction *BSwap = MatchBSwap(I))
3911       return BSwap;
3912   }
3913   
3914   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3915   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3916       MaskedValueIsZero(Op1, C1->getValue())) {
3917     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3918     InsertNewInstBefore(NOr, I);
3919     NOr->takeName(Op0);
3920     return BinaryOperator::createXor(NOr, C1);
3921   }
3922
3923   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3924   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3925       MaskedValueIsZero(Op0, C1->getValue())) {
3926     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3927     InsertNewInstBefore(NOr, I);
3928     NOr->takeName(Op0);
3929     return BinaryOperator::createXor(NOr, C1);
3930   }
3931
3932   // (A & C)|(B & D)
3933   Value *C = 0, *D = 0;
3934   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3935       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3936     Value *V1 = 0, *V2 = 0, *V3 = 0;
3937     C1 = dyn_cast<ConstantInt>(C);
3938     C2 = dyn_cast<ConstantInt>(D);
3939     if (C1 && C2) {  // (A & C1)|(B & C2)
3940       // If we have: ((V + N) & C1) | (V & C2)
3941       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3942       // replace with V+N.
3943       if (C1->getValue() == ~C2->getValue()) {
3944         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3945             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3946           // Add commutes, try both ways.
3947           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3948             return ReplaceInstUsesWith(I, A);
3949           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3950             return ReplaceInstUsesWith(I, A);
3951         }
3952         // Or commutes, try both ways.
3953         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3954             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3955           // Add commutes, try both ways.
3956           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3957             return ReplaceInstUsesWith(I, B);
3958           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3959             return ReplaceInstUsesWith(I, B);
3960         }
3961       }
3962       V1 = 0; V2 = 0; V3 = 0;
3963     }
3964     
3965     // Check to see if we have any common things being and'ed.  If so, find the
3966     // terms for V1 & (V2|V3).
3967     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3968       if (A == B)      // (A & C)|(A & D) == A & (C|D)
3969         V1 = A, V2 = C, V3 = D;
3970       else if (A == D) // (A & C)|(B & A) == A & (B|C)
3971         V1 = A, V2 = B, V3 = C;
3972       else if (C == B) // (A & C)|(C & D) == C & (A|D)
3973         V1 = C, V2 = A, V3 = D;
3974       else if (C == D) // (A & C)|(B & C) == C & (A|B)
3975         V1 = C, V2 = A, V3 = B;
3976       
3977       if (V1) {
3978         Value *Or =
3979           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3980         return BinaryOperator::createAnd(V1, Or);
3981       }
3982     }
3983   }
3984   
3985   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3986   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3987     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3988       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3989           SI0->getOperand(1) == SI1->getOperand(1) &&
3990           (SI0->hasOneUse() || SI1->hasOneUse())) {
3991         Instruction *NewOp =
3992         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3993                                                      SI1->getOperand(0),
3994                                                      SI0->getName()), I);
3995         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3996                                       SI1->getOperand(1));
3997       }
3998   }
3999
4000   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4001     if (A == Op1)   // ~A | A == -1
4002       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4003   } else {
4004     A = 0;
4005   }
4006   // Note, A is still live here!
4007   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4008     if (Op0 == B)
4009       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4010
4011     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4012     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4013       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4014                                               I.getName()+".demorgan"), I);
4015       return BinaryOperator::createNot(And);
4016     }
4017   }
4018
4019   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4020   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4021     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4022       return R;
4023
4024     Value *LHSVal, *RHSVal;
4025     ConstantInt *LHSCst, *RHSCst;
4026     ICmpInst::Predicate LHSCC, RHSCC;
4027     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4028       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4029         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4030             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4031             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4032             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4033             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4034             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4035             // We can't fold (ugt x, C) | (sgt x, C2).
4036             PredicatesFoldable(LHSCC, RHSCC)) {
4037           // Ensure that the larger constant is on the RHS.
4038           ICmpInst *LHS = cast<ICmpInst>(Op0);
4039           bool NeedsSwap;
4040           if (ICmpInst::isSignedPredicate(LHSCC))
4041             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4042           else
4043             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4044             
4045           if (NeedsSwap) {
4046             std::swap(LHS, RHS);
4047             std::swap(LHSCst, RHSCst);
4048             std::swap(LHSCC, RHSCC);
4049           }
4050
4051           // At this point, we know we have have two icmp instructions
4052           // comparing a value against two constants and or'ing the result
4053           // together.  Because of the above check, we know that we only have
4054           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4055           // FoldICmpLogical check above), that the two constants are not
4056           // equal.
4057           assert(LHSCst != RHSCst && "Compares not folded above?");
4058
4059           switch (LHSCC) {
4060           default: assert(0 && "Unknown integer condition code!");
4061           case ICmpInst::ICMP_EQ:
4062             switch (RHSCC) {
4063             default: assert(0 && "Unknown integer condition code!");
4064             case ICmpInst::ICMP_EQ:
4065               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4066                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4067                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4068                                                       LHSVal->getName()+".off");
4069                 InsertNewInstBefore(Add, I);
4070                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4071                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4072               }
4073               break;                         // (X == 13 | X == 15) -> no change
4074             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4075             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4076               break;
4077             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4078             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4079             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4080               return ReplaceInstUsesWith(I, RHS);
4081             }
4082             break;
4083           case ICmpInst::ICMP_NE:
4084             switch (RHSCC) {
4085             default: assert(0 && "Unknown integer condition code!");
4086             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4087             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4088             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4089               return ReplaceInstUsesWith(I, LHS);
4090             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4091             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4092             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4093               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4094             }
4095             break;
4096           case ICmpInst::ICMP_ULT:
4097             switch (RHSCC) {
4098             default: assert(0 && "Unknown integer condition code!");
4099             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4100               break;
4101             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4102               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4103               // this can cause overflow.
4104               if (RHSCst->isMaxValue(false))
4105                 return ReplaceInstUsesWith(I, LHS);
4106               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4107                                      false, I);
4108             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4109               break;
4110             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4111             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4112               return ReplaceInstUsesWith(I, RHS);
4113             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4114               break;
4115             }
4116             break;
4117           case ICmpInst::ICMP_SLT:
4118             switch (RHSCC) {
4119             default: assert(0 && "Unknown integer condition code!");
4120             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4121               break;
4122             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4123               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4124               // this can cause overflow.
4125               if (RHSCst->isMaxValue(true))
4126                 return ReplaceInstUsesWith(I, LHS);
4127               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4128                                      false, I);
4129             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4130               break;
4131             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4132             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4133               return ReplaceInstUsesWith(I, RHS);
4134             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4135               break;
4136             }
4137             break;
4138           case ICmpInst::ICMP_UGT:
4139             switch (RHSCC) {
4140             default: assert(0 && "Unknown integer condition code!");
4141             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4142             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4143               return ReplaceInstUsesWith(I, LHS);
4144             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4145               break;
4146             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4147             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4148               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4149             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4150               break;
4151             }
4152             break;
4153           case ICmpInst::ICMP_SGT:
4154             switch (RHSCC) {
4155             default: assert(0 && "Unknown integer condition code!");
4156             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4157             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4158               return ReplaceInstUsesWith(I, LHS);
4159             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4160               break;
4161             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4162             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4163               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4164             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4165               break;
4166             }
4167             break;
4168           }
4169         }
4170   }
4171     
4172   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4173   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4174     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4175       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4176         const Type *SrcTy = Op0C->getOperand(0)->getType();
4177         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4178             // Only do this if the casts both really cause code to be generated.
4179             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4180                               I.getType(), TD) &&
4181             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4182                               I.getType(), TD)) {
4183           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4184                                                         Op1C->getOperand(0),
4185                                                         I.getName());
4186           InsertNewInstBefore(NewOp, I);
4187           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4188         }
4189       }
4190   }
4191   
4192     
4193   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4194   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4195     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4196       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4197           RHS->getPredicate() == FCmpInst::FCMP_UNO)
4198         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4199           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4200             // If either of the constants are nans, then the whole thing returns
4201             // true.
4202             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4203               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4204             
4205             // Otherwise, no need to compare the two constants, compare the
4206             // rest.
4207             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4208                                 RHS->getOperand(0));
4209           }
4210     }
4211   }
4212
4213   return Changed ? &I : 0;
4214 }
4215
4216 // XorSelf - Implements: X ^ X --> 0
4217 struct XorSelf {
4218   Value *RHS;
4219   XorSelf(Value *rhs) : RHS(rhs) {}
4220   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4221   Instruction *apply(BinaryOperator &Xor) const {
4222     return &Xor;
4223   }
4224 };
4225
4226
4227 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4228   bool Changed = SimplifyCommutative(I);
4229   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4230
4231   if (isa<UndefValue>(Op1))
4232     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4233
4234   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4235   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4236     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4237     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4238   }
4239   
4240   // See if we can simplify any instructions used by the instruction whose sole 
4241   // purpose is to compute bits we don't care about.
4242   if (!isa<VectorType>(I.getType())) {
4243     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4244     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4245     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4246                              KnownZero, KnownOne))
4247       return &I;
4248   } else if (isa<ConstantAggregateZero>(Op1)) {
4249     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4250   }
4251
4252   // Is this a ~ operation?
4253   if (Value *NotOp = dyn_castNotVal(&I)) {
4254     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4255     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4256     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4257       if (Op0I->getOpcode() == Instruction::And || 
4258           Op0I->getOpcode() == Instruction::Or) {
4259         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4260         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4261           Instruction *NotY =
4262             BinaryOperator::createNot(Op0I->getOperand(1),
4263                                       Op0I->getOperand(1)->getName()+".not");
4264           InsertNewInstBefore(NotY, I);
4265           if (Op0I->getOpcode() == Instruction::And)
4266             return BinaryOperator::createOr(Op0NotVal, NotY);
4267           else
4268             return BinaryOperator::createAnd(Op0NotVal, NotY);
4269         }
4270       }
4271     }
4272   }
4273   
4274   
4275   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4276     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4277     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4278       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4279         return new ICmpInst(ICI->getInversePredicate(),
4280                             ICI->getOperand(0), ICI->getOperand(1));
4281
4282       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4283         return new FCmpInst(FCI->getInversePredicate(),
4284                             FCI->getOperand(0), FCI->getOperand(1));
4285     }
4286
4287     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4288       // ~(c-X) == X-c-1 == X+(-c-1)
4289       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4290         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4291           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4292           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4293                                               ConstantInt::get(I.getType(), 1));
4294           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4295         }
4296           
4297       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4298         if (Op0I->getOpcode() == Instruction::Add) {
4299           // ~(X-c) --> (-c-1)-X
4300           if (RHS->isAllOnesValue()) {
4301             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4302             return BinaryOperator::createSub(
4303                            ConstantExpr::getSub(NegOp0CI,
4304                                              ConstantInt::get(I.getType(), 1)),
4305                                           Op0I->getOperand(0));
4306           } else if (RHS->getValue().isSignBit()) {
4307             // (X + C) ^ signbit -> (X + C + signbit)
4308             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4309             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4310
4311           }
4312         } else if (Op0I->getOpcode() == Instruction::Or) {
4313           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4314           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4315             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4316             // Anything in both C1 and C2 is known to be zero, remove it from
4317             // NewRHS.
4318             Constant *CommonBits = And(Op0CI, RHS);
4319             NewRHS = ConstantExpr::getAnd(NewRHS, 
4320                                           ConstantExpr::getNot(CommonBits));
4321             AddToWorkList(Op0I);
4322             I.setOperand(0, Op0I->getOperand(0));
4323             I.setOperand(1, NewRHS);
4324             return &I;
4325           }
4326         }
4327     }
4328
4329     // Try to fold constant and into select arguments.
4330     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4331       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4332         return R;
4333     if (isa<PHINode>(Op0))
4334       if (Instruction *NV = FoldOpIntoPhi(I))
4335         return NV;
4336   }
4337
4338   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4339     if (X == Op1)
4340       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4341
4342   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4343     if (X == Op0)
4344       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4345
4346   
4347   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4348   if (Op1I) {
4349     Value *A, *B;
4350     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4351       if (A == Op0) {              // B^(B|A) == (A|B)^B
4352         Op1I->swapOperands();
4353         I.swapOperands();
4354         std::swap(Op0, Op1);
4355       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4356         I.swapOperands();     // Simplified below.
4357         std::swap(Op0, Op1);
4358       }
4359     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4360       if (Op0 == A)                                          // A^(A^B) == B
4361         return ReplaceInstUsesWith(I, B);
4362       else if (Op0 == B)                                     // A^(B^A) == B
4363         return ReplaceInstUsesWith(I, A);
4364     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4365       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4366         Op1I->swapOperands();
4367         std::swap(A, B);
4368       }
4369       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4370         I.swapOperands();     // Simplified below.
4371         std::swap(Op0, Op1);
4372       }
4373     }
4374   }
4375   
4376   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4377   if (Op0I) {
4378     Value *A, *B;
4379     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4380       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4381         std::swap(A, B);
4382       if (B == Op1) {                                // (A|B)^B == A & ~B
4383         Instruction *NotB =
4384           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4385         return BinaryOperator::createAnd(A, NotB);
4386       }
4387     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4388       if (Op1 == A)                                          // (A^B)^A == B
4389         return ReplaceInstUsesWith(I, B);
4390       else if (Op1 == B)                                     // (B^A)^A == B
4391         return ReplaceInstUsesWith(I, A);
4392     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4393       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4394         std::swap(A, B);
4395       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4396           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4397         Instruction *N =
4398           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4399         return BinaryOperator::createAnd(N, Op1);
4400       }
4401     }
4402   }
4403   
4404   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4405   if (Op0I && Op1I && Op0I->isShift() && 
4406       Op0I->getOpcode() == Op1I->getOpcode() && 
4407       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4408       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4409     Instruction *NewOp =
4410       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4411                                                     Op1I->getOperand(0),
4412                                                     Op0I->getName()), I);
4413     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4414                                   Op1I->getOperand(1));
4415   }
4416     
4417   if (Op0I && Op1I) {
4418     Value *A, *B, *C, *D;
4419     // (A & B)^(A | B) -> A ^ B
4420     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4421         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4422       if ((A == C && B == D) || (A == D && B == C)) 
4423         return BinaryOperator::createXor(A, B);
4424     }
4425     // (A | B)^(A & B) -> A ^ B
4426     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4427         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4428       if ((A == C && B == D) || (A == D && B == C)) 
4429         return BinaryOperator::createXor(A, B);
4430     }
4431     
4432     // (A & B)^(C & D)
4433     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4434         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4435         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4436       // (X & Y)^(X & Y) -> (Y^Z) & X
4437       Value *X = 0, *Y = 0, *Z = 0;
4438       if (A == C)
4439         X = A, Y = B, Z = D;
4440       else if (A == D)
4441         X = A, Y = B, Z = C;
4442       else if (B == C)
4443         X = B, Y = A, Z = D;
4444       else if (B == D)
4445         X = B, Y = A, Z = C;
4446       
4447       if (X) {
4448         Instruction *NewOp =
4449         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4450         return BinaryOperator::createAnd(NewOp, X);
4451       }
4452     }
4453   }
4454     
4455   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4456   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4457     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4458       return R;
4459
4460   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4461   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4462     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4463       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4464         const Type *SrcTy = Op0C->getOperand(0)->getType();
4465         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4466             // Only do this if the casts both really cause code to be generated.
4467             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4468                               I.getType(), TD) &&
4469             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4470                               I.getType(), TD)) {
4471           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4472                                                          Op1C->getOperand(0),
4473                                                          I.getName());
4474           InsertNewInstBefore(NewOp, I);
4475           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4476         }
4477       }
4478   }
4479   return Changed ? &I : 0;
4480 }
4481
4482 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4483 /// overflowed for this type.
4484 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4485                             ConstantInt *In2, bool IsSigned = false) {
4486   Result = cast<ConstantInt>(Add(In1, In2));
4487
4488   if (IsSigned)
4489     if (In2->getValue().isNegative())
4490       return Result->getValue().sgt(In1->getValue());
4491     else
4492       return Result->getValue().slt(In1->getValue());
4493   else
4494     return Result->getValue().ult(In1->getValue());
4495 }
4496
4497 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4498 /// code necessary to compute the offset from the base pointer (without adding
4499 /// in the base pointer).  Return the result as a signed integer of intptr size.
4500 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4501   TargetData &TD = IC.getTargetData();
4502   gep_type_iterator GTI = gep_type_begin(GEP);
4503   const Type *IntPtrTy = TD.getIntPtrType();
4504   Value *Result = Constant::getNullValue(IntPtrTy);
4505
4506   // Build a mask for high order bits.
4507   unsigned IntPtrWidth = TD.getPointerSize()*8;
4508   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4509
4510   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4511     Value *Op = GEP->getOperand(i);
4512     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4513     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4514       if (OpC->isZero()) continue;
4515       
4516       // Handle a struct index, which adds its field offset to the pointer.
4517       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4518         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4519         
4520         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4521           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4522         else
4523           Result = IC.InsertNewInstBefore(
4524                    BinaryOperator::createAdd(Result,
4525                                              ConstantInt::get(IntPtrTy, Size),
4526                                              GEP->getName()+".offs"), I);
4527         continue;
4528       }
4529       
4530       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4531       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4532       Scale = ConstantExpr::getMul(OC, Scale);
4533       if (Constant *RC = dyn_cast<Constant>(Result))
4534         Result = ConstantExpr::getAdd(RC, Scale);
4535       else {
4536         // Emit an add instruction.
4537         Result = IC.InsertNewInstBefore(
4538            BinaryOperator::createAdd(Result, Scale,
4539                                      GEP->getName()+".offs"), I);
4540       }
4541       continue;
4542     }
4543     // Convert to correct type.
4544     if (Op->getType() != IntPtrTy) {
4545       if (Constant *OpC = dyn_cast<Constant>(Op))
4546         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4547       else
4548         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4549                                                  Op->getName()+".c"), I);
4550     }
4551     if (Size != 1) {
4552       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4553       if (Constant *OpC = dyn_cast<Constant>(Op))
4554         Op = ConstantExpr::getMul(OpC, Scale);
4555       else    // We'll let instcombine(mul) convert this to a shl if possible.
4556         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4557                                                   GEP->getName()+".idx"), I);
4558     }
4559
4560     // Emit an add instruction.
4561     if (isa<Constant>(Op) && isa<Constant>(Result))
4562       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4563                                     cast<Constant>(Result));
4564     else
4565       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4566                                                   GEP->getName()+".offs"), I);
4567   }
4568   return Result;
4569 }
4570
4571 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4572 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4573 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4574                                        ICmpInst::Predicate Cond,
4575                                        Instruction &I) {
4576   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4577
4578   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4579     if (isa<PointerType>(CI->getOperand(0)->getType()))
4580       RHS = CI->getOperand(0);
4581
4582   Value *PtrBase = GEPLHS->getOperand(0);
4583   if (PtrBase == RHS) {
4584     // As an optimization, we don't actually have to compute the actual value of
4585     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4586     // each index is zero or not.
4587     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4588       Instruction *InVal = 0;
4589       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4590       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4591         bool EmitIt = true;
4592         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4593           if (isa<UndefValue>(C))  // undef index -> undef.
4594             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4595           if (C->isNullValue())
4596             EmitIt = false;
4597           else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
4598             EmitIt = false;  // This is indexing into a zero sized array?
4599           } else if (isa<ConstantInt>(C))
4600             return ReplaceInstUsesWith(I, // No comparison is needed here.
4601                                  ConstantInt::get(Type::Int1Ty, 
4602                                                   Cond == ICmpInst::ICMP_NE));
4603         }
4604
4605         if (EmitIt) {
4606           Instruction *Comp =
4607             new ICmpInst(Cond, GEPLHS->getOperand(i),
4608                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4609           if (InVal == 0)
4610             InVal = Comp;
4611           else {
4612             InVal = InsertNewInstBefore(InVal, I);
4613             InsertNewInstBefore(Comp, I);
4614             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4615               InVal = BinaryOperator::createOr(InVal, Comp);
4616             else                              // True if all are equal
4617               InVal = BinaryOperator::createAnd(InVal, Comp);
4618           }
4619         }
4620       }
4621
4622       if (InVal)
4623         return InVal;
4624       else
4625         // No comparison is needed here, all indexes = 0
4626         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4627                                                 Cond == ICmpInst::ICMP_EQ));
4628     }
4629
4630     // Only lower this if the icmp is the only user of the GEP or if we expect
4631     // the result to fold to a constant!
4632     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4633       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4634       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4635       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4636                           Constant::getNullValue(Offset->getType()));
4637     }
4638   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4639     // If the base pointers are different, but the indices are the same, just
4640     // compare the base pointer.
4641     if (PtrBase != GEPRHS->getOperand(0)) {
4642       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4643       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4644                         GEPRHS->getOperand(0)->getType();
4645       if (IndicesTheSame)
4646         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4647           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4648             IndicesTheSame = false;
4649             break;
4650           }
4651
4652       // If all indices are the same, just compare the base pointers.
4653       if (IndicesTheSame)
4654         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4655                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4656
4657       // Otherwise, the base pointers are different and the indices are
4658       // different, bail out.
4659       return 0;
4660     }
4661
4662     // If one of the GEPs has all zero indices, recurse.
4663     bool AllZeros = true;
4664     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4665       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4666           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4667         AllZeros = false;
4668         break;
4669       }
4670     if (AllZeros)
4671       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4672                           ICmpInst::getSwappedPredicate(Cond), I);
4673
4674     // If the other GEP has all zero indices, recurse.
4675     AllZeros = true;
4676     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4677       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4678           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4679         AllZeros = false;
4680         break;
4681       }
4682     if (AllZeros)
4683       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4684
4685     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4686       // If the GEPs only differ by one index, compare it.
4687       unsigned NumDifferences = 0;  // Keep track of # differences.
4688       unsigned DiffOperand = 0;     // The operand that differs.
4689       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4690         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4691           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4692                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4693             // Irreconcilable differences.
4694             NumDifferences = 2;
4695             break;
4696           } else {
4697             if (NumDifferences++) break;
4698             DiffOperand = i;
4699           }
4700         }
4701
4702       if (NumDifferences == 0)   // SAME GEP?
4703         return ReplaceInstUsesWith(I, // No comparison is needed here.
4704                                    ConstantInt::get(Type::Int1Ty,
4705                                                     isTrueWhenEqual(Cond)));
4706
4707       else if (NumDifferences == 1) {
4708         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4709         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4710         // Make sure we do a signed comparison here.
4711         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4712       }
4713     }
4714
4715     // Only lower this if the icmp is the only user of the GEP or if we expect
4716     // the result to fold to a constant!
4717     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4718         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4719       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4720       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4721       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4722       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4723     }
4724   }
4725   return 0;
4726 }
4727
4728 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4729   bool Changed = SimplifyCompare(I);
4730   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4731
4732   // Fold trivial predicates.
4733   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4734     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4735   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4736     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4737   
4738   // Simplify 'fcmp pred X, X'
4739   if (Op0 == Op1) {
4740     switch (I.getPredicate()) {
4741     default: assert(0 && "Unknown predicate!");
4742     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4743     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4744     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4745       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4746     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4747     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4748     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4749       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4750       
4751     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4752     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4753     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4754     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4755       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4756       I.setPredicate(FCmpInst::FCMP_UNO);
4757       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4758       return &I;
4759       
4760     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4761     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4762     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4763     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4764       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4765       I.setPredicate(FCmpInst::FCMP_ORD);
4766       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4767       return &I;
4768     }
4769   }
4770     
4771   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4772     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4773
4774   // Handle fcmp with constant RHS
4775   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4776     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4777       switch (LHSI->getOpcode()) {
4778       case Instruction::PHI:
4779         if (Instruction *NV = FoldOpIntoPhi(I))
4780           return NV;
4781         break;
4782       case Instruction::Select:
4783         // If either operand of the select is a constant, we can fold the
4784         // comparison into the select arms, which will cause one to be
4785         // constant folded and the select turned into a bitwise or.
4786         Value *Op1 = 0, *Op2 = 0;
4787         if (LHSI->hasOneUse()) {
4788           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4789             // Fold the known value into the constant operand.
4790             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4791             // Insert a new FCmp of the other select operand.
4792             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4793                                                       LHSI->getOperand(2), RHSC,
4794                                                       I.getName()), I);
4795           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4796             // Fold the known value into the constant operand.
4797             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4798             // Insert a new FCmp of the other select operand.
4799             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4800                                                       LHSI->getOperand(1), RHSC,
4801                                                       I.getName()), I);
4802           }
4803         }
4804
4805         if (Op1)
4806           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4807         break;
4808       }
4809   }
4810
4811   return Changed ? &I : 0;
4812 }
4813
4814 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4815   bool Changed = SimplifyCompare(I);
4816   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4817   const Type *Ty = Op0->getType();
4818
4819   // icmp X, X
4820   if (Op0 == Op1)
4821     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4822                                                    isTrueWhenEqual(I)));
4823
4824   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4825     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4826
4827   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4828   // addresses never equal each other!  We already know that Op0 != Op1.
4829   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4830        isa<ConstantPointerNull>(Op0)) &&
4831       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4832        isa<ConstantPointerNull>(Op1)))
4833     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4834                                                    !isTrueWhenEqual(I)));
4835
4836   // icmp's with boolean values can always be turned into bitwise operations
4837   if (Ty == Type::Int1Ty) {
4838     switch (I.getPredicate()) {
4839     default: assert(0 && "Invalid icmp instruction!");
4840     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4841       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4842       InsertNewInstBefore(Xor, I);
4843       return BinaryOperator::createNot(Xor);
4844     }
4845     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4846       return BinaryOperator::createXor(Op0, Op1);
4847
4848     case ICmpInst::ICMP_UGT:
4849     case ICmpInst::ICMP_SGT:
4850       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4851       // FALL THROUGH
4852     case ICmpInst::ICMP_ULT:
4853     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4854       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4855       InsertNewInstBefore(Not, I);
4856       return BinaryOperator::createAnd(Not, Op1);
4857     }
4858     case ICmpInst::ICMP_UGE:
4859     case ICmpInst::ICMP_SGE:
4860       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4861       // FALL THROUGH
4862     case ICmpInst::ICMP_ULE:
4863     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4864       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4865       InsertNewInstBefore(Not, I);
4866       return BinaryOperator::createOr(Not, Op1);
4867     }
4868     }
4869   }
4870
4871   // See if we are doing a comparison between a constant and an instruction that
4872   // can be folded into the comparison.
4873   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4874     switch (I.getPredicate()) {
4875     default: break;
4876     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4877       if (CI->isMinValue(false))
4878         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4879       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4880         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4881       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4882         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4883       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4884       if (CI->isMinValue(true))
4885         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4886                             ConstantInt::getAllOnesValue(Op0->getType()));
4887           
4888       break;
4889
4890     case ICmpInst::ICMP_SLT:
4891       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4892         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4893       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4894         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4895       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4896         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4897       break;
4898
4899     case ICmpInst::ICMP_UGT:
4900       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4901         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4902       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4903         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4904       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4905         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4906         
4907       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4908       if (CI->isMaxValue(true))
4909         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4910                             ConstantInt::getNullValue(Op0->getType()));
4911       break;
4912
4913     case ICmpInst::ICMP_SGT:
4914       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4915         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4916       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4917         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4918       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4919         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4920       break;
4921
4922     case ICmpInst::ICMP_ULE:
4923       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4924         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4925       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4926         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4927       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4928         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4929       break;
4930
4931     case ICmpInst::ICMP_SLE:
4932       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4933         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4934       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4935         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4936       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4937         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4938       break;
4939
4940     case ICmpInst::ICMP_UGE:
4941       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4942         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4943       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4944         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4945       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4946         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4947       break;
4948
4949     case ICmpInst::ICMP_SGE:
4950       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4951         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4952       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4953         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4954       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4955         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4956       break;
4957     }
4958
4959     // If we still have a icmp le or icmp ge instruction, turn it into the
4960     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4961     // already been handled above, this requires little checking.
4962     //
4963     switch (I.getPredicate()) {
4964     default: break;
4965     case ICmpInst::ICMP_ULE: 
4966       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4967     case ICmpInst::ICMP_SLE:
4968       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4969     case ICmpInst::ICMP_UGE:
4970       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4971     case ICmpInst::ICMP_SGE:
4972       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4973     }
4974     
4975     // See if we can fold the comparison based on bits known to be zero or one
4976     // in the input.  If this comparison is a normal comparison, it demands all
4977     // bits, if it is a sign bit comparison, it only demands the sign bit.
4978     
4979     bool UnusedBit;
4980     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4981     
4982     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4983     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4984     if (SimplifyDemandedBits(Op0, 
4985                              isSignBit ? APInt::getSignBit(BitWidth)
4986                                        : APInt::getAllOnesValue(BitWidth),
4987                              KnownZero, KnownOne, 0))
4988       return &I;
4989         
4990     // Given the known and unknown bits, compute a range that the LHS could be
4991     // in.
4992     if ((KnownOne | KnownZero) != 0) {
4993       // Compute the Min, Max and RHS values based on the known bits. For the
4994       // EQ and NE we use unsigned values.
4995       APInt Min(BitWidth, 0), Max(BitWidth, 0);
4996       const APInt& RHSVal = CI->getValue();
4997       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4998         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4999                                                Max);
5000       } else {
5001         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5002                                                  Max);
5003       }
5004       switch (I.getPredicate()) {  // LE/GE have been folded already.
5005       default: assert(0 && "Unknown icmp opcode!");
5006       case ICmpInst::ICMP_EQ:
5007         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5008           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5009         break;
5010       case ICmpInst::ICMP_NE:
5011         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5012           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5013         break;
5014       case ICmpInst::ICMP_ULT:
5015         if (Max.ult(RHSVal))
5016           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5017         if (Min.uge(RHSVal))
5018           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5019         break;
5020       case ICmpInst::ICMP_UGT:
5021         if (Min.ugt(RHSVal))
5022           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5023         if (Max.ule(RHSVal))
5024           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5025         break;
5026       case ICmpInst::ICMP_SLT:
5027         if (Max.slt(RHSVal))
5028           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5029         if (Min.sgt(RHSVal))
5030           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5031         break;
5032       case ICmpInst::ICMP_SGT: 
5033         if (Min.sgt(RHSVal))
5034           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5035         if (Max.sle(RHSVal))
5036           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5037         break;
5038       }
5039     }
5040           
5041     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5042     // instruction, see if that instruction also has constants so that the 
5043     // instruction can be folded into the icmp 
5044     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5045       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5046         return Res;
5047   }
5048
5049   // Handle icmp with constant (but not simple integer constant) RHS
5050   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5051     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5052       switch (LHSI->getOpcode()) {
5053       case Instruction::GetElementPtr:
5054         if (RHSC->isNullValue()) {
5055           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5056           bool isAllZeros = true;
5057           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5058             if (!isa<Constant>(LHSI->getOperand(i)) ||
5059                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5060               isAllZeros = false;
5061               break;
5062             }
5063           if (isAllZeros)
5064             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5065                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5066         }
5067         break;
5068
5069       case Instruction::PHI:
5070         if (Instruction *NV = FoldOpIntoPhi(I))
5071           return NV;
5072         break;
5073       case Instruction::Select: {
5074         // If either operand of the select is a constant, we can fold the
5075         // comparison into the select arms, which will cause one to be
5076         // constant folded and the select turned into a bitwise or.
5077         Value *Op1 = 0, *Op2 = 0;
5078         if (LHSI->hasOneUse()) {
5079           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5080             // Fold the known value into the constant operand.
5081             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5082             // Insert a new ICmp of the other select operand.
5083             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5084                                                    LHSI->getOperand(2), RHSC,
5085                                                    I.getName()), I);
5086           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5087             // Fold the known value into the constant operand.
5088             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5089             // Insert a new ICmp of the other select operand.
5090             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5091                                                    LHSI->getOperand(1), RHSC,
5092                                                    I.getName()), I);
5093           }
5094         }
5095
5096         if (Op1)
5097           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5098         break;
5099       }
5100       case Instruction::Malloc:
5101         // If we have (malloc != null), and if the malloc has a single use, we
5102         // can assume it is successful and remove the malloc.
5103         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5104           AddToWorkList(LHSI);
5105           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5106                                                          !isTrueWhenEqual(I)));
5107         }
5108         break;
5109       }
5110   }
5111
5112   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5113   if (User *GEP = dyn_castGetElementPtr(Op0))
5114     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5115       return NI;
5116   if (User *GEP = dyn_castGetElementPtr(Op1))
5117     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5118                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5119       return NI;
5120
5121   // Test to see if the operands of the icmp are casted versions of other
5122   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5123   // now.
5124   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5125     if (isa<PointerType>(Op0->getType()) && 
5126         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5127       // We keep moving the cast from the left operand over to the right
5128       // operand, where it can often be eliminated completely.
5129       Op0 = CI->getOperand(0);
5130
5131       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5132       // so eliminate it as well.
5133       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5134         Op1 = CI2->getOperand(0);
5135
5136       // If Op1 is a constant, we can fold the cast into the constant.
5137       if (Op0->getType() != Op1->getType())
5138         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5139           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5140         } else {
5141           // Otherwise, cast the RHS right before the icmp
5142           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5143         }
5144       return new ICmpInst(I.getPredicate(), Op0, Op1);
5145     }
5146   }
5147   
5148   if (isa<CastInst>(Op0)) {
5149     // Handle the special case of: icmp (cast bool to X), <cst>
5150     // This comes up when you have code like
5151     //   int X = A < B;
5152     //   if (X) ...
5153     // For generality, we handle any zero-extension of any operand comparison
5154     // with a constant or another cast from the same type.
5155     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5156       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5157         return R;
5158   }
5159   
5160   if (I.isEquality()) {
5161     Value *A, *B, *C, *D;
5162     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5163       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5164         Value *OtherVal = A == Op1 ? B : A;
5165         return new ICmpInst(I.getPredicate(), OtherVal,
5166                             Constant::getNullValue(A->getType()));
5167       }
5168
5169       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5170         // A^c1 == C^c2 --> A == C^(c1^c2)
5171         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5172           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5173             if (Op1->hasOneUse()) {
5174               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5175               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5176               return new ICmpInst(I.getPredicate(), A,
5177                                   InsertNewInstBefore(Xor, I));
5178             }
5179         
5180         // A^B == A^D -> B == D
5181         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5182         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5183         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5184         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5185       }
5186     }
5187     
5188     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5189         (A == Op0 || B == Op0)) {
5190       // A == (A^B)  ->  B == 0
5191       Value *OtherVal = A == Op0 ? B : A;
5192       return new ICmpInst(I.getPredicate(), OtherVal,
5193                           Constant::getNullValue(A->getType()));
5194     }
5195     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5196       // (A-B) == A  ->  B == 0
5197       return new ICmpInst(I.getPredicate(), B,
5198                           Constant::getNullValue(B->getType()));
5199     }
5200     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5201       // A == (A-B)  ->  B == 0
5202       return new ICmpInst(I.getPredicate(), B,
5203                           Constant::getNullValue(B->getType()));
5204     }
5205     
5206     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5207     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5208         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5209         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5210       Value *X = 0, *Y = 0, *Z = 0;
5211       
5212       if (A == C) {
5213         X = B; Y = D; Z = A;
5214       } else if (A == D) {
5215         X = B; Y = C; Z = A;
5216       } else if (B == C) {
5217         X = A; Y = D; Z = B;
5218       } else if (B == D) {
5219         X = A; Y = C; Z = B;
5220       }
5221       
5222       if (X) {   // Build (X^Y) & Z
5223         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5224         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5225         I.setOperand(0, Op1);
5226         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5227         return &I;
5228       }
5229     }
5230   }
5231   return Changed ? &I : 0;
5232 }
5233
5234
5235 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5236 /// and CmpRHS are both known to be integer constants.
5237 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5238                                           ConstantInt *DivRHS) {
5239   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5240   const APInt &CmpRHSV = CmpRHS->getValue();
5241   
5242   // FIXME: If the operand types don't match the type of the divide 
5243   // then don't attempt this transform. The code below doesn't have the
5244   // logic to deal with a signed divide and an unsigned compare (and
5245   // vice versa). This is because (x /s C1) <s C2  produces different 
5246   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5247   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5248   // work. :(  The if statement below tests that condition and bails 
5249   // if it finds it. 
5250   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5251   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5252     return 0;
5253   if (DivRHS->isZero())
5254     return 0; // The ProdOV computation fails on divide by zero.
5255
5256   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5257   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5258   // C2 (CI). By solving for X we can turn this into a range check 
5259   // instead of computing a divide. 
5260   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5261
5262   // Determine if the product overflows by seeing if the product is
5263   // not equal to the divide. Make sure we do the same kind of divide
5264   // as in the LHS instruction that we're folding. 
5265   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5266                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5267
5268   // Get the ICmp opcode
5269   ICmpInst::Predicate Pred = ICI.getPredicate();
5270
5271   // Figure out the interval that is being checked.  For example, a comparison
5272   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5273   // Compute this interval based on the constants involved and the signedness of
5274   // the compare/divide.  This computes a half-open interval, keeping track of
5275   // whether either value in the interval overflows.  After analysis each
5276   // overflow variable is set to 0 if it's corresponding bound variable is valid
5277   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5278   int LoOverflow = 0, HiOverflow = 0;
5279   ConstantInt *LoBound = 0, *HiBound = 0;
5280   
5281   
5282   if (!DivIsSigned) {  // udiv
5283     // e.g. X/5 op 3  --> [15, 20)
5284     LoBound = Prod;
5285     HiOverflow = LoOverflow = ProdOV;
5286     if (!HiOverflow)
5287       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5288   } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5289     if (CmpRHSV == 0) {       // (X / pos) op 0
5290       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5291       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5292       HiBound = DivRHS;
5293     } else if (CmpRHSV.isPositive()) {   // (X / pos) op pos
5294       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5295       HiOverflow = LoOverflow = ProdOV;
5296       if (!HiOverflow)
5297         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5298     } else {                       // (X / pos) op neg
5299       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5300       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5301       LoOverflow = AddWithOverflow(LoBound, Prod,
5302                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5303       HiBound = AddOne(Prod);
5304       HiOverflow = ProdOV ? -1 : 0;
5305     }
5306   } else {                         // Divisor is < 0.
5307     if (CmpRHSV == 0) {       // (X / neg) op 0
5308       // e.g. X/-5 op 0  --> [-4, 5)
5309       LoBound = AddOne(DivRHS);
5310       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5311       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5312         HiOverflow = 1;            // [INTMIN+1, overflow)
5313         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5314       }
5315     } else if (CmpRHSV.isPositive()) {   // (X / neg) op pos
5316       // e.g. X/-5 op 3  --> [-19, -14)
5317       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5318       if (!LoOverflow)
5319         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5320       HiBound = AddOne(Prod);
5321     } else {                       // (X / neg) op neg
5322       // e.g. X/-5 op -3  --> [15, 20)
5323       LoBound = Prod;
5324       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5325       HiBound = Subtract(Prod, DivRHS);
5326     }
5327     
5328     // Dividing by a negative swaps the condition.  LT <-> GT
5329     Pred = ICmpInst::getSwappedPredicate(Pred);
5330   }
5331
5332   Value *X = DivI->getOperand(0);
5333   switch (Pred) {
5334   default: assert(0 && "Unhandled icmp opcode!");
5335   case ICmpInst::ICMP_EQ:
5336     if (LoOverflow && HiOverflow)
5337       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5338     else if (HiOverflow)
5339       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5340                           ICmpInst::ICMP_UGE, X, LoBound);
5341     else if (LoOverflow)
5342       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5343                           ICmpInst::ICMP_ULT, X, HiBound);
5344     else
5345       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5346   case ICmpInst::ICMP_NE:
5347     if (LoOverflow && HiOverflow)
5348       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5349     else if (HiOverflow)
5350       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5351                           ICmpInst::ICMP_ULT, X, LoBound);
5352     else if (LoOverflow)
5353       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5354                           ICmpInst::ICMP_UGE, X, HiBound);
5355     else
5356       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5357   case ICmpInst::ICMP_ULT:
5358   case ICmpInst::ICMP_SLT:
5359     if (LoOverflow == +1)   // Low bound is greater than input range.
5360       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5361     if (LoOverflow == -1)   // Low bound is less than input range.
5362       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5363     return new ICmpInst(Pred, X, LoBound);
5364   case ICmpInst::ICMP_UGT:
5365   case ICmpInst::ICMP_SGT:
5366     if (HiOverflow == +1)       // High bound greater than input range.
5367       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5368     else if (HiOverflow == -1)  // High bound less than input range.
5369       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5370     if (Pred == ICmpInst::ICMP_UGT)
5371       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5372     else
5373       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5374   }
5375 }
5376
5377
5378 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5379 ///
5380 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5381                                                           Instruction *LHSI,
5382                                                           ConstantInt *RHS) {
5383   const APInt &RHSV = RHS->getValue();
5384   
5385   switch (LHSI->getOpcode()) {
5386   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5387     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5388       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5389       // fold the xor.
5390       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5391           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5392         Value *CompareVal = LHSI->getOperand(0);
5393         
5394         // If the sign bit of the XorCST is not set, there is no change to
5395         // the operation, just stop using the Xor.
5396         if (!XorCST->getValue().isNegative()) {
5397           ICI.setOperand(0, CompareVal);
5398           AddToWorkList(LHSI);
5399           return &ICI;
5400         }
5401         
5402         // Was the old condition true if the operand is positive?
5403         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5404         
5405         // If so, the new one isn't.
5406         isTrueIfPositive ^= true;
5407         
5408         if (isTrueIfPositive)
5409           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5410         else
5411           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5412       }
5413     }
5414     break;
5415   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5416     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5417         LHSI->getOperand(0)->hasOneUse()) {
5418       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5419       
5420       // If the LHS is an AND of a truncating cast, we can widen the
5421       // and/compare to be the input width without changing the value
5422       // produced, eliminating a cast.
5423       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5424         // We can do this transformation if either the AND constant does not
5425         // have its sign bit set or if it is an equality comparison. 
5426         // Extending a relational comparison when we're checking the sign
5427         // bit would not work.
5428         if (Cast->hasOneUse() &&
5429             (ICI.isEquality() || AndCST->getValue().isPositive() && 
5430              RHSV.isPositive())) {
5431           uint32_t BitWidth = 
5432             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5433           APInt NewCST = AndCST->getValue();
5434           NewCST.zext(BitWidth);
5435           APInt NewCI = RHSV;
5436           NewCI.zext(BitWidth);
5437           Instruction *NewAnd = 
5438             BinaryOperator::createAnd(Cast->getOperand(0),
5439                                       ConstantInt::get(NewCST),LHSI->getName());
5440           InsertNewInstBefore(NewAnd, ICI);
5441           return new ICmpInst(ICI.getPredicate(), NewAnd,
5442                               ConstantInt::get(NewCI));
5443         }
5444       }
5445       
5446       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5447       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5448       // happens a LOT in code produced by the C front-end, for bitfield
5449       // access.
5450       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5451       if (Shift && !Shift->isShift())
5452         Shift = 0;
5453       
5454       ConstantInt *ShAmt;
5455       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5456       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5457       const Type *AndTy = AndCST->getType();          // Type of the and.
5458       
5459       // We can fold this as long as we can't shift unknown bits
5460       // into the mask.  This can only happen with signed shift
5461       // rights, as they sign-extend.
5462       if (ShAmt) {
5463         bool CanFold = Shift->isLogicalShift();
5464         if (!CanFold) {
5465           // To test for the bad case of the signed shr, see if any
5466           // of the bits shifted in could be tested after the mask.
5467           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5468           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5469           
5470           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5471           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5472                AndCST->getValue()) == 0)
5473             CanFold = true;
5474         }
5475         
5476         if (CanFold) {
5477           Constant *NewCst;
5478           if (Shift->getOpcode() == Instruction::Shl)
5479             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5480           else
5481             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5482           
5483           // Check to see if we are shifting out any of the bits being
5484           // compared.
5485           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5486             // If we shifted bits out, the fold is not going to work out.
5487             // As a special case, check to see if this means that the
5488             // result is always true or false now.
5489             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5490               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5491             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5492               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5493           } else {
5494             ICI.setOperand(1, NewCst);
5495             Constant *NewAndCST;
5496             if (Shift->getOpcode() == Instruction::Shl)
5497               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5498             else
5499               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5500             LHSI->setOperand(1, NewAndCST);
5501             LHSI->setOperand(0, Shift->getOperand(0));
5502             AddToWorkList(Shift); // Shift is dead.
5503             AddUsesToWorkList(ICI);
5504             return &ICI;
5505           }
5506         }
5507       }
5508       
5509       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5510       // preferable because it allows the C<<Y expression to be hoisted out
5511       // of a loop if Y is invariant and X is not.
5512       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5513           ICI.isEquality() && !Shift->isArithmeticShift() &&
5514           isa<Instruction>(Shift->getOperand(0))) {
5515         // Compute C << Y.
5516         Value *NS;
5517         if (Shift->getOpcode() == Instruction::LShr) {
5518           NS = BinaryOperator::createShl(AndCST, 
5519                                          Shift->getOperand(1), "tmp");
5520         } else {
5521           // Insert a logical shift.
5522           NS = BinaryOperator::createLShr(AndCST,
5523                                           Shift->getOperand(1), "tmp");
5524         }
5525         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5526         
5527         // Compute X & (C << Y).
5528         Instruction *NewAnd = 
5529           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5530         InsertNewInstBefore(NewAnd, ICI);
5531         
5532         ICI.setOperand(0, NewAnd);
5533         return &ICI;
5534       }
5535     }
5536     break;
5537     
5538   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5539     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5540     if (!ShAmt) break;
5541     
5542     uint32_t TypeBits = RHSV.getBitWidth();
5543     
5544     // Check that the shift amount is in range.  If not, don't perform
5545     // undefined shifts.  When the shift is visited it will be
5546     // simplified.
5547     if (ShAmt->uge(TypeBits))
5548       break;
5549     
5550     if (ICI.isEquality()) {
5551       // If we are comparing against bits always shifted out, the
5552       // comparison cannot succeed.
5553       Constant *Comp =
5554         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5555       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5556         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5557         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5558         return ReplaceInstUsesWith(ICI, Cst);
5559       }
5560       
5561       if (LHSI->hasOneUse()) {
5562         // Otherwise strength reduce the shift into an and.
5563         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5564         Constant *Mask =
5565           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5566         
5567         Instruction *AndI =
5568           BinaryOperator::createAnd(LHSI->getOperand(0),
5569                                     Mask, LHSI->getName()+".mask");
5570         Value *And = InsertNewInstBefore(AndI, ICI);
5571         return new ICmpInst(ICI.getPredicate(), And,
5572                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5573       }
5574     }
5575     
5576     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5577     bool TrueIfSigned = false;
5578     if (LHSI->hasOneUse() &&
5579         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5580       // (X << 31) <s 0  --> (X&1) != 0
5581       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5582                                            (TypeBits-ShAmt->getZExtValue()-1));
5583       Instruction *AndI =
5584         BinaryOperator::createAnd(LHSI->getOperand(0),
5585                                   Mask, LHSI->getName()+".mask");
5586       Value *And = InsertNewInstBefore(AndI, ICI);
5587       
5588       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5589                           And, Constant::getNullValue(And->getType()));
5590     }
5591     break;
5592   }
5593     
5594   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5595   case Instruction::AShr: {
5596     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5597     if (!ShAmt) break;
5598
5599     if (ICI.isEquality()) {
5600       // Check that the shift amount is in range.  If not, don't perform
5601       // undefined shifts.  When the shift is visited it will be
5602       // simplified.
5603       uint32_t TypeBits = RHSV.getBitWidth();
5604       if (ShAmt->uge(TypeBits))
5605         break;
5606       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5607       
5608       // If we are comparing against bits always shifted out, the
5609       // comparison cannot succeed.
5610       APInt Comp = RHSV << ShAmtVal;
5611       if (LHSI->getOpcode() == Instruction::LShr)
5612         Comp = Comp.lshr(ShAmtVal);
5613       else
5614         Comp = Comp.ashr(ShAmtVal);
5615       
5616       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5617         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5618         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5619         return ReplaceInstUsesWith(ICI, Cst);
5620       }
5621       
5622       if (LHSI->hasOneUse() || RHSV == 0) {
5623         // Otherwise strength reduce the shift into an and.
5624         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5625         Constant *Mask = ConstantInt::get(Val);
5626         
5627         Instruction *AndI =
5628           BinaryOperator::createAnd(LHSI->getOperand(0),
5629                                     Mask, LHSI->getName()+".mask");
5630         Value *And = InsertNewInstBefore(AndI, ICI);
5631         return new ICmpInst(ICI.getPredicate(), And,
5632                             ConstantExpr::getShl(RHS, ShAmt));
5633       }
5634     }
5635     break;
5636   }
5637     
5638   case Instruction::SDiv:
5639   case Instruction::UDiv:
5640     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5641     // Fold this div into the comparison, producing a range check. 
5642     // Determine, based on the divide type, what the range is being 
5643     // checked.  If there is an overflow on the low or high side, remember 
5644     // it, otherwise compute the range [low, hi) bounding the new value.
5645     // See: InsertRangeTest above for the kinds of replacements possible.
5646     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5647       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5648                                           DivRHS))
5649         return R;
5650     break;
5651   }
5652   
5653   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5654   if (ICI.isEquality()) {
5655     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5656     
5657     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5658     // the second operand is a constant, simplify a bit.
5659     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5660       switch (BO->getOpcode()) {
5661       case Instruction::SRem:
5662         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5663         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5664           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5665           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5666             Instruction *NewRem =
5667               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5668                                          BO->getName());
5669             InsertNewInstBefore(NewRem, ICI);
5670             return new ICmpInst(ICI.getPredicate(), NewRem, 
5671                                 Constant::getNullValue(BO->getType()));
5672           }
5673         }
5674         break;
5675       case Instruction::Add:
5676         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5677         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5678           if (BO->hasOneUse())
5679             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5680                                 Subtract(RHS, BOp1C));
5681         } else if (RHSV == 0) {
5682           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5683           // efficiently invertible, or if the add has just this one use.
5684           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5685           
5686           if (Value *NegVal = dyn_castNegVal(BOp1))
5687             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5688           else if (Value *NegVal = dyn_castNegVal(BOp0))
5689             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5690           else if (BO->hasOneUse()) {
5691             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5692             InsertNewInstBefore(Neg, ICI);
5693             Neg->takeName(BO);
5694             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5695           }
5696         }
5697         break;
5698       case Instruction::Xor:
5699         // For the xor case, we can xor two constants together, eliminating
5700         // the explicit xor.
5701         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5702           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5703                               ConstantExpr::getXor(RHS, BOC));
5704         
5705         // FALLTHROUGH
5706       case Instruction::Sub:
5707         // Replace (([sub|xor] A, B) != 0) with (A != B)
5708         if (RHSV == 0)
5709           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5710                               BO->getOperand(1));
5711         break;
5712         
5713       case Instruction::Or:
5714         // If bits are being or'd in that are not present in the constant we
5715         // are comparing against, then the comparison could never succeed!
5716         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5717           Constant *NotCI = ConstantExpr::getNot(RHS);
5718           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5719             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5720                                                              isICMP_NE));
5721         }
5722         break;
5723         
5724       case Instruction::And:
5725         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5726           // If bits are being compared against that are and'd out, then the
5727           // comparison can never succeed!
5728           if ((RHSV & ~BOC->getValue()) != 0)
5729             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5730                                                              isICMP_NE));
5731           
5732           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5733           if (RHS == BOC && RHSV.isPowerOf2())
5734             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5735                                 ICmpInst::ICMP_NE, LHSI,
5736                                 Constant::getNullValue(RHS->getType()));
5737           
5738           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5739           if (isSignBit(BOC)) {
5740             Value *X = BO->getOperand(0);
5741             Constant *Zero = Constant::getNullValue(X->getType());
5742             ICmpInst::Predicate pred = isICMP_NE ? 
5743               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5744             return new ICmpInst(pred, X, Zero);
5745           }
5746           
5747           // ((X & ~7) == 0) --> X < 8
5748           if (RHSV == 0 && isHighOnes(BOC)) {
5749             Value *X = BO->getOperand(0);
5750             Constant *NegX = ConstantExpr::getNeg(BOC);
5751             ICmpInst::Predicate pred = isICMP_NE ? 
5752               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5753             return new ICmpInst(pred, X, NegX);
5754           }
5755         }
5756       default: break;
5757       }
5758     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5759       // Handle icmp {eq|ne} <intrinsic>, intcst.
5760       if (II->getIntrinsicID() == Intrinsic::bswap) {
5761         AddToWorkList(II);
5762         ICI.setOperand(0, II->getOperand(1));
5763         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5764         return &ICI;
5765       }
5766     }
5767   } else {  // Not a ICMP_EQ/ICMP_NE
5768             // If the LHS is a cast from an integral value of the same size, 
5769             // then since we know the RHS is a constant, try to simlify.
5770     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5771       Value *CastOp = Cast->getOperand(0);
5772       const Type *SrcTy = CastOp->getType();
5773       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5774       if (SrcTy->isInteger() && 
5775           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5776         // If this is an unsigned comparison, try to make the comparison use
5777         // smaller constant values.
5778         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5779           // X u< 128 => X s> -1
5780           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5781                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5782         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5783                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5784           // X u> 127 => X s< 0
5785           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5786                               Constant::getNullValue(SrcTy));
5787         }
5788       }
5789     }
5790   }
5791   return 0;
5792 }
5793
5794 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5795 /// We only handle extending casts so far.
5796 ///
5797 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5798   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5799   Value *LHSCIOp        = LHSCI->getOperand(0);
5800   const Type *SrcTy     = LHSCIOp->getType();
5801   const Type *DestTy    = LHSCI->getType();
5802   Value *RHSCIOp;
5803
5804   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5805   // integer type is the same size as the pointer type.
5806   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5807       getTargetData().getPointerSizeInBits() == 
5808          cast<IntegerType>(DestTy)->getBitWidth()) {
5809     Value *RHSOp = 0;
5810     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5811       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5812     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5813       RHSOp = RHSC->getOperand(0);
5814       // If the pointer types don't match, insert a bitcast.
5815       if (LHSCIOp->getType() != RHSOp->getType())
5816         RHSOp = InsertCastBefore(Instruction::BitCast, RHSOp,
5817                                  LHSCIOp->getType(), ICI);
5818     }
5819
5820     if (RHSOp)
5821       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5822   }
5823   
5824   // The code below only handles extension cast instructions, so far.
5825   // Enforce this.
5826   if (LHSCI->getOpcode() != Instruction::ZExt &&
5827       LHSCI->getOpcode() != Instruction::SExt)
5828     return 0;
5829
5830   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5831   bool isSignedCmp = ICI.isSignedPredicate();
5832
5833   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5834     // Not an extension from the same type?
5835     RHSCIOp = CI->getOperand(0);
5836     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5837       return 0;
5838     
5839     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5840     // and the other is a zext), then we can't handle this.
5841     if (CI->getOpcode() != LHSCI->getOpcode())
5842       return 0;
5843
5844     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5845     // then we can't handle this.
5846     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5847       return 0;
5848     
5849     // Okay, just insert a compare of the reduced operands now!
5850     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5851   }
5852
5853   // If we aren't dealing with a constant on the RHS, exit early
5854   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5855   if (!CI)
5856     return 0;
5857
5858   // Compute the constant that would happen if we truncated to SrcTy then
5859   // reextended to DestTy.
5860   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5861   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5862
5863   // If the re-extended constant didn't change...
5864   if (Res2 == CI) {
5865     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5866     // For example, we might have:
5867     //    %A = sext short %X to uint
5868     //    %B = icmp ugt uint %A, 1330
5869     // It is incorrect to transform this into 
5870     //    %B = icmp ugt short %X, 1330 
5871     // because %A may have negative value. 
5872     //
5873     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5874     // OR operation is EQ/NE.
5875     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5876       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5877     else
5878       return 0;
5879   }
5880
5881   // The re-extended constant changed so the constant cannot be represented 
5882   // in the shorter type. Consequently, we cannot emit a simple comparison.
5883
5884   // First, handle some easy cases. We know the result cannot be equal at this
5885   // point so handle the ICI.isEquality() cases
5886   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5887     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5888   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5889     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5890
5891   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5892   // should have been folded away previously and not enter in here.
5893   Value *Result;
5894   if (isSignedCmp) {
5895     // We're performing a signed comparison.
5896     if (cast<ConstantInt>(CI)->getValue().isNegative())
5897       Result = ConstantInt::getFalse();          // X < (small) --> false
5898     else
5899       Result = ConstantInt::getTrue();           // X < (large) --> true
5900   } else {
5901     // We're performing an unsigned comparison.
5902     if (isSignedExt) {
5903       // We're performing an unsigned comp with a sign extended value.
5904       // This is true if the input is >= 0. [aka >s -1]
5905       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5906       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5907                                    NegOne, ICI.getName()), ICI);
5908     } else {
5909       // Unsigned extend & unsigned compare -> always true.
5910       Result = ConstantInt::getTrue();
5911     }
5912   }
5913
5914   // Finally, return the value computed.
5915   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5916       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5917     return ReplaceInstUsesWith(ICI, Result);
5918   } else {
5919     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5920             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5921            "ICmp should be folded!");
5922     if (Constant *CI = dyn_cast<Constant>(Result))
5923       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5924     else
5925       return BinaryOperator::createNot(Result);
5926   }
5927 }
5928
5929 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5930   return commonShiftTransforms(I);
5931 }
5932
5933 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5934   return commonShiftTransforms(I);
5935 }
5936
5937 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5938   if (Instruction *R = commonShiftTransforms(I))
5939     return R;
5940   
5941   Value *Op0 = I.getOperand(0);
5942   
5943   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5944   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5945     if (CSI->isAllOnesValue())
5946       return ReplaceInstUsesWith(I, CSI);
5947   
5948   // See if we can turn a signed shr into an unsigned shr.
5949   if (MaskedValueIsZero(Op0, 
5950                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5951     return BinaryOperator::createLShr(Op0, I.getOperand(1));
5952   
5953   return 0;
5954 }
5955
5956 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5957   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5958   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5959
5960   // shl X, 0 == X and shr X, 0 == X
5961   // shl 0, X == 0 and shr 0, X == 0
5962   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5963       Op0 == Constant::getNullValue(Op0->getType()))
5964     return ReplaceInstUsesWith(I, Op0);
5965   
5966   if (isa<UndefValue>(Op0)) {            
5967     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5968       return ReplaceInstUsesWith(I, Op0);
5969     else                                    // undef << X -> 0, undef >>u X -> 0
5970       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5971   }
5972   if (isa<UndefValue>(Op1)) {
5973     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5974       return ReplaceInstUsesWith(I, Op0);          
5975     else                                     // X << undef, X >>u undef -> 0
5976       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5977   }
5978
5979   // Try to fold constant and into select arguments.
5980   if (isa<Constant>(Op0))
5981     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5982       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5983         return R;
5984
5985   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5986     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5987       return Res;
5988   return 0;
5989 }
5990
5991 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5992                                                BinaryOperator &I) {
5993   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5994
5995   // See if we can simplify any instructions used by the instruction whose sole 
5996   // purpose is to compute bits we don't care about.
5997   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5998   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5999   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6000                            KnownZero, KnownOne))
6001     return &I;
6002   
6003   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6004   // of a signed value.
6005   //
6006   if (Op1->uge(TypeBits)) {
6007     if (I.getOpcode() != Instruction::AShr)
6008       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6009     else {
6010       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6011       return &I;
6012     }
6013   }
6014   
6015   // ((X*C1) << C2) == (X * (C1 << C2))
6016   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6017     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6018       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6019         return BinaryOperator::createMul(BO->getOperand(0),
6020                                          ConstantExpr::getShl(BOOp, Op1));
6021   
6022   // Try to fold constant and into select arguments.
6023   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6024     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6025       return R;
6026   if (isa<PHINode>(Op0))
6027     if (Instruction *NV = FoldOpIntoPhi(I))
6028       return NV;
6029   
6030   if (Op0->hasOneUse()) {
6031     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6032       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6033       Value *V1, *V2;
6034       ConstantInt *CC;
6035       switch (Op0BO->getOpcode()) {
6036         default: break;
6037         case Instruction::Add:
6038         case Instruction::And:
6039         case Instruction::Or:
6040         case Instruction::Xor: {
6041           // These operators commute.
6042           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6043           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6044               match(Op0BO->getOperand(1),
6045                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6046             Instruction *YS = BinaryOperator::createShl(
6047                                             Op0BO->getOperand(0), Op1,
6048                                             Op0BO->getName());
6049             InsertNewInstBefore(YS, I); // (Y << C)
6050             Instruction *X = 
6051               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6052                                      Op0BO->getOperand(1)->getName());
6053             InsertNewInstBefore(X, I);  // (X + (Y << C))
6054             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6055             return BinaryOperator::createAnd(X, ConstantInt::get(
6056                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6057           }
6058           
6059           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6060           Value *Op0BOOp1 = Op0BO->getOperand(1);
6061           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6062               match(Op0BOOp1, 
6063                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6064               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6065               V2 == Op1) {
6066             Instruction *YS = BinaryOperator::createShl(
6067                                                      Op0BO->getOperand(0), Op1,
6068                                                      Op0BO->getName());
6069             InsertNewInstBefore(YS, I); // (Y << C)
6070             Instruction *XM =
6071               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6072                                         V1->getName()+".mask");
6073             InsertNewInstBefore(XM, I); // X & (CC << C)
6074             
6075             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6076           }
6077         }
6078           
6079         // FALL THROUGH.
6080         case Instruction::Sub: {
6081           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6082           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6083               match(Op0BO->getOperand(0),
6084                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6085             Instruction *YS = BinaryOperator::createShl(
6086                                                      Op0BO->getOperand(1), Op1,
6087                                                      Op0BO->getName());
6088             InsertNewInstBefore(YS, I); // (Y << C)
6089             Instruction *X =
6090               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6091                                      Op0BO->getOperand(0)->getName());
6092             InsertNewInstBefore(X, I);  // (X + (Y << C))
6093             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6094             return BinaryOperator::createAnd(X, ConstantInt::get(
6095                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6096           }
6097           
6098           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6099           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6100               match(Op0BO->getOperand(0),
6101                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6102                           m_ConstantInt(CC))) && V2 == Op1 &&
6103               cast<BinaryOperator>(Op0BO->getOperand(0))
6104                   ->getOperand(0)->hasOneUse()) {
6105             Instruction *YS = BinaryOperator::createShl(
6106                                                      Op0BO->getOperand(1), Op1,
6107                                                      Op0BO->getName());
6108             InsertNewInstBefore(YS, I); // (Y << C)
6109             Instruction *XM =
6110               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6111                                         V1->getName()+".mask");
6112             InsertNewInstBefore(XM, I); // X & (CC << C)
6113             
6114             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6115           }
6116           
6117           break;
6118         }
6119       }
6120       
6121       
6122       // If the operand is an bitwise operator with a constant RHS, and the
6123       // shift is the only use, we can pull it out of the shift.
6124       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6125         bool isValid = true;     // Valid only for And, Or, Xor
6126         bool highBitSet = false; // Transform if high bit of constant set?
6127         
6128         switch (Op0BO->getOpcode()) {
6129           default: isValid = false; break;   // Do not perform transform!
6130           case Instruction::Add:
6131             isValid = isLeftShift;
6132             break;
6133           case Instruction::Or:
6134           case Instruction::Xor:
6135             highBitSet = false;
6136             break;
6137           case Instruction::And:
6138             highBitSet = true;
6139             break;
6140         }
6141         
6142         // If this is a signed shift right, and the high bit is modified
6143         // by the logical operation, do not perform the transformation.
6144         // The highBitSet boolean indicates the value of the high bit of
6145         // the constant which would cause it to be modified for this
6146         // operation.
6147         //
6148         if (isValid && I.getOpcode() == Instruction::AShr)
6149           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6150         
6151         if (isValid) {
6152           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6153           
6154           Instruction *NewShift =
6155             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6156           InsertNewInstBefore(NewShift, I);
6157           NewShift->takeName(Op0BO);
6158           
6159           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6160                                         NewRHS);
6161         }
6162       }
6163     }
6164   }
6165   
6166   // Find out if this is a shift of a shift by a constant.
6167   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6168   if (ShiftOp && !ShiftOp->isShift())
6169     ShiftOp = 0;
6170   
6171   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6172     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6173     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6174     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6175     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6176     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6177     Value *X = ShiftOp->getOperand(0);
6178     
6179     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6180     if (AmtSum > TypeBits)
6181       AmtSum = TypeBits;
6182     
6183     const IntegerType *Ty = cast<IntegerType>(I.getType());
6184     
6185     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6186     if (I.getOpcode() == ShiftOp->getOpcode()) {
6187       return BinaryOperator::create(I.getOpcode(), X,
6188                                     ConstantInt::get(Ty, AmtSum));
6189     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6190                I.getOpcode() == Instruction::AShr) {
6191       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6192       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6193     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6194                I.getOpcode() == Instruction::LShr) {
6195       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6196       Instruction *Shift =
6197         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6198       InsertNewInstBefore(Shift, I);
6199
6200       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6201       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6202     }
6203     
6204     // Okay, if we get here, one shift must be left, and the other shift must be
6205     // right.  See if the amounts are equal.
6206     if (ShiftAmt1 == ShiftAmt2) {
6207       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6208       if (I.getOpcode() == Instruction::Shl) {
6209         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6210         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6211       }
6212       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6213       if (I.getOpcode() == Instruction::LShr) {
6214         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6215         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6216       }
6217       // We can simplify ((X << C) >>s C) into a trunc + sext.
6218       // NOTE: we could do this for any C, but that would make 'unusual' integer
6219       // types.  For now, just stick to ones well-supported by the code
6220       // generators.
6221       const Type *SExtType = 0;
6222       switch (Ty->getBitWidth() - ShiftAmt1) {
6223       case 1  :
6224       case 8  :
6225       case 16 :
6226       case 32 :
6227       case 64 :
6228       case 128:
6229         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6230         break;
6231       default: break;
6232       }
6233       if (SExtType) {
6234         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6235         InsertNewInstBefore(NewTrunc, I);
6236         return new SExtInst(NewTrunc, Ty);
6237       }
6238       // Otherwise, we can't handle it yet.
6239     } else if (ShiftAmt1 < ShiftAmt2) {
6240       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6241       
6242       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6243       if (I.getOpcode() == Instruction::Shl) {
6244         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6245                ShiftOp->getOpcode() == Instruction::AShr);
6246         Instruction *Shift =
6247           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6248         InsertNewInstBefore(Shift, I);
6249         
6250         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6251         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6252       }
6253       
6254       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6255       if (I.getOpcode() == Instruction::LShr) {
6256         assert(ShiftOp->getOpcode() == Instruction::Shl);
6257         Instruction *Shift =
6258           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6259         InsertNewInstBefore(Shift, I);
6260         
6261         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6262         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6263       }
6264       
6265       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6266     } else {
6267       assert(ShiftAmt2 < ShiftAmt1);
6268       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6269
6270       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6271       if (I.getOpcode() == Instruction::Shl) {
6272         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6273                ShiftOp->getOpcode() == Instruction::AShr);
6274         Instruction *Shift =
6275           BinaryOperator::create(ShiftOp->getOpcode(), X,
6276                                  ConstantInt::get(Ty, ShiftDiff));
6277         InsertNewInstBefore(Shift, I);
6278         
6279         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6280         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6281       }
6282       
6283       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6284       if (I.getOpcode() == Instruction::LShr) {
6285         assert(ShiftOp->getOpcode() == Instruction::Shl);
6286         Instruction *Shift =
6287           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6288         InsertNewInstBefore(Shift, I);
6289         
6290         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6291         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6292       }
6293       
6294       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6295     }
6296   }
6297   return 0;
6298 }
6299
6300
6301 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6302 /// expression.  If so, decompose it, returning some value X, such that Val is
6303 /// X*Scale+Offset.
6304 ///
6305 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6306                                         int &Offset) {
6307   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6308   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6309     Offset = CI->getZExtValue();
6310     Scale  = 0;
6311     return ConstantInt::get(Type::Int32Ty, 0);
6312   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6313     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6314       if (I->getOpcode() == Instruction::Shl) {
6315         // This is a value scaled by '1 << the shift amt'.
6316         Scale = 1U << RHS->getZExtValue();
6317         Offset = 0;
6318         return I->getOperand(0);
6319       } else if (I->getOpcode() == Instruction::Mul) {
6320         // This value is scaled by 'RHS'.
6321         Scale = RHS->getZExtValue();
6322         Offset = 0;
6323         return I->getOperand(0);
6324       } else if (I->getOpcode() == Instruction::Add) {
6325         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6326         // where C1 is divisible by C2.
6327         unsigned SubScale;
6328         Value *SubVal = 
6329           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6330         Offset += RHS->getZExtValue();
6331         Scale = SubScale;
6332         return SubVal;
6333       }
6334     }
6335   }
6336
6337   // Otherwise, we can't look past this.
6338   Scale = 1;
6339   Offset = 0;
6340   return Val;
6341 }
6342
6343
6344 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6345 /// try to eliminate the cast by moving the type information into the alloc.
6346 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6347                                                    AllocationInst &AI) {
6348   const PointerType *PTy = cast<PointerType>(CI.getType());
6349   
6350   // Remove any uses of AI that are dead.
6351   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6352   
6353   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6354     Instruction *User = cast<Instruction>(*UI++);
6355     if (isInstructionTriviallyDead(User)) {
6356       while (UI != E && *UI == User)
6357         ++UI; // If this instruction uses AI more than once, don't break UI.
6358       
6359       ++NumDeadInst;
6360       DOUT << "IC: DCE: " << *User;
6361       EraseInstFromFunction(*User);
6362     }
6363   }
6364   
6365   // Get the type really allocated and the type casted to.
6366   const Type *AllocElTy = AI.getAllocatedType();
6367   const Type *CastElTy = PTy->getElementType();
6368   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6369
6370   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6371   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6372   if (CastElTyAlign < AllocElTyAlign) return 0;
6373
6374   // If the allocation has multiple uses, only promote it if we are strictly
6375   // increasing the alignment of the resultant allocation.  If we keep it the
6376   // same, we open the door to infinite loops of various kinds.
6377   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6378
6379   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6380   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6381   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6382
6383   // See if we can satisfy the modulus by pulling a scale out of the array
6384   // size argument.
6385   unsigned ArraySizeScale;
6386   int ArrayOffset;
6387   Value *NumElements = // See if the array size is a decomposable linear expr.
6388     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6389  
6390   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6391   // do the xform.
6392   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6393       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6394
6395   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6396   Value *Amt = 0;
6397   if (Scale == 1) {
6398     Amt = NumElements;
6399   } else {
6400     // If the allocation size is constant, form a constant mul expression
6401     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6402     if (isa<ConstantInt>(NumElements))
6403       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6404     // otherwise multiply the amount and the number of elements
6405     else if (Scale != 1) {
6406       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6407       Amt = InsertNewInstBefore(Tmp, AI);
6408     }
6409   }
6410   
6411   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6412     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6413     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6414     Amt = InsertNewInstBefore(Tmp, AI);
6415   }
6416   
6417   AllocationInst *New;
6418   if (isa<MallocInst>(AI))
6419     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6420   else
6421     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6422   InsertNewInstBefore(New, AI);
6423   New->takeName(&AI);
6424   
6425   // If the allocation has multiple uses, insert a cast and change all things
6426   // that used it to use the new cast.  This will also hack on CI, but it will
6427   // die soon.
6428   if (!AI.hasOneUse()) {
6429     AddUsesToWorkList(AI);
6430     // New is the allocation instruction, pointer typed. AI is the original
6431     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6432     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6433     InsertNewInstBefore(NewCast, AI);
6434     AI.replaceAllUsesWith(NewCast);
6435   }
6436   return ReplaceInstUsesWith(CI, New);
6437 }
6438
6439 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6440 /// and return it as type Ty without inserting any new casts and without
6441 /// changing the computed value.  This is used by code that tries to decide
6442 /// whether promoting or shrinking integer operations to wider or smaller types
6443 /// will allow us to eliminate a truncate or extend.
6444 ///
6445 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6446 /// extension operation if Ty is larger.
6447 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6448                                        unsigned CastOpc, int &NumCastsRemoved) {
6449   // We can always evaluate constants in another type.
6450   if (isa<ConstantInt>(V))
6451     return true;
6452   
6453   Instruction *I = dyn_cast<Instruction>(V);
6454   if (!I) return false;
6455   
6456   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6457   
6458   // If this is an extension or truncate, we can often eliminate it.
6459   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6460     // If this is a cast from the destination type, we can trivially eliminate
6461     // it, and this will remove a cast overall.
6462     if (I->getOperand(0)->getType() == Ty) {
6463       // If the first operand is itself a cast, and is eliminable, do not count
6464       // this as an eliminable cast.  We would prefer to eliminate those two
6465       // casts first.
6466       if (!isa<CastInst>(I->getOperand(0)))
6467         ++NumCastsRemoved;
6468       return true;
6469     }
6470   }
6471
6472   // We can't extend or shrink something that has multiple uses: doing so would
6473   // require duplicating the instruction in general, which isn't profitable.
6474   if (!I->hasOneUse()) return false;
6475
6476   switch (I->getOpcode()) {
6477   case Instruction::Add:
6478   case Instruction::Sub:
6479   case Instruction::And:
6480   case Instruction::Or:
6481   case Instruction::Xor:
6482     // These operators can all arbitrarily be extended or truncated.
6483     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6484                                       NumCastsRemoved) &&
6485            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6486                                       NumCastsRemoved);
6487
6488   case Instruction::Shl:
6489     // If we are truncating the result of this SHL, and if it's a shift of a
6490     // constant amount, we can always perform a SHL in a smaller type.
6491     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6492       uint32_t BitWidth = Ty->getBitWidth();
6493       if (BitWidth < OrigTy->getBitWidth() && 
6494           CI->getLimitedValue(BitWidth) < BitWidth)
6495         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6496                                           NumCastsRemoved);
6497     }
6498     break;
6499   case Instruction::LShr:
6500     // If this is a truncate of a logical shr, we can truncate it to a smaller
6501     // lshr iff we know that the bits we would otherwise be shifting in are
6502     // already zeros.
6503     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6504       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6505       uint32_t BitWidth = Ty->getBitWidth();
6506       if (BitWidth < OrigBitWidth &&
6507           MaskedValueIsZero(I->getOperand(0),
6508             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6509           CI->getLimitedValue(BitWidth) < BitWidth) {
6510         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6511                                           NumCastsRemoved);
6512       }
6513     }
6514     break;
6515   case Instruction::ZExt:
6516   case Instruction::SExt:
6517   case Instruction::Trunc:
6518     // If this is the same kind of case as our original (e.g. zext+zext), we
6519     // can safely replace it.  Note that replacing it does not reduce the number
6520     // of casts in the input.
6521     if (I->getOpcode() == CastOpc)
6522       return true;
6523     
6524     break;
6525   default:
6526     // TODO: Can handle more cases here.
6527     break;
6528   }
6529   
6530   return false;
6531 }
6532
6533 /// EvaluateInDifferentType - Given an expression that 
6534 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6535 /// evaluate the expression.
6536 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6537                                              bool isSigned) {
6538   if (Constant *C = dyn_cast<Constant>(V))
6539     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6540
6541   // Otherwise, it must be an instruction.
6542   Instruction *I = cast<Instruction>(V);
6543   Instruction *Res = 0;
6544   switch (I->getOpcode()) {
6545   case Instruction::Add:
6546   case Instruction::Sub:
6547   case Instruction::And:
6548   case Instruction::Or:
6549   case Instruction::Xor:
6550   case Instruction::AShr:
6551   case Instruction::LShr:
6552   case Instruction::Shl: {
6553     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6554     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6555     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6556                                  LHS, RHS, I->getName());
6557     break;
6558   }    
6559   case Instruction::Trunc:
6560   case Instruction::ZExt:
6561   case Instruction::SExt:
6562     // If the source type of the cast is the type we're trying for then we can
6563     // just return the source.  There's no need to insert it because it is not
6564     // new.
6565     if (I->getOperand(0)->getType() == Ty)
6566       return I->getOperand(0);
6567     
6568     // Otherwise, must be the same type of case, so just reinsert a new one.
6569     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6570                            Ty, I->getName());
6571     break;
6572   default: 
6573     // TODO: Can handle more cases here.
6574     assert(0 && "Unreachable!");
6575     break;
6576   }
6577   
6578   return InsertNewInstBefore(Res, *I);
6579 }
6580
6581 /// @brief Implement the transforms common to all CastInst visitors.
6582 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6583   Value *Src = CI.getOperand(0);
6584
6585   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6586   // eliminate it now.
6587   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6588     if (Instruction::CastOps opc = 
6589         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6590       // The first cast (CSrc) is eliminable so we need to fix up or replace
6591       // the second cast (CI). CSrc will then have a good chance of being dead.
6592       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6593     }
6594   }
6595
6596   // If we are casting a select then fold the cast into the select
6597   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6598     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6599       return NV;
6600
6601   // If we are casting a PHI then fold the cast into the PHI
6602   if (isa<PHINode>(Src))
6603     if (Instruction *NV = FoldOpIntoPhi(CI))
6604       return NV;
6605   
6606   return 0;
6607 }
6608
6609 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6610 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6611   Value *Src = CI.getOperand(0);
6612   
6613   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6614     // If casting the result of a getelementptr instruction with no offset, turn
6615     // this into a cast of the original pointer!
6616     if (GEP->hasAllZeroIndices()) {
6617       // Changing the cast operand is usually not a good idea but it is safe
6618       // here because the pointer operand is being replaced with another 
6619       // pointer operand so the opcode doesn't need to change.
6620       AddToWorkList(GEP);
6621       CI.setOperand(0, GEP->getOperand(0));
6622       return &CI;
6623     }
6624     
6625     // If the GEP has a single use, and the base pointer is a bitcast, and the
6626     // GEP computes a constant offset, see if we can convert these three
6627     // instructions into fewer.  This typically happens with unions and other
6628     // non-type-safe code.
6629     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6630       if (GEP->hasAllConstantIndices()) {
6631         // We are guaranteed to get a constant from EmitGEPOffset.
6632         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6633         int64_t Offset = OffsetV->getSExtValue();
6634         
6635         // Get the base pointer input of the bitcast, and the type it points to.
6636         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6637         const Type *GEPIdxTy =
6638           cast<PointerType>(OrigBase->getType())->getElementType();
6639         if (GEPIdxTy->isSized()) {
6640           SmallVector<Value*, 8> NewIndices;
6641           
6642           // Start with the index over the outer type.  Note that the type size
6643           // might be zero (even if the offset isn't zero) if the indexed type
6644           // is something like [0 x {int, int}]
6645           const Type *IntPtrTy = TD->getIntPtrType();
6646           int64_t FirstIdx = 0;
6647           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6648             FirstIdx = Offset/TySize;
6649             Offset %= TySize;
6650           
6651             // Handle silly modulus not returning values values [0..TySize).
6652             if (Offset < 0) {
6653               --FirstIdx;
6654               Offset += TySize;
6655               assert(Offset >= 0);
6656             }
6657             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6658           }
6659           
6660           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6661
6662           // Index into the types.  If we fail, set OrigBase to null.
6663           while (Offset) {
6664             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6665               const StructLayout *SL = TD->getStructLayout(STy);
6666               if (Offset < (int64_t)SL->getSizeInBytes()) {
6667                 unsigned Elt = SL->getElementContainingOffset(Offset);
6668                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6669               
6670                 Offset -= SL->getElementOffset(Elt);
6671                 GEPIdxTy = STy->getElementType(Elt);
6672               } else {
6673                 // Otherwise, we can't index into this, bail out.
6674                 Offset = 0;
6675                 OrigBase = 0;
6676               }
6677             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6678               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6679               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6680                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6681                 Offset %= EltSize;
6682               } else {
6683                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6684               }
6685               GEPIdxTy = STy->getElementType();
6686             } else {
6687               // Otherwise, we can't index into this, bail out.
6688               Offset = 0;
6689               OrigBase = 0;
6690             }
6691           }
6692           if (OrigBase) {
6693             // If we were able to index down into an element, create the GEP
6694             // and bitcast the result.  This eliminates one bitcast, potentially
6695             // two.
6696             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6697                                                       NewIndices.begin(),
6698                                                       NewIndices.end(), "");
6699             InsertNewInstBefore(NGEP, CI);
6700             NGEP->takeName(GEP);
6701             
6702             if (isa<BitCastInst>(CI))
6703               return new BitCastInst(NGEP, CI.getType());
6704             assert(isa<PtrToIntInst>(CI));
6705             return new PtrToIntInst(NGEP, CI.getType());
6706           }
6707         }
6708       }      
6709     }
6710   }
6711     
6712   return commonCastTransforms(CI);
6713 }
6714
6715
6716
6717 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6718 /// integer types. This function implements the common transforms for all those
6719 /// cases.
6720 /// @brief Implement the transforms common to CastInst with integer operands
6721 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6722   if (Instruction *Result = commonCastTransforms(CI))
6723     return Result;
6724
6725   Value *Src = CI.getOperand(0);
6726   const Type *SrcTy = Src->getType();
6727   const Type *DestTy = CI.getType();
6728   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6729   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6730
6731   // See if we can simplify any instructions used by the LHS whose sole 
6732   // purpose is to compute bits we don't care about.
6733   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6734   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6735                            KnownZero, KnownOne))
6736     return &CI;
6737
6738   // If the source isn't an instruction or has more than one use then we
6739   // can't do anything more. 
6740   Instruction *SrcI = dyn_cast<Instruction>(Src);
6741   if (!SrcI || !Src->hasOneUse())
6742     return 0;
6743
6744   // Attempt to propagate the cast into the instruction for int->int casts.
6745   int NumCastsRemoved = 0;
6746   if (!isa<BitCastInst>(CI) &&
6747       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6748                                  CI.getOpcode(), NumCastsRemoved)) {
6749     // If this cast is a truncate, evaluting in a different type always
6750     // eliminates the cast, so it is always a win.  If this is a zero-extension,
6751     // we need to do an AND to maintain the clear top-part of the computation,
6752     // so we require that the input have eliminated at least one cast.  If this
6753     // is a sign extension, we insert two new casts (to do the extension) so we
6754     // require that two casts have been eliminated.
6755     bool DoXForm;
6756     switch (CI.getOpcode()) {
6757     default:
6758       // All the others use floating point so we shouldn't actually 
6759       // get here because of the check above.
6760       assert(0 && "Unknown cast type");
6761     case Instruction::Trunc:
6762       DoXForm = true;
6763       break;
6764     case Instruction::ZExt:
6765       DoXForm = NumCastsRemoved >= 1;
6766       break;
6767     case Instruction::SExt:
6768       DoXForm = NumCastsRemoved >= 2;
6769       break;
6770     }
6771     
6772     if (DoXForm) {
6773       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6774                                            CI.getOpcode() == Instruction::SExt);
6775       assert(Res->getType() == DestTy);
6776       switch (CI.getOpcode()) {
6777       default: assert(0 && "Unknown cast type!");
6778       case Instruction::Trunc:
6779       case Instruction::BitCast:
6780         // Just replace this cast with the result.
6781         return ReplaceInstUsesWith(CI, Res);
6782       case Instruction::ZExt: {
6783         // We need to emit an AND to clear the high bits.
6784         assert(SrcBitSize < DestBitSize && "Not a zext?");
6785         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6786                                                             SrcBitSize));
6787         return BinaryOperator::createAnd(Res, C);
6788       }
6789       case Instruction::SExt:
6790         // We need to emit a cast to truncate, then a cast to sext.
6791         return CastInst::create(Instruction::SExt,
6792             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6793                              CI), DestTy);
6794       }
6795     }
6796   }
6797   
6798   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6799   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6800
6801   switch (SrcI->getOpcode()) {
6802   case Instruction::Add:
6803   case Instruction::Mul:
6804   case Instruction::And:
6805   case Instruction::Or:
6806   case Instruction::Xor:
6807     // If we are discarding information, rewrite.
6808     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6809       // Don't insert two casts if they cannot be eliminated.  We allow 
6810       // two casts to be inserted if the sizes are the same.  This could 
6811       // only be converting signedness, which is a noop.
6812       if (DestBitSize == SrcBitSize || 
6813           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6814           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6815         Instruction::CastOps opcode = CI.getOpcode();
6816         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6817         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6818         return BinaryOperator::create(
6819             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6820       }
6821     }
6822
6823     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6824     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6825         SrcI->getOpcode() == Instruction::Xor &&
6826         Op1 == ConstantInt::getTrue() &&
6827         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6828       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6829       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6830     }
6831     break;
6832   case Instruction::SDiv:
6833   case Instruction::UDiv:
6834   case Instruction::SRem:
6835   case Instruction::URem:
6836     // If we are just changing the sign, rewrite.
6837     if (DestBitSize == SrcBitSize) {
6838       // Don't insert two casts if they cannot be eliminated.  We allow 
6839       // two casts to be inserted if the sizes are the same.  This could 
6840       // only be converting signedness, which is a noop.
6841       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6842           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6843         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6844                                               Op0, DestTy, SrcI);
6845         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6846                                               Op1, DestTy, SrcI);
6847         return BinaryOperator::create(
6848           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6849       }
6850     }
6851     break;
6852
6853   case Instruction::Shl:
6854     // Allow changing the sign of the source operand.  Do not allow 
6855     // changing the size of the shift, UNLESS the shift amount is a 
6856     // constant.  We must not change variable sized shifts to a smaller 
6857     // size, because it is undefined to shift more bits out than exist 
6858     // in the value.
6859     if (DestBitSize == SrcBitSize ||
6860         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6861       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6862           Instruction::BitCast : Instruction::Trunc);
6863       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6864       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6865       return BinaryOperator::createShl(Op0c, Op1c);
6866     }
6867     break;
6868   case Instruction::AShr:
6869     // If this is a signed shr, and if all bits shifted in are about to be
6870     // truncated off, turn it into an unsigned shr to allow greater
6871     // simplifications.
6872     if (DestBitSize < SrcBitSize &&
6873         isa<ConstantInt>(Op1)) {
6874       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6875       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6876         // Insert the new logical shift right.
6877         return BinaryOperator::createLShr(Op0, Op1);
6878       }
6879     }
6880     break;
6881   }
6882   return 0;
6883 }
6884
6885 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6886   if (Instruction *Result = commonIntCastTransforms(CI))
6887     return Result;
6888   
6889   Value *Src = CI.getOperand(0);
6890   const Type *Ty = CI.getType();
6891   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6892   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6893   
6894   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6895     switch (SrcI->getOpcode()) {
6896     default: break;
6897     case Instruction::LShr:
6898       // We can shrink lshr to something smaller if we know the bits shifted in
6899       // are already zeros.
6900       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6901         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6902         
6903         // Get a mask for the bits shifting in.
6904         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6905         Value* SrcIOp0 = SrcI->getOperand(0);
6906         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6907           if (ShAmt >= DestBitWidth)        // All zeros.
6908             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6909
6910           // Okay, we can shrink this.  Truncate the input, then return a new
6911           // shift.
6912           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6913           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6914                                        Ty, CI);
6915           return BinaryOperator::createLShr(V1, V2);
6916         }
6917       } else {     // This is a variable shr.
6918         
6919         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6920         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6921         // loop-invariant and CSE'd.
6922         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6923           Value *One = ConstantInt::get(SrcI->getType(), 1);
6924
6925           Value *V = InsertNewInstBefore(
6926               BinaryOperator::createShl(One, SrcI->getOperand(1),
6927                                      "tmp"), CI);
6928           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6929                                                             SrcI->getOperand(0),
6930                                                             "tmp"), CI);
6931           Value *Zero = Constant::getNullValue(V->getType());
6932           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6933         }
6934       }
6935       break;
6936     }
6937   }
6938   
6939   return 0;
6940 }
6941
6942 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6943   // If one of the common conversion will work ..
6944   if (Instruction *Result = commonIntCastTransforms(CI))
6945     return Result;
6946
6947   Value *Src = CI.getOperand(0);
6948
6949   // If this is a cast of a cast
6950   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6951     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6952     // types and if the sizes are just right we can convert this into a logical
6953     // 'and' which will be much cheaper than the pair of casts.
6954     if (isa<TruncInst>(CSrc)) {
6955       // Get the sizes of the types involved
6956       Value *A = CSrc->getOperand(0);
6957       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6958       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6959       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6960       // If we're actually extending zero bits and the trunc is a no-op
6961       if (MidSize < DstSize && SrcSize == DstSize) {
6962         // Replace both of the casts with an And of the type mask.
6963         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
6964         Constant *AndConst = ConstantInt::get(AndValue);
6965         Instruction *And = 
6966           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6967         // Unfortunately, if the type changed, we need to cast it back.
6968         if (And->getType() != CI.getType()) {
6969           And->setName(CSrc->getName()+".mask");
6970           InsertNewInstBefore(And, CI);
6971           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6972         }
6973         return And;
6974       }
6975     }
6976   }
6977
6978   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6979     // If we are just checking for a icmp eq of a single bit and zext'ing it
6980     // to an integer, then shift the bit to the appropriate place and then
6981     // cast to integer to avoid the comparison.
6982     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6983       const APInt &Op1CV = Op1C->getValue();
6984       
6985       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
6986       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
6987       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6988           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6989         Value *In = ICI->getOperand(0);
6990         Value *Sh = ConstantInt::get(In->getType(),
6991                                     In->getType()->getPrimitiveSizeInBits()-1);
6992         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
6993                                                         In->getName()+".lobit"),
6994                                  CI);
6995         if (In->getType() != CI.getType())
6996           In = CastInst::createIntegerCast(In, CI.getType(),
6997                                            false/*ZExt*/, "tmp", &CI);
6998
6999         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7000           Constant *One = ConstantInt::get(In->getType(), 1);
7001           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7002                                                           In->getName()+".not"),
7003                                    CI);
7004         }
7005
7006         return ReplaceInstUsesWith(CI, In);
7007       }
7008       
7009       
7010       
7011       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7012       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7013       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7014       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7015       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7016       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7017       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7018       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7019       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7020           // This only works for EQ and NE
7021           ICI->isEquality()) {
7022         // If Op1C some other power of two, convert:
7023         uint32_t BitWidth = Op1C->getType()->getBitWidth();
7024         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7025         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7026         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7027         
7028         APInt KnownZeroMask(~KnownZero);
7029         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7030           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7031           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7032             // (X&4) == 2 --> false
7033             // (X&4) != 2 --> true
7034             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7035             Res = ConstantExpr::getZExt(Res, CI.getType());
7036             return ReplaceInstUsesWith(CI, Res);
7037           }
7038           
7039           uint32_t ShiftAmt = KnownZeroMask.logBase2();
7040           Value *In = ICI->getOperand(0);
7041           if (ShiftAmt) {
7042             // Perform a logical shr by shiftamt.
7043             // Insert the shift to put the result in the low bit.
7044             In = InsertNewInstBefore(
7045                    BinaryOperator::createLShr(In,
7046                                      ConstantInt::get(In->getType(), ShiftAmt),
7047                                               In->getName()+".lobit"), CI);
7048           }
7049           
7050           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7051             Constant *One = ConstantInt::get(In->getType(), 1);
7052             In = BinaryOperator::createXor(In, One, "tmp");
7053             InsertNewInstBefore(cast<Instruction>(In), CI);
7054           }
7055           
7056           if (CI.getType() == In->getType())
7057             return ReplaceInstUsesWith(CI, In);
7058           else
7059             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7060         }
7061       }
7062     }
7063   }    
7064   return 0;
7065 }
7066
7067 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7068   if (Instruction *I = commonIntCastTransforms(CI))
7069     return I;
7070   
7071   Value *Src = CI.getOperand(0);
7072   
7073   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7074   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7075   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7076     // If we are just checking for a icmp eq of a single bit and zext'ing it
7077     // to an integer, then shift the bit to the appropriate place and then
7078     // cast to integer to avoid the comparison.
7079     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7080       const APInt &Op1CV = Op1C->getValue();
7081       
7082       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7083       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7084       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7085           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7086         Value *In = ICI->getOperand(0);
7087         Value *Sh = ConstantInt::get(In->getType(),
7088                                      In->getType()->getPrimitiveSizeInBits()-1);
7089         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7090                                                         In->getName()+".lobit"),
7091                                  CI);
7092         if (In->getType() != CI.getType())
7093           In = CastInst::createIntegerCast(In, CI.getType(),
7094                                            true/*SExt*/, "tmp", &CI);
7095         
7096         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7097           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7098                                      In->getName()+".not"), CI);
7099         
7100         return ReplaceInstUsesWith(CI, In);
7101       }
7102     }
7103   }
7104       
7105   return 0;
7106 }
7107
7108 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7109   return commonCastTransforms(CI);
7110 }
7111
7112 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7113   return commonCastTransforms(CI);
7114 }
7115
7116 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7117   return commonCastTransforms(CI);
7118 }
7119
7120 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7121   return commonCastTransforms(CI);
7122 }
7123
7124 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7125   return commonCastTransforms(CI);
7126 }
7127
7128 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7129   return commonCastTransforms(CI);
7130 }
7131
7132 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7133   return commonPointerCastTransforms(CI);
7134 }
7135
7136 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7137   return commonCastTransforms(CI);
7138 }
7139
7140 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7141   // If the operands are integer typed then apply the integer transforms,
7142   // otherwise just apply the common ones.
7143   Value *Src = CI.getOperand(0);
7144   const Type *SrcTy = Src->getType();
7145   const Type *DestTy = CI.getType();
7146
7147   if (SrcTy->isInteger() && DestTy->isInteger()) {
7148     if (Instruction *Result = commonIntCastTransforms(CI))
7149       return Result;
7150   } else if (isa<PointerType>(SrcTy)) {
7151     if (Instruction *I = commonPointerCastTransforms(CI))
7152       return I;
7153   } else {
7154     if (Instruction *Result = commonCastTransforms(CI))
7155       return Result;
7156   }
7157
7158
7159   // Get rid of casts from one type to the same type. These are useless and can
7160   // be replaced by the operand.
7161   if (DestTy == Src->getType())
7162     return ReplaceInstUsesWith(CI, Src);
7163
7164   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7165     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7166     const Type *DstElTy = DstPTy->getElementType();
7167     const Type *SrcElTy = SrcPTy->getElementType();
7168     
7169     // If we are casting a malloc or alloca to a pointer to a type of the same
7170     // size, rewrite the allocation instruction to allocate the "right" type.
7171     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7172       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7173         return V;
7174     
7175     // If the source and destination are pointers, and this cast is equivalent
7176     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7177     // This can enhance SROA and other transforms that want type-safe pointers.
7178     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7179     unsigned NumZeros = 0;
7180     while (SrcElTy != DstElTy && 
7181            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7182            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7183       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7184       ++NumZeros;
7185     }
7186
7187     // If we found a path from the src to dest, create the getelementptr now.
7188     if (SrcElTy == DstElTy) {
7189       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7190       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7191                                    ((Instruction*) NULL));
7192     }
7193   }
7194
7195   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7196     if (SVI->hasOneUse()) {
7197       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7198       // a bitconvert to a vector with the same # elts.
7199       if (isa<VectorType>(DestTy) && 
7200           cast<VectorType>(DestTy)->getNumElements() == 
7201                 SVI->getType()->getNumElements()) {
7202         CastInst *Tmp;
7203         // If either of the operands is a cast from CI.getType(), then
7204         // evaluating the shuffle in the casted destination's type will allow
7205         // us to eliminate at least one cast.
7206         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7207              Tmp->getOperand(0)->getType() == DestTy) ||
7208             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7209              Tmp->getOperand(0)->getType() == DestTy)) {
7210           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7211                                                SVI->getOperand(0), DestTy, &CI);
7212           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7213                                                SVI->getOperand(1), DestTy, &CI);
7214           // Return a new shuffle vector.  Use the same element ID's, as we
7215           // know the vector types match #elts.
7216           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7217         }
7218       }
7219     }
7220   }
7221   return 0;
7222 }
7223
7224 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7225 ///   %C = or %A, %B
7226 ///   %D = select %cond, %C, %A
7227 /// into:
7228 ///   %C = select %cond, %B, 0
7229 ///   %D = or %A, %C
7230 ///
7231 /// Assuming that the specified instruction is an operand to the select, return
7232 /// a bitmask indicating which operands of this instruction are foldable if they
7233 /// equal the other incoming value of the select.
7234 ///
7235 static unsigned GetSelectFoldableOperands(Instruction *I) {
7236   switch (I->getOpcode()) {
7237   case Instruction::Add:
7238   case Instruction::Mul:
7239   case Instruction::And:
7240   case Instruction::Or:
7241   case Instruction::Xor:
7242     return 3;              // Can fold through either operand.
7243   case Instruction::Sub:   // Can only fold on the amount subtracted.
7244   case Instruction::Shl:   // Can only fold on the shift amount.
7245   case Instruction::LShr:
7246   case Instruction::AShr:
7247     return 1;
7248   default:
7249     return 0;              // Cannot fold
7250   }
7251 }
7252
7253 /// GetSelectFoldableConstant - For the same transformation as the previous
7254 /// function, return the identity constant that goes into the select.
7255 static Constant *GetSelectFoldableConstant(Instruction *I) {
7256   switch (I->getOpcode()) {
7257   default: assert(0 && "This cannot happen!"); abort();
7258   case Instruction::Add:
7259   case Instruction::Sub:
7260   case Instruction::Or:
7261   case Instruction::Xor:
7262   case Instruction::Shl:
7263   case Instruction::LShr:
7264   case Instruction::AShr:
7265     return Constant::getNullValue(I->getType());
7266   case Instruction::And:
7267     return Constant::getAllOnesValue(I->getType());
7268   case Instruction::Mul:
7269     return ConstantInt::get(I->getType(), 1);
7270   }
7271 }
7272
7273 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7274 /// have the same opcode and only one use each.  Try to simplify this.
7275 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7276                                           Instruction *FI) {
7277   if (TI->getNumOperands() == 1) {
7278     // If this is a non-volatile load or a cast from the same type,
7279     // merge.
7280     if (TI->isCast()) {
7281       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7282         return 0;
7283     } else {
7284       return 0;  // unknown unary op.
7285     }
7286
7287     // Fold this by inserting a select from the input values.
7288     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7289                                        FI->getOperand(0), SI.getName()+".v");
7290     InsertNewInstBefore(NewSI, SI);
7291     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7292                             TI->getType());
7293   }
7294
7295   // Only handle binary operators here.
7296   if (!isa<BinaryOperator>(TI))
7297     return 0;
7298
7299   // Figure out if the operations have any operands in common.
7300   Value *MatchOp, *OtherOpT, *OtherOpF;
7301   bool MatchIsOpZero;
7302   if (TI->getOperand(0) == FI->getOperand(0)) {
7303     MatchOp  = TI->getOperand(0);
7304     OtherOpT = TI->getOperand(1);
7305     OtherOpF = FI->getOperand(1);
7306     MatchIsOpZero = true;
7307   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7308     MatchOp  = TI->getOperand(1);
7309     OtherOpT = TI->getOperand(0);
7310     OtherOpF = FI->getOperand(0);
7311     MatchIsOpZero = false;
7312   } else if (!TI->isCommutative()) {
7313     return 0;
7314   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7315     MatchOp  = TI->getOperand(0);
7316     OtherOpT = TI->getOperand(1);
7317     OtherOpF = FI->getOperand(0);
7318     MatchIsOpZero = true;
7319   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7320     MatchOp  = TI->getOperand(1);
7321     OtherOpT = TI->getOperand(0);
7322     OtherOpF = FI->getOperand(1);
7323     MatchIsOpZero = true;
7324   } else {
7325     return 0;
7326   }
7327
7328   // If we reach here, they do have operations in common.
7329   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7330                                      OtherOpF, SI.getName()+".v");
7331   InsertNewInstBefore(NewSI, SI);
7332
7333   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7334     if (MatchIsOpZero)
7335       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7336     else
7337       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7338   }
7339   assert(0 && "Shouldn't get here");
7340   return 0;
7341 }
7342
7343 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7344   Value *CondVal = SI.getCondition();
7345   Value *TrueVal = SI.getTrueValue();
7346   Value *FalseVal = SI.getFalseValue();
7347
7348   // select true, X, Y  -> X
7349   // select false, X, Y -> Y
7350   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7351     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7352
7353   // select C, X, X -> X
7354   if (TrueVal == FalseVal)
7355     return ReplaceInstUsesWith(SI, TrueVal);
7356
7357   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7358     return ReplaceInstUsesWith(SI, FalseVal);
7359   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7360     return ReplaceInstUsesWith(SI, TrueVal);
7361   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7362     if (isa<Constant>(TrueVal))
7363       return ReplaceInstUsesWith(SI, TrueVal);
7364     else
7365       return ReplaceInstUsesWith(SI, FalseVal);
7366   }
7367
7368   if (SI.getType() == Type::Int1Ty) {
7369     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7370       if (C->getZExtValue()) {
7371         // Change: A = select B, true, C --> A = or B, C
7372         return BinaryOperator::createOr(CondVal, FalseVal);
7373       } else {
7374         // Change: A = select B, false, C --> A = and !B, C
7375         Value *NotCond =
7376           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7377                                              "not."+CondVal->getName()), SI);
7378         return BinaryOperator::createAnd(NotCond, FalseVal);
7379       }
7380     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7381       if (C->getZExtValue() == false) {
7382         // Change: A = select B, C, false --> A = and B, C
7383         return BinaryOperator::createAnd(CondVal, TrueVal);
7384       } else {
7385         // Change: A = select B, C, true --> A = or !B, C
7386         Value *NotCond =
7387           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7388                                              "not."+CondVal->getName()), SI);
7389         return BinaryOperator::createOr(NotCond, TrueVal);
7390       }
7391     }
7392     
7393     // select a, b, a  -> a&b
7394     // select a, a, b  -> a|b
7395     if (CondVal == TrueVal)
7396       return BinaryOperator::createOr(CondVal, FalseVal);
7397     else if (CondVal == FalseVal)
7398       return BinaryOperator::createAnd(CondVal, TrueVal);
7399   }
7400
7401   // Selecting between two integer constants?
7402   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7403     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7404       // select C, 1, 0 -> zext C to int
7405       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7406         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7407       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7408         // select C, 0, 1 -> zext !C to int
7409         Value *NotCond =
7410           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7411                                                "not."+CondVal->getName()), SI);
7412         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7413       }
7414       
7415       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7416
7417       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7418
7419         // (x <s 0) ? -1 : 0 -> ashr x, 31
7420         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7421           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7422             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7423               // The comparison constant and the result are not neccessarily the
7424               // same width. Make an all-ones value by inserting a AShr.
7425               Value *X = IC->getOperand(0);
7426               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7427               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7428               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7429                                                         ShAmt, "ones");
7430               InsertNewInstBefore(SRA, SI);
7431               
7432               // Finally, convert to the type of the select RHS.  We figure out
7433               // if this requires a SExt, Trunc or BitCast based on the sizes.
7434               Instruction::CastOps opc = Instruction::BitCast;
7435               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7436               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7437               if (SRASize < SISize)
7438                 opc = Instruction::SExt;
7439               else if (SRASize > SISize)
7440                 opc = Instruction::Trunc;
7441               return CastInst::create(opc, SRA, SI.getType());
7442             }
7443           }
7444
7445
7446         // If one of the constants is zero (we know they can't both be) and we
7447         // have an icmp instruction with zero, and we have an 'and' with the
7448         // non-constant value, eliminate this whole mess.  This corresponds to
7449         // cases like this: ((X & 27) ? 27 : 0)
7450         if (TrueValC->isZero() || FalseValC->isZero())
7451           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7452               cast<Constant>(IC->getOperand(1))->isNullValue())
7453             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7454               if (ICA->getOpcode() == Instruction::And &&
7455                   isa<ConstantInt>(ICA->getOperand(1)) &&
7456                   (ICA->getOperand(1) == TrueValC ||
7457                    ICA->getOperand(1) == FalseValC) &&
7458                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7459                 // Okay, now we know that everything is set up, we just don't
7460                 // know whether we have a icmp_ne or icmp_eq and whether the 
7461                 // true or false val is the zero.
7462                 bool ShouldNotVal = !TrueValC->isZero();
7463                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7464                 Value *V = ICA;
7465                 if (ShouldNotVal)
7466                   V = InsertNewInstBefore(BinaryOperator::create(
7467                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7468                 return ReplaceInstUsesWith(SI, V);
7469               }
7470       }
7471     }
7472
7473   // See if we are selecting two values based on a comparison of the two values.
7474   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7475     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7476       // Transform (X == Y) ? X : Y  -> Y
7477       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7478         // This is not safe in general for floating point:  
7479         // consider X== -0, Y== +0.
7480         // It becomes safe if either operand is a nonzero constant.
7481         ConstantFP *CFPt, *CFPf;
7482         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7483               !CFPt->getValueAPF().isZero()) ||
7484             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7485              !CFPf->getValueAPF().isZero()))
7486         return ReplaceInstUsesWith(SI, FalseVal);
7487       }
7488       // Transform (X != Y) ? X : Y  -> X
7489       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7490         return ReplaceInstUsesWith(SI, TrueVal);
7491       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7492
7493     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7494       // Transform (X == Y) ? Y : X  -> X
7495       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7496         // This is not safe in general for floating point:  
7497         // consider X== -0, Y== +0.
7498         // It becomes safe if either operand is a nonzero constant.
7499         ConstantFP *CFPt, *CFPf;
7500         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7501               !CFPt->getValueAPF().isZero()) ||
7502             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7503              !CFPf->getValueAPF().isZero()))
7504           return ReplaceInstUsesWith(SI, FalseVal);
7505       }
7506       // Transform (X != Y) ? Y : X  -> Y
7507       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7508         return ReplaceInstUsesWith(SI, TrueVal);
7509       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7510     }
7511   }
7512
7513   // See if we are selecting two values based on a comparison of the two values.
7514   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7515     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7516       // Transform (X == Y) ? X : Y  -> Y
7517       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7518         return ReplaceInstUsesWith(SI, FalseVal);
7519       // Transform (X != Y) ? X : Y  -> X
7520       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7521         return ReplaceInstUsesWith(SI, TrueVal);
7522       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7523
7524     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7525       // Transform (X == Y) ? Y : X  -> X
7526       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7527         return ReplaceInstUsesWith(SI, FalseVal);
7528       // Transform (X != Y) ? Y : X  -> Y
7529       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7530         return ReplaceInstUsesWith(SI, TrueVal);
7531       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7532     }
7533   }
7534
7535   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7536     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7537       if (TI->hasOneUse() && FI->hasOneUse()) {
7538         Instruction *AddOp = 0, *SubOp = 0;
7539
7540         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7541         if (TI->getOpcode() == FI->getOpcode())
7542           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7543             return IV;
7544
7545         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7546         // even legal for FP.
7547         if (TI->getOpcode() == Instruction::Sub &&
7548             FI->getOpcode() == Instruction::Add) {
7549           AddOp = FI; SubOp = TI;
7550         } else if (FI->getOpcode() == Instruction::Sub &&
7551                    TI->getOpcode() == Instruction::Add) {
7552           AddOp = TI; SubOp = FI;
7553         }
7554
7555         if (AddOp) {
7556           Value *OtherAddOp = 0;
7557           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7558             OtherAddOp = AddOp->getOperand(1);
7559           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7560             OtherAddOp = AddOp->getOperand(0);
7561           }
7562
7563           if (OtherAddOp) {
7564             // So at this point we know we have (Y -> OtherAddOp):
7565             //        select C, (add X, Y), (sub X, Z)
7566             Value *NegVal;  // Compute -Z
7567             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7568               NegVal = ConstantExpr::getNeg(C);
7569             } else {
7570               NegVal = InsertNewInstBefore(
7571                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7572             }
7573
7574             Value *NewTrueOp = OtherAddOp;
7575             Value *NewFalseOp = NegVal;
7576             if (AddOp != TI)
7577               std::swap(NewTrueOp, NewFalseOp);
7578             Instruction *NewSel =
7579               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7580
7581             NewSel = InsertNewInstBefore(NewSel, SI);
7582             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7583           }
7584         }
7585       }
7586
7587   // See if we can fold the select into one of our operands.
7588   if (SI.getType()->isInteger()) {
7589     // See the comment above GetSelectFoldableOperands for a description of the
7590     // transformation we are doing here.
7591     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7592       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7593           !isa<Constant>(FalseVal))
7594         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7595           unsigned OpToFold = 0;
7596           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7597             OpToFold = 1;
7598           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7599             OpToFold = 2;
7600           }
7601
7602           if (OpToFold) {
7603             Constant *C = GetSelectFoldableConstant(TVI);
7604             Instruction *NewSel =
7605               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7606             InsertNewInstBefore(NewSel, SI);
7607             NewSel->takeName(TVI);
7608             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7609               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7610             else {
7611               assert(0 && "Unknown instruction!!");
7612             }
7613           }
7614         }
7615
7616     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7617       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7618           !isa<Constant>(TrueVal))
7619         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7620           unsigned OpToFold = 0;
7621           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7622             OpToFold = 1;
7623           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7624             OpToFold = 2;
7625           }
7626
7627           if (OpToFold) {
7628             Constant *C = GetSelectFoldableConstant(FVI);
7629             Instruction *NewSel =
7630               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7631             InsertNewInstBefore(NewSel, SI);
7632             NewSel->takeName(FVI);
7633             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7634               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7635             else
7636               assert(0 && "Unknown instruction!!");
7637           }
7638         }
7639   }
7640
7641   if (BinaryOperator::isNot(CondVal)) {
7642     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7643     SI.setOperand(1, FalseVal);
7644     SI.setOperand(2, TrueVal);
7645     return &SI;
7646   }
7647
7648   return 0;
7649 }
7650
7651 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7652 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
7653 /// and it is more than the alignment of the ultimate object, see if we can
7654 /// increase the alignment of the ultimate object, making this check succeed.
7655 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7656                                            unsigned PrefAlign = 0) {
7657   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7658     unsigned Align = GV->getAlignment();
7659     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
7660       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7661
7662     // If there is a large requested alignment and we can, bump up the alignment
7663     // of the global.
7664     if (PrefAlign > Align && GV->hasInitializer()) {
7665       GV->setAlignment(PrefAlign);
7666       Align = PrefAlign;
7667     }
7668     return Align;
7669   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7670     unsigned Align = AI->getAlignment();
7671     if (Align == 0 && TD) {
7672       if (isa<AllocaInst>(AI))
7673         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7674       else if (isa<MallocInst>(AI)) {
7675         // Malloc returns maximally aligned memory.
7676         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7677         Align =
7678           std::max(Align,
7679                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7680         Align =
7681           std::max(Align,
7682                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7683       }
7684     }
7685     
7686     // If there is a requested alignment and if this is an alloca, round up.  We
7687     // don't do this for malloc, because some systems can't respect the request.
7688     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7689       AI->setAlignment(PrefAlign);
7690       Align = PrefAlign;
7691     }
7692     return Align;
7693   } else if (isa<BitCastInst>(V) ||
7694              (isa<ConstantExpr>(V) && 
7695               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7696     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7697                                       TD, PrefAlign);
7698   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7699     // If all indexes are zero, it is just the alignment of the base pointer.
7700     bool AllZeroOperands = true;
7701     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7702       if (!isa<Constant>(GEPI->getOperand(i)) ||
7703           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7704         AllZeroOperands = false;
7705         break;
7706       }
7707
7708     if (AllZeroOperands) {
7709       // Treat this like a bitcast.
7710       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7711     }
7712
7713     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7714     if (BaseAlignment == 0) return 0;
7715
7716     // Otherwise, if the base alignment is >= the alignment we expect for the
7717     // base pointer type, then we know that the resultant pointer is aligned at
7718     // least as much as its type requires.
7719     if (!TD) return 0;
7720
7721     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7722     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7723     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7724     if (Align <= BaseAlignment) {
7725       const Type *GEPTy = GEPI->getType();
7726       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7727       Align = std::min(Align, (unsigned)
7728                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7729       return Align;
7730     }
7731     return 0;
7732   }
7733   return 0;
7734 }
7735
7736
7737 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7738 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7739 /// the heavy lifting.
7740 ///
7741 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7742   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7743   if (!II) return visitCallSite(&CI);
7744   
7745   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7746   // visitCallSite.
7747   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7748     bool Changed = false;
7749
7750     // memmove/cpy/set of zero bytes is a noop.
7751     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7752       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7753
7754       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7755         if (CI->getZExtValue() == 1) {
7756           // Replace the instruction with just byte operations.  We would
7757           // transform other cases to loads/stores, but we don't know if
7758           // alignment is sufficient.
7759         }
7760     }
7761
7762     // If we have a memmove and the source operation is a constant global,
7763     // then the source and dest pointers can't alias, so we can change this
7764     // into a call to memcpy.
7765     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7766       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7767         if (GVSrc->isConstant()) {
7768           Module *M = CI.getParent()->getParent()->getParent();
7769           const char *Name;
7770           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7771               Type::Int32Ty)
7772             Name = "llvm.memcpy.i32";
7773           else
7774             Name = "llvm.memcpy.i64";
7775           Constant *MemCpy = M->getOrInsertFunction(Name,
7776                                      CI.getCalledFunction()->getFunctionType());
7777           CI.setOperand(0, MemCpy);
7778           Changed = true;
7779         }
7780     }
7781
7782     // If we can determine a pointer alignment that is bigger than currently
7783     // set, update the alignment.
7784     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7785       unsigned Alignment1 = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7786       unsigned Alignment2 = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7787       unsigned Align = std::min(Alignment1, Alignment2);
7788       if (MI->getAlignment()->getZExtValue() < Align) {
7789         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7790         Changed = true;
7791       }
7792
7793       // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7794       // load/store.
7795       ConstantInt *MemOpLength = dyn_cast<ConstantInt>(CI.getOperand(3));
7796       if (MemOpLength) {
7797         unsigned Size = MemOpLength->getZExtValue();
7798         unsigned Align = cast<ConstantInt>(CI.getOperand(4))->getZExtValue();
7799         PointerType *NewPtrTy = NULL;
7800         // Destination pointer type is always i8 *
7801         // If Size is 8 then use Int64Ty
7802         // If Size is 4 then use Int32Ty
7803         // If Size is 2 then use Int16Ty
7804         // If Size is 1 then use Int8Ty
7805         if (Size && Size <=8 && !(Size&(Size-1)))
7806           NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
7807
7808         if (NewPtrTy) {
7809           Value *Src = InsertCastBefore(Instruction::BitCast, CI.getOperand(2),
7810                                         NewPtrTy, CI);
7811           Value *Dest = InsertCastBefore(Instruction::BitCast, CI.getOperand(1),
7812                                          NewPtrTy, CI);
7813           Value *L = new LoadInst(Src, "tmp", false, Align, &CI);
7814           Value *NS = new StoreInst(L, Dest, false, Align, &CI);
7815           CI.replaceAllUsesWith(NS);
7816           Changed = true;
7817           return EraseInstFromFunction(CI);
7818         }
7819       }
7820     } else if (isa<MemSetInst>(MI)) {
7821       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
7822       if (MI->getAlignment()->getZExtValue() < Alignment) {
7823         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7824         Changed = true;
7825       }
7826     }
7827           
7828     if (Changed) return II;
7829   } else {
7830     switch (II->getIntrinsicID()) {
7831     default: break;
7832     case Intrinsic::ppc_altivec_lvx:
7833     case Intrinsic::ppc_altivec_lvxl:
7834     case Intrinsic::x86_sse_loadu_ps:
7835     case Intrinsic::x86_sse2_loadu_pd:
7836     case Intrinsic::x86_sse2_loadu_dq:
7837       // Turn PPC lvx     -> load if the pointer is known aligned.
7838       // Turn X86 loadups -> load if the pointer is known aligned.
7839       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
7840         Value *Ptr = 
7841           InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7842                            PointerType::getUnqual(II->getType()), CI);
7843         return new LoadInst(Ptr);
7844       }
7845       break;
7846     case Intrinsic::ppc_altivec_stvx:
7847     case Intrinsic::ppc_altivec_stvxl:
7848       // Turn stvx -> store if the pointer is known aligned.
7849       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
7850         const Type *OpPtrTy = 
7851           PointerType::getUnqual(II->getOperand(1)->getType());
7852         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7853                                       OpPtrTy, CI);
7854         return new StoreInst(II->getOperand(1), Ptr);
7855       }
7856       break;
7857     case Intrinsic::x86_sse_storeu_ps:
7858     case Intrinsic::x86_sse2_storeu_pd:
7859     case Intrinsic::x86_sse2_storeu_dq:
7860     case Intrinsic::x86_sse2_storel_dq:
7861       // Turn X86 storeu -> store if the pointer is known aligned.
7862       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
7863         const Type *OpPtrTy = 
7864           PointerType::getUnqual(II->getOperand(2)->getType());
7865         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7866                                       OpPtrTy, CI);
7867         return new StoreInst(II->getOperand(2), Ptr);
7868       }
7869       break;
7870       
7871     case Intrinsic::x86_sse_cvttss2si: {
7872       // These intrinsics only demands the 0th element of its input vector.  If
7873       // we can simplify the input based on that, do so now.
7874       uint64_t UndefElts;
7875       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7876                                                 UndefElts)) {
7877         II->setOperand(1, V);
7878         return II;
7879       }
7880       break;
7881     }
7882       
7883     case Intrinsic::ppc_altivec_vperm:
7884       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7885       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7886         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7887         
7888         // Check that all of the elements are integer constants or undefs.
7889         bool AllEltsOk = true;
7890         for (unsigned i = 0; i != 16; ++i) {
7891           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7892               !isa<UndefValue>(Mask->getOperand(i))) {
7893             AllEltsOk = false;
7894             break;
7895           }
7896         }
7897         
7898         if (AllEltsOk) {
7899           // Cast the input vectors to byte vectors.
7900           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7901                                         II->getOperand(1), Mask->getType(), CI);
7902           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7903                                         II->getOperand(2), Mask->getType(), CI);
7904           Value *Result = UndefValue::get(Op0->getType());
7905           
7906           // Only extract each element once.
7907           Value *ExtractedElts[32];
7908           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7909           
7910           for (unsigned i = 0; i != 16; ++i) {
7911             if (isa<UndefValue>(Mask->getOperand(i)))
7912               continue;
7913             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7914             Idx &= 31;  // Match the hardware behavior.
7915             
7916             if (ExtractedElts[Idx] == 0) {
7917               Instruction *Elt = 
7918                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7919               InsertNewInstBefore(Elt, CI);
7920               ExtractedElts[Idx] = Elt;
7921             }
7922           
7923             // Insert this value into the result vector.
7924             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7925             InsertNewInstBefore(cast<Instruction>(Result), CI);
7926           }
7927           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7928         }
7929       }
7930       break;
7931
7932     case Intrinsic::stackrestore: {
7933       // If the save is right next to the restore, remove the restore.  This can
7934       // happen when variable allocas are DCE'd.
7935       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7936         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7937           BasicBlock::iterator BI = SS;
7938           if (&*++BI == II)
7939             return EraseInstFromFunction(CI);
7940         }
7941       }
7942       
7943       // If the stack restore is in a return/unwind block and if there are no
7944       // allocas or calls between the restore and the return, nuke the restore.
7945       TerminatorInst *TI = II->getParent()->getTerminator();
7946       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7947         BasicBlock::iterator BI = II;
7948         bool CannotRemove = false;
7949         for (++BI; &*BI != TI; ++BI) {
7950           if (isa<AllocaInst>(BI) ||
7951               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7952             CannotRemove = true;
7953             break;
7954           }
7955         }
7956         if (!CannotRemove)
7957           return EraseInstFromFunction(CI);
7958       }
7959       break;
7960     }
7961     }
7962   }
7963
7964   return visitCallSite(II);
7965 }
7966
7967 // InvokeInst simplification
7968 //
7969 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7970   return visitCallSite(&II);
7971 }
7972
7973 // visitCallSite - Improvements for call and invoke instructions.
7974 //
7975 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7976   bool Changed = false;
7977
7978   // If the callee is a constexpr cast of a function, attempt to move the cast
7979   // to the arguments of the call/invoke.
7980   if (transformConstExprCastCall(CS)) return 0;
7981
7982   Value *Callee = CS.getCalledValue();
7983
7984   if (Function *CalleeF = dyn_cast<Function>(Callee))
7985     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7986       Instruction *OldCall = CS.getInstruction();
7987       // If the call and callee calling conventions don't match, this call must
7988       // be unreachable, as the call is undefined.
7989       new StoreInst(ConstantInt::getTrue(),
7990                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
7991                                     OldCall);
7992       if (!OldCall->use_empty())
7993         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7994       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7995         return EraseInstFromFunction(*OldCall);
7996       return 0;
7997     }
7998
7999   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8000     // This instruction is not reachable, just remove it.  We insert a store to
8001     // undef so that we know that this code is not reachable, despite the fact
8002     // that we can't modify the CFG here.
8003     new StoreInst(ConstantInt::getTrue(),
8004                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8005                   CS.getInstruction());
8006
8007     if (!CS.getInstruction()->use_empty())
8008       CS.getInstruction()->
8009         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8010
8011     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8012       // Don't break the CFG, insert a dummy cond branch.
8013       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8014                      ConstantInt::getTrue(), II);
8015     }
8016     return EraseInstFromFunction(*CS.getInstruction());
8017   }
8018
8019   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8020     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8021       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8022         return transformCallThroughTrampoline(CS);
8023
8024   const PointerType *PTy = cast<PointerType>(Callee->getType());
8025   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8026   if (FTy->isVarArg()) {
8027     // See if we can optimize any arguments passed through the varargs area of
8028     // the call.
8029     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8030            E = CS.arg_end(); I != E; ++I)
8031       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8032         // If this cast does not effect the value passed through the varargs
8033         // area, we can eliminate the use of the cast.
8034         Value *Op = CI->getOperand(0);
8035         if (CI->isLosslessCast()) {
8036           *I = Op;
8037           Changed = true;
8038         }
8039       }
8040   }
8041
8042   if (isa<InlineAsm>(Callee) && !CS.isNoUnwind()) {
8043     // Inline asm calls cannot throw - mark them 'nounwind'.
8044     const ParamAttrsList *PAL = CS.getParamAttrs();
8045     uint16_t RAttributes = PAL ? PAL->getParamAttrs(0) : 0;
8046     RAttributes |= ParamAttr::NoUnwind;
8047
8048     ParamAttrsVector modVec;
8049     modVec.push_back(ParamAttrsWithIndex::get(0, RAttributes));
8050     PAL = ParamAttrsList::getModified(PAL, modVec);
8051     CS.setParamAttrs(PAL);
8052     Changed = true;
8053   }
8054
8055   return Changed ? CS.getInstruction() : 0;
8056 }
8057
8058 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8059 // attempt to move the cast to the arguments of the call/invoke.
8060 //
8061 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8062   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8063   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8064   if (CE->getOpcode() != Instruction::BitCast || 
8065       !isa<Function>(CE->getOperand(0)))
8066     return false;
8067   Function *Callee = cast<Function>(CE->getOperand(0));
8068   Instruction *Caller = CS.getInstruction();
8069
8070   // Okay, this is a cast from a function to a different type.  Unless doing so
8071   // would cause a type conversion of one of our arguments, change this call to
8072   // be a direct call with arguments casted to the appropriate types.
8073   //
8074   const FunctionType *FT = Callee->getFunctionType();
8075   const Type *OldRetTy = Caller->getType();
8076
8077   const ParamAttrsList* CallerPAL = 0;
8078   if (CallInst *CallerCI = dyn_cast<CallInst>(Caller))
8079     CallerPAL = CallerCI->getParamAttrs();
8080   else if (InvokeInst *CallerII = dyn_cast<InvokeInst>(Caller))
8081     CallerPAL = CallerII->getParamAttrs();
8082
8083   // If the parameter attributes are not compatible, don't do the xform.  We
8084   // don't want to lose an sret attribute or something.
8085   if (!ParamAttrsList::areCompatible(CallerPAL, Callee->getParamAttrs()))
8086     return false;
8087
8088   // Check to see if we are changing the return type...
8089   if (OldRetTy != FT->getReturnType()) {
8090     if (Callee->isDeclaration() && !Caller->use_empty() && 
8091         // Conversion is ok if changing from pointer to int of same size.
8092         !(isa<PointerType>(FT->getReturnType()) &&
8093           TD->getIntPtrType() == OldRetTy))
8094       return false;   // Cannot transform this return value.
8095
8096     // If the callsite is an invoke instruction, and the return value is used by
8097     // a PHI node in a successor, we cannot change the return type of the call
8098     // because there is no place to put the cast instruction (without breaking
8099     // the critical edge).  Bail out in this case.
8100     if (!Caller->use_empty())
8101       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8102         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8103              UI != E; ++UI)
8104           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8105             if (PN->getParent() == II->getNormalDest() ||
8106                 PN->getParent() == II->getUnwindDest())
8107               return false;
8108   }
8109
8110   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8111   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8112
8113   CallSite::arg_iterator AI = CS.arg_begin();
8114   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8115     const Type *ParamTy = FT->getParamType(i);
8116     const Type *ActTy = (*AI)->getType();
8117     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8118     //Some conversions are safe even if we do not have a body.
8119     //Either we can cast directly, or we can upconvert the argument
8120     bool isConvertible = ActTy == ParamTy ||
8121       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8122       (ParamTy->isInteger() && ActTy->isInteger() &&
8123        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8124       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8125        && c->getValue().isStrictlyPositive());
8126     if (Callee->isDeclaration() && !isConvertible) return false;
8127
8128     // Most other conversions can be done if we have a body, even if these
8129     // lose information, e.g. int->short.
8130     // Some conversions cannot be done at all, e.g. float to pointer.
8131     // Logic here parallels CastInst::getCastOpcode (the design there
8132     // requires legality checks like this be done before calling it).
8133     if (ParamTy->isInteger()) {
8134       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8135         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
8136           return false;
8137       }
8138       if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
8139           !isa<PointerType>(ActTy))
8140         return false;
8141     } else if (ParamTy->isFloatingPoint()) {
8142       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8143         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
8144           return false;
8145       }
8146       if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
8147         return false;
8148     } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
8149       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8150         if (VActTy->getBitWidth() != VParamTy->getBitWidth())
8151           return false;
8152       }
8153       if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())      
8154         return false;
8155     } else if (isa<PointerType>(ParamTy)) {
8156       if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
8157         return false;
8158     } else {
8159       return false;
8160     }
8161   }
8162
8163   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8164       Callee->isDeclaration())
8165     return false;   // Do not delete arguments unless we have a function body...
8166
8167   // Okay, we decided that this is a safe thing to do: go ahead and start
8168   // inserting cast instructions as necessary...
8169   std::vector<Value*> Args;
8170   Args.reserve(NumActualArgs);
8171
8172   AI = CS.arg_begin();
8173   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8174     const Type *ParamTy = FT->getParamType(i);
8175     if ((*AI)->getType() == ParamTy) {
8176       Args.push_back(*AI);
8177     } else {
8178       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8179           false, ParamTy, false);
8180       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8181       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8182     }
8183   }
8184
8185   // If the function takes more arguments than the call was taking, add them
8186   // now...
8187   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8188     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8189
8190   // If we are removing arguments to the function, emit an obnoxious warning...
8191   if (FT->getNumParams() < NumActualArgs)
8192     if (!FT->isVarArg()) {
8193       cerr << "WARNING: While resolving call to function '"
8194            << Callee->getName() << "' arguments were dropped!\n";
8195     } else {
8196       // Add all of the arguments in their promoted form to the arg list...
8197       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8198         const Type *PTy = getPromotedType((*AI)->getType());
8199         if (PTy != (*AI)->getType()) {
8200           // Must promote to pass through va_arg area!
8201           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8202                                                                 PTy, false);
8203           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8204           InsertNewInstBefore(Cast, *Caller);
8205           Args.push_back(Cast);
8206         } else {
8207           Args.push_back(*AI);
8208         }
8209       }
8210     }
8211
8212   if (FT->getReturnType() == Type::VoidTy)
8213     Caller->setName("");   // Void type should not have a name.
8214
8215   Instruction *NC;
8216   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8217     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8218                         Args.begin(), Args.end(), Caller->getName(), Caller);
8219     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8220     cast<InvokeInst>(NC)->setParamAttrs(CallerPAL);
8221   } else {
8222     NC = new CallInst(Callee, Args.begin(), Args.end(),
8223                       Caller->getName(), Caller);
8224     CallInst *CI = cast<CallInst>(Caller);
8225     if (CI->isTailCall())
8226       cast<CallInst>(NC)->setTailCall();
8227     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8228     cast<CallInst>(NC)->setParamAttrs(CallerPAL);
8229   }
8230
8231   // Insert a cast of the return type as necessary.
8232   Value *NV = NC;
8233   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8234     if (NV->getType() != Type::VoidTy) {
8235       const Type *CallerTy = Caller->getType();
8236       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8237                                                             CallerTy, false);
8238       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
8239
8240       // If this is an invoke instruction, we should insert it after the first
8241       // non-phi, instruction in the normal successor block.
8242       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8243         BasicBlock::iterator I = II->getNormalDest()->begin();
8244         while (isa<PHINode>(I)) ++I;
8245         InsertNewInstBefore(NC, *I);
8246       } else {
8247         // Otherwise, it's a call, just insert cast right after the call instr
8248         InsertNewInstBefore(NC, *Caller);
8249       }
8250       AddUsersToWorkList(*Caller);
8251     } else {
8252       NV = UndefValue::get(Caller->getType());
8253     }
8254   }
8255
8256   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8257     Caller->replaceAllUsesWith(NV);
8258   Caller->eraseFromParent();
8259   RemoveFromWorkList(Caller);
8260   return true;
8261 }
8262
8263 // transformCallThroughTrampoline - Turn a call to a function created by the
8264 // init_trampoline intrinsic into a direct call to the underlying function.
8265 //
8266 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8267   Value *Callee = CS.getCalledValue();
8268   const PointerType *PTy = cast<PointerType>(Callee->getType());
8269   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8270
8271   IntrinsicInst *Tramp =
8272     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8273
8274   Function *NestF =
8275     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8276   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8277   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8278
8279   if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
8280     unsigned NestIdx = 1;
8281     const Type *NestTy = 0;
8282     uint16_t NestAttr = 0;
8283
8284     // Look for a parameter marked with the 'nest' attribute.
8285     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8286          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8287       if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8288         // Record the parameter type and any other attributes.
8289         NestTy = *I;
8290         NestAttr = NestAttrs->getParamAttrs(NestIdx);
8291         break;
8292       }
8293
8294     if (NestTy) {
8295       Instruction *Caller = CS.getInstruction();
8296       std::vector<Value*> NewArgs;
8297       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8298
8299       // Insert the nest argument into the call argument list, which may
8300       // mean appending it.
8301       {
8302         unsigned Idx = 1;
8303         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8304         do {
8305           if (Idx == NestIdx) {
8306             // Add the chain argument.
8307             Value *NestVal = Tramp->getOperand(3);
8308             if (NestVal->getType() != NestTy)
8309               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8310             NewArgs.push_back(NestVal);
8311           }
8312
8313           if (I == E)
8314             break;
8315
8316           // Add the original argument.
8317           NewArgs.push_back(*I);
8318
8319           ++Idx, ++I;
8320         } while (1);
8321       }
8322
8323       // The trampoline may have been bitcast to a bogus type (FTy).
8324       // Handle this by synthesizing a new function type, equal to FTy
8325       // with the chain parameter inserted.  Likewise for attributes.
8326
8327       const ParamAttrsList *Attrs = CS.getParamAttrs();
8328       std::vector<const Type*> NewTypes;
8329       ParamAttrsVector NewAttrs;
8330       NewTypes.reserve(FTy->getNumParams()+1);
8331
8332       // Add any function result attributes.
8333       uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8334       if (Attr)
8335         NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8336
8337       // Insert the chain's type into the list of parameter types, which may
8338       // mean appending it.  Likewise for the chain's attributes.
8339       {
8340         unsigned Idx = 1;
8341         FunctionType::param_iterator I = FTy->param_begin(),
8342           E = FTy->param_end();
8343
8344         do {
8345           if (Idx == NestIdx) {
8346             // Add the chain's type and attributes.
8347             NewTypes.push_back(NestTy);
8348             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8349           }
8350
8351           if (I == E)
8352             break;
8353
8354           // Add the original type and attributes.
8355           NewTypes.push_back(*I);
8356           Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8357           if (Attr)
8358             NewAttrs.push_back
8359               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8360
8361           ++Idx, ++I;
8362         } while (1);
8363       }
8364
8365       // Replace the trampoline call with a direct call.  Let the generic
8366       // code sort out any function type mismatches.
8367       FunctionType *NewFTy =
8368         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8369       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8370         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8371       const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
8372
8373       Instruction *NewCaller;
8374       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8375         NewCaller = new InvokeInst(NewCallee,
8376                                    II->getNormalDest(), II->getUnwindDest(),
8377                                    NewArgs.begin(), NewArgs.end(),
8378                                    Caller->getName(), Caller);
8379         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8380         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8381       } else {
8382         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8383                                  Caller->getName(), Caller);
8384         if (cast<CallInst>(Caller)->isTailCall())
8385           cast<CallInst>(NewCaller)->setTailCall();
8386         cast<CallInst>(NewCaller)->
8387           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8388         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8389       }
8390       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8391         Caller->replaceAllUsesWith(NewCaller);
8392       Caller->eraseFromParent();
8393       RemoveFromWorkList(Caller);
8394       return 0;
8395     }
8396   }
8397
8398   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8399   // parameter, there is no need to adjust the argument list.  Let the generic
8400   // code sort out any function type mismatches.
8401   Constant *NewCallee =
8402     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8403   CS.setCalledFunction(NewCallee);
8404   return CS.getInstruction();
8405 }
8406
8407 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8408 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8409 /// and a single binop.
8410 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8411   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8412   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8413          isa<CmpInst>(FirstInst));
8414   unsigned Opc = FirstInst->getOpcode();
8415   Value *LHSVal = FirstInst->getOperand(0);
8416   Value *RHSVal = FirstInst->getOperand(1);
8417     
8418   const Type *LHSType = LHSVal->getType();
8419   const Type *RHSType = RHSVal->getType();
8420   
8421   // Scan to see if all operands are the same opcode, all have one use, and all
8422   // kill their operands (i.e. the operands have one use).
8423   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8424     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8425     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8426         // Verify type of the LHS matches so we don't fold cmp's of different
8427         // types or GEP's with different index types.
8428         I->getOperand(0)->getType() != LHSType ||
8429         I->getOperand(1)->getType() != RHSType)
8430       return 0;
8431
8432     // If they are CmpInst instructions, check their predicates
8433     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8434       if (cast<CmpInst>(I)->getPredicate() !=
8435           cast<CmpInst>(FirstInst)->getPredicate())
8436         return 0;
8437     
8438     // Keep track of which operand needs a phi node.
8439     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8440     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8441   }
8442   
8443   // Otherwise, this is safe to transform, determine if it is profitable.
8444
8445   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8446   // Indexes are often folded into load/store instructions, so we don't want to
8447   // hide them behind a phi.
8448   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8449     return 0;
8450   
8451   Value *InLHS = FirstInst->getOperand(0);
8452   Value *InRHS = FirstInst->getOperand(1);
8453   PHINode *NewLHS = 0, *NewRHS = 0;
8454   if (LHSVal == 0) {
8455     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8456     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8457     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8458     InsertNewInstBefore(NewLHS, PN);
8459     LHSVal = NewLHS;
8460   }
8461   
8462   if (RHSVal == 0) {
8463     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8464     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8465     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8466     InsertNewInstBefore(NewRHS, PN);
8467     RHSVal = NewRHS;
8468   }
8469   
8470   // Add all operands to the new PHIs.
8471   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8472     if (NewLHS) {
8473       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8474       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8475     }
8476     if (NewRHS) {
8477       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8478       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8479     }
8480   }
8481     
8482   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8483     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8484   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8485     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8486                            RHSVal);
8487   else {
8488     assert(isa<GetElementPtrInst>(FirstInst));
8489     return new GetElementPtrInst(LHSVal, RHSVal);
8490   }
8491 }
8492
8493 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8494 /// of the block that defines it.  This means that it must be obvious the value
8495 /// of the load is not changed from the point of the load to the end of the
8496 /// block it is in.
8497 ///
8498 /// Finally, it is safe, but not profitable, to sink a load targetting a
8499 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8500 /// to a register.
8501 static bool isSafeToSinkLoad(LoadInst *L) {
8502   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8503   
8504   for (++BBI; BBI != E; ++BBI)
8505     if (BBI->mayWriteToMemory())
8506       return false;
8507   
8508   // Check for non-address taken alloca.  If not address-taken already, it isn't
8509   // profitable to do this xform.
8510   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8511     bool isAddressTaken = false;
8512     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8513          UI != E; ++UI) {
8514       if (isa<LoadInst>(UI)) continue;
8515       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8516         // If storing TO the alloca, then the address isn't taken.
8517         if (SI->getOperand(1) == AI) continue;
8518       }
8519       isAddressTaken = true;
8520       break;
8521     }
8522     
8523     if (!isAddressTaken)
8524       return false;
8525   }
8526   
8527   return true;
8528 }
8529
8530
8531 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8532 // operator and they all are only used by the PHI, PHI together their
8533 // inputs, and do the operation once, to the result of the PHI.
8534 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8535   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8536
8537   // Scan the instruction, looking for input operations that can be folded away.
8538   // If all input operands to the phi are the same instruction (e.g. a cast from
8539   // the same type or "+42") we can pull the operation through the PHI, reducing
8540   // code size and simplifying code.
8541   Constant *ConstantOp = 0;
8542   const Type *CastSrcTy = 0;
8543   bool isVolatile = false;
8544   if (isa<CastInst>(FirstInst)) {
8545     CastSrcTy = FirstInst->getOperand(0)->getType();
8546   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8547     // Can fold binop, compare or shift here if the RHS is a constant, 
8548     // otherwise call FoldPHIArgBinOpIntoPHI.
8549     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8550     if (ConstantOp == 0)
8551       return FoldPHIArgBinOpIntoPHI(PN);
8552   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8553     isVolatile = LI->isVolatile();
8554     // We can't sink the load if the loaded value could be modified between the
8555     // load and the PHI.
8556     if (LI->getParent() != PN.getIncomingBlock(0) ||
8557         !isSafeToSinkLoad(LI))
8558       return 0;
8559   } else if (isa<GetElementPtrInst>(FirstInst)) {
8560     if (FirstInst->getNumOperands() == 2)
8561       return FoldPHIArgBinOpIntoPHI(PN);
8562     // Can't handle general GEPs yet.
8563     return 0;
8564   } else {
8565     return 0;  // Cannot fold this operation.
8566   }
8567
8568   // Check to see if all arguments are the same operation.
8569   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8570     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8571     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8572     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8573       return 0;
8574     if (CastSrcTy) {
8575       if (I->getOperand(0)->getType() != CastSrcTy)
8576         return 0;  // Cast operation must match.
8577     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8578       // We can't sink the load if the loaded value could be modified between 
8579       // the load and the PHI.
8580       if (LI->isVolatile() != isVolatile ||
8581           LI->getParent() != PN.getIncomingBlock(i) ||
8582           !isSafeToSinkLoad(LI))
8583         return 0;
8584     } else if (I->getOperand(1) != ConstantOp) {
8585       return 0;
8586     }
8587   }
8588
8589   // Okay, they are all the same operation.  Create a new PHI node of the
8590   // correct type, and PHI together all of the LHS's of the instructions.
8591   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8592                                PN.getName()+".in");
8593   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8594
8595   Value *InVal = FirstInst->getOperand(0);
8596   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8597
8598   // Add all operands to the new PHI.
8599   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8600     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8601     if (NewInVal != InVal)
8602       InVal = 0;
8603     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8604   }
8605
8606   Value *PhiVal;
8607   if (InVal) {
8608     // The new PHI unions all of the same values together.  This is really
8609     // common, so we handle it intelligently here for compile-time speed.
8610     PhiVal = InVal;
8611     delete NewPN;
8612   } else {
8613     InsertNewInstBefore(NewPN, PN);
8614     PhiVal = NewPN;
8615   }
8616
8617   // Insert and return the new operation.
8618   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8619     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8620   else if (isa<LoadInst>(FirstInst))
8621     return new LoadInst(PhiVal, "", isVolatile);
8622   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8623     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8624   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8625     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8626                            PhiVal, ConstantOp);
8627   else
8628     assert(0 && "Unknown operation");
8629   return 0;
8630 }
8631
8632 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8633 /// that is dead.
8634 static bool DeadPHICycle(PHINode *PN,
8635                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8636   if (PN->use_empty()) return true;
8637   if (!PN->hasOneUse()) return false;
8638
8639   // Remember this node, and if we find the cycle, return.
8640   if (!PotentiallyDeadPHIs.insert(PN))
8641     return true;
8642   
8643   // Don't scan crazily complex things.
8644   if (PotentiallyDeadPHIs.size() == 16)
8645     return false;
8646
8647   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8648     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8649
8650   return false;
8651 }
8652
8653 /// PHIsEqualValue - Return true if this phi node is always equal to
8654 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
8655 ///   z = some value; x = phi (y, z); y = phi (x, z)
8656 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
8657                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8658   // See if we already saw this PHI node.
8659   if (!ValueEqualPHIs.insert(PN))
8660     return true;
8661   
8662   // Don't scan crazily complex things.
8663   if (ValueEqualPHIs.size() == 16)
8664     return false;
8665  
8666   // Scan the operands to see if they are either phi nodes or are equal to
8667   // the value.
8668   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8669     Value *Op = PN->getIncomingValue(i);
8670     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8671       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8672         return false;
8673     } else if (Op != NonPhiInVal)
8674       return false;
8675   }
8676   
8677   return true;
8678 }
8679
8680
8681 // PHINode simplification
8682 //
8683 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8684   // If LCSSA is around, don't mess with Phi nodes
8685   if (MustPreserveLCSSA) return 0;
8686   
8687   if (Value *V = PN.hasConstantValue())
8688     return ReplaceInstUsesWith(PN, V);
8689
8690   // If all PHI operands are the same operation, pull them through the PHI,
8691   // reducing code size.
8692   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8693       PN.getIncomingValue(0)->hasOneUse())
8694     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8695       return Result;
8696
8697   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8698   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8699   // PHI)... break the cycle.
8700   if (PN.hasOneUse()) {
8701     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8702     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8703       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8704       PotentiallyDeadPHIs.insert(&PN);
8705       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8706         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8707     }
8708    
8709     // If this phi has a single use, and if that use just computes a value for
8710     // the next iteration of a loop, delete the phi.  This occurs with unused
8711     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8712     // common case here is good because the only other things that catch this
8713     // are induction variable analysis (sometimes) and ADCE, which is only run
8714     // late.
8715     if (PHIUser->hasOneUse() &&
8716         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8717         PHIUser->use_back() == &PN) {
8718       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8719     }
8720   }
8721
8722   // We sometimes end up with phi cycles that non-obviously end up being the
8723   // same value, for example:
8724   //   z = some value; x = phi (y, z); y = phi (x, z)
8725   // where the phi nodes don't necessarily need to be in the same block.  Do a
8726   // quick check to see if the PHI node only contains a single non-phi value, if
8727   // so, scan to see if the phi cycle is actually equal to that value.
8728   {
8729     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8730     // Scan for the first non-phi operand.
8731     while (InValNo != NumOperandVals && 
8732            isa<PHINode>(PN.getIncomingValue(InValNo)))
8733       ++InValNo;
8734
8735     if (InValNo != NumOperandVals) {
8736       Value *NonPhiInVal = PN.getOperand(InValNo);
8737       
8738       // Scan the rest of the operands to see if there are any conflicts, if so
8739       // there is no need to recursively scan other phis.
8740       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8741         Value *OpVal = PN.getIncomingValue(InValNo);
8742         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8743           break;
8744       }
8745       
8746       // If we scanned over all operands, then we have one unique value plus
8747       // phi values.  Scan PHI nodes to see if they all merge in each other or
8748       // the value.
8749       if (InValNo == NumOperandVals) {
8750         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8751         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8752           return ReplaceInstUsesWith(PN, NonPhiInVal);
8753       }
8754     }
8755   }
8756   return 0;
8757 }
8758
8759 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8760                                    Instruction *InsertPoint,
8761                                    InstCombiner *IC) {
8762   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8763   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8764   // We must cast correctly to the pointer type. Ensure that we
8765   // sign extend the integer value if it is smaller as this is
8766   // used for address computation.
8767   Instruction::CastOps opcode = 
8768      (VTySize < PtrSize ? Instruction::SExt :
8769       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8770   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8771 }
8772
8773
8774 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8775   Value *PtrOp = GEP.getOperand(0);
8776   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
8777   // If so, eliminate the noop.
8778   if (GEP.getNumOperands() == 1)
8779     return ReplaceInstUsesWith(GEP, PtrOp);
8780
8781   if (isa<UndefValue>(GEP.getOperand(0)))
8782     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8783
8784   bool HasZeroPointerIndex = false;
8785   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8786     HasZeroPointerIndex = C->isNullValue();
8787
8788   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8789     return ReplaceInstUsesWith(GEP, PtrOp);
8790
8791   // Eliminate unneeded casts for indices.
8792   bool MadeChange = false;
8793   
8794   gep_type_iterator GTI = gep_type_begin(GEP);
8795   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8796     if (isa<SequentialType>(*GTI)) {
8797       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8798         if (CI->getOpcode() == Instruction::ZExt ||
8799             CI->getOpcode() == Instruction::SExt) {
8800           const Type *SrcTy = CI->getOperand(0)->getType();
8801           // We can eliminate a cast from i32 to i64 iff the target 
8802           // is a 32-bit pointer target.
8803           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8804             MadeChange = true;
8805             GEP.setOperand(i, CI->getOperand(0));
8806           }
8807         }
8808       }
8809       // If we are using a wider index than needed for this platform, shrink it
8810       // to what we need.  If the incoming value needs a cast instruction,
8811       // insert it.  This explicit cast can make subsequent optimizations more
8812       // obvious.
8813       Value *Op = GEP.getOperand(i);
8814       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
8815         if (Constant *C = dyn_cast<Constant>(Op)) {
8816           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8817           MadeChange = true;
8818         } else {
8819           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8820                                 GEP);
8821           GEP.setOperand(i, Op);
8822           MadeChange = true;
8823         }
8824     }
8825   }
8826   if (MadeChange) return &GEP;
8827
8828   // If this GEP instruction doesn't move the pointer, and if the input operand
8829   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8830   // real input to the dest type.
8831   if (GEP.hasAllZeroIndices()) {
8832     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
8833       // If the bitcast is of an allocation, and the allocation will be
8834       // converted to match the type of the cast, don't touch this.
8835       if (isa<AllocationInst>(BCI->getOperand(0))) {
8836         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
8837         if (Instruction *I = visitBitCast(*BCI)) {
8838           if (I != BCI) {
8839             I->takeName(BCI);
8840             BCI->getParent()->getInstList().insert(BCI, I);
8841             ReplaceInstUsesWith(*BCI, I);
8842           }
8843           return &GEP;
8844         }
8845       }
8846       return new BitCastInst(BCI->getOperand(0), GEP.getType());
8847     }
8848   }
8849   
8850   // Combine Indices - If the source pointer to this getelementptr instruction
8851   // is a getelementptr instruction, combine the indices of the two
8852   // getelementptr instructions into a single instruction.
8853   //
8854   SmallVector<Value*, 8> SrcGEPOperands;
8855   if (User *Src = dyn_castGetElementPtr(PtrOp))
8856     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8857
8858   if (!SrcGEPOperands.empty()) {
8859     // Note that if our source is a gep chain itself that we wait for that
8860     // chain to be resolved before we perform this transformation.  This
8861     // avoids us creating a TON of code in some cases.
8862     //
8863     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8864         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8865       return 0;   // Wait until our source is folded to completion.
8866
8867     SmallVector<Value*, 8> Indices;
8868
8869     // Find out whether the last index in the source GEP is a sequential idx.
8870     bool EndsWithSequential = false;
8871     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8872            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8873       EndsWithSequential = !isa<StructType>(*I);
8874
8875     // Can we combine the two pointer arithmetics offsets?
8876     if (EndsWithSequential) {
8877       // Replace: gep (gep %P, long B), long A, ...
8878       // With:    T = long A+B; gep %P, T, ...
8879       //
8880       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8881       if (SO1 == Constant::getNullValue(SO1->getType())) {
8882         Sum = GO1;
8883       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8884         Sum = SO1;
8885       } else {
8886         // If they aren't the same type, convert both to an integer of the
8887         // target's pointer size.
8888         if (SO1->getType() != GO1->getType()) {
8889           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8890             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8891           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8892             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8893           } else {
8894             unsigned PS = TD->getPointerSizeInBits();
8895             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
8896               // Convert GO1 to SO1's type.
8897               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8898
8899             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
8900               // Convert SO1 to GO1's type.
8901               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8902             } else {
8903               const Type *PT = TD->getIntPtrType();
8904               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8905               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8906             }
8907           }
8908         }
8909         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8910           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8911         else {
8912           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8913           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8914         }
8915       }
8916
8917       // Recycle the GEP we already have if possible.
8918       if (SrcGEPOperands.size() == 2) {
8919         GEP.setOperand(0, SrcGEPOperands[0]);
8920         GEP.setOperand(1, Sum);
8921         return &GEP;
8922       } else {
8923         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8924                        SrcGEPOperands.end()-1);
8925         Indices.push_back(Sum);
8926         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8927       }
8928     } else if (isa<Constant>(*GEP.idx_begin()) &&
8929                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8930                SrcGEPOperands.size() != 1) {
8931       // Otherwise we can do the fold if the first index of the GEP is a zero
8932       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8933                      SrcGEPOperands.end());
8934       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8935     }
8936
8937     if (!Indices.empty())
8938       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
8939                                    Indices.end(), GEP.getName());
8940
8941   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8942     // GEP of global variable.  If all of the indices for this GEP are
8943     // constants, we can promote this to a constexpr instead of an instruction.
8944
8945     // Scan for nonconstants...
8946     SmallVector<Constant*, 8> Indices;
8947     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8948     for (; I != E && isa<Constant>(*I); ++I)
8949       Indices.push_back(cast<Constant>(*I));
8950
8951     if (I == E) {  // If they are all constants...
8952       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8953                                                     &Indices[0],Indices.size());
8954
8955       // Replace all uses of the GEP with the new constexpr...
8956       return ReplaceInstUsesWith(GEP, CE);
8957     }
8958   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8959     if (!isa<PointerType>(X->getType())) {
8960       // Not interesting.  Source pointer must be a cast from pointer.
8961     } else if (HasZeroPointerIndex) {
8962       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
8963       // into     : GEP [10 x i8]* X, i32 0, ...
8964       //
8965       // This occurs when the program declares an array extern like "int X[];"
8966       //
8967       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8968       const PointerType *XTy = cast<PointerType>(X->getType());
8969       if (const ArrayType *XATy =
8970           dyn_cast<ArrayType>(XTy->getElementType()))
8971         if (const ArrayType *CATy =
8972             dyn_cast<ArrayType>(CPTy->getElementType()))
8973           if (CATy->getElementType() == XATy->getElementType()) {
8974             // At this point, we know that the cast source type is a pointer
8975             // to an array of the same type as the destination pointer
8976             // array.  Because the array type is never stepped over (there
8977             // is a leading zero) we can fold the cast into this GEP.
8978             GEP.setOperand(0, X);
8979             return &GEP;
8980           }
8981     } else if (GEP.getNumOperands() == 2) {
8982       // Transform things like:
8983       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
8984       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
8985       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8986       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8987       if (isa<ArrayType>(SrcElTy) &&
8988           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8989           TD->getABITypeSize(ResElTy)) {
8990         Value *Idx[2];
8991         Idx[0] = Constant::getNullValue(Type::Int32Ty);
8992         Idx[1] = GEP.getOperand(1);
8993         Value *V = InsertNewInstBefore(
8994                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
8995         // V and GEP are both pointer types --> BitCast
8996         return new BitCastInst(V, GEP.getType());
8997       }
8998       
8999       // Transform things like:
9000       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9001       //   (where tmp = 8*tmp2) into:
9002       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9003       
9004       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9005         uint64_t ArrayEltSize =
9006             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9007         
9008         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9009         // allow either a mul, shift, or constant here.
9010         Value *NewIdx = 0;
9011         ConstantInt *Scale = 0;
9012         if (ArrayEltSize == 1) {
9013           NewIdx = GEP.getOperand(1);
9014           Scale = ConstantInt::get(NewIdx->getType(), 1);
9015         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9016           NewIdx = ConstantInt::get(CI->getType(), 1);
9017           Scale = CI;
9018         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9019           if (Inst->getOpcode() == Instruction::Shl &&
9020               isa<ConstantInt>(Inst->getOperand(1))) {
9021             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9022             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9023             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9024             NewIdx = Inst->getOperand(0);
9025           } else if (Inst->getOpcode() == Instruction::Mul &&
9026                      isa<ConstantInt>(Inst->getOperand(1))) {
9027             Scale = cast<ConstantInt>(Inst->getOperand(1));
9028             NewIdx = Inst->getOperand(0);
9029           }
9030         }
9031         
9032         // If the index will be to exactly the right offset with the scale taken
9033         // out, perform the transformation. Note, we don't know whether Scale is
9034         // signed or not. We'll use unsigned version of division/modulo
9035         // operation after making sure Scale doesn't have the sign bit set.
9036         if (Scale && Scale->getSExtValue() >= 0LL &&
9037             Scale->getZExtValue() % ArrayEltSize == 0) {
9038           Scale = ConstantInt::get(Scale->getType(),
9039                                    Scale->getZExtValue() / ArrayEltSize);
9040           if (Scale->getZExtValue() != 1) {
9041             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9042                                                        false /*ZExt*/);
9043             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9044             NewIdx = InsertNewInstBefore(Sc, GEP);
9045           }
9046
9047           // Insert the new GEP instruction.
9048           Value *Idx[2];
9049           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9050           Idx[1] = NewIdx;
9051           Instruction *NewGEP =
9052             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9053           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9054           // The NewGEP must be pointer typed, so must the old one -> BitCast
9055           return new BitCastInst(NewGEP, GEP.getType());
9056         }
9057       }
9058     }
9059   }
9060
9061   return 0;
9062 }
9063
9064 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9065   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9066   if (AI.isArrayAllocation())    // Check C != 1
9067     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9068       const Type *NewTy = 
9069         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9070       AllocationInst *New = 0;
9071
9072       // Create and insert the replacement instruction...
9073       if (isa<MallocInst>(AI))
9074         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9075       else {
9076         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9077         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9078       }
9079
9080       InsertNewInstBefore(New, AI);
9081
9082       // Scan to the end of the allocation instructions, to skip over a block of
9083       // allocas if possible...
9084       //
9085       BasicBlock::iterator It = New;
9086       while (isa<AllocationInst>(*It)) ++It;
9087
9088       // Now that I is pointing to the first non-allocation-inst in the block,
9089       // insert our getelementptr instruction...
9090       //
9091       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9092       Value *Idx[2];
9093       Idx[0] = NullIdx;
9094       Idx[1] = NullIdx;
9095       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9096                                        New->getName()+".sub", It);
9097
9098       // Now make everything use the getelementptr instead of the original
9099       // allocation.
9100       return ReplaceInstUsesWith(AI, V);
9101     } else if (isa<UndefValue>(AI.getArraySize())) {
9102       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9103     }
9104
9105   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9106   // Note that we only do this for alloca's, because malloc should allocate and
9107   // return a unique pointer, even for a zero byte allocation.
9108   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9109       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9110     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9111
9112   return 0;
9113 }
9114
9115 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9116   Value *Op = FI.getOperand(0);
9117
9118   // free undef -> unreachable.
9119   if (isa<UndefValue>(Op)) {
9120     // Insert a new store to null because we cannot modify the CFG here.
9121     new StoreInst(ConstantInt::getTrue(),
9122                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9123     return EraseInstFromFunction(FI);
9124   }
9125   
9126   // If we have 'free null' delete the instruction.  This can happen in stl code
9127   // when lots of inlining happens.
9128   if (isa<ConstantPointerNull>(Op))
9129     return EraseInstFromFunction(FI);
9130   
9131   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9132   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9133     FI.setOperand(0, CI->getOperand(0));
9134     return &FI;
9135   }
9136   
9137   // Change free (gep X, 0,0,0,0) into free(X)
9138   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9139     if (GEPI->hasAllZeroIndices()) {
9140       AddToWorkList(GEPI);
9141       FI.setOperand(0, GEPI->getOperand(0));
9142       return &FI;
9143     }
9144   }
9145   
9146   // Change free(malloc) into nothing, if the malloc has a single use.
9147   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9148     if (MI->hasOneUse()) {
9149       EraseInstFromFunction(FI);
9150       return EraseInstFromFunction(*MI);
9151     }
9152
9153   return 0;
9154 }
9155
9156
9157 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9158 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9159                                         const TargetData *TD) {
9160   User *CI = cast<User>(LI.getOperand(0));
9161   Value *CastOp = CI->getOperand(0);
9162
9163   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9164     // Instead of loading constant c string, use corresponding integer value
9165     // directly if string length is small enough.
9166     const std::string &Str = CE->getOperand(0)->getStringValue();
9167     if (!Str.empty()) {
9168       unsigned len = Str.length();
9169       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9170       unsigned numBits = Ty->getPrimitiveSizeInBits();
9171       // Replace LI with immediate integer store.
9172       if ((numBits >> 3) == len + 1) {
9173         APInt StrVal(numBits, 0);
9174         APInt SingleChar(numBits, 0);
9175         if (TD->isLittleEndian()) {
9176           for (signed i = len-1; i >= 0; i--) {
9177             SingleChar = (uint64_t) Str[i];
9178             StrVal = (StrVal << 8) | SingleChar;
9179           }
9180         } else {
9181           for (unsigned i = 0; i < len; i++) {
9182             SingleChar = (uint64_t) Str[i];
9183                 StrVal = (StrVal << 8) | SingleChar;
9184           }
9185           // Append NULL at the end.
9186           SingleChar = 0;
9187           StrVal = (StrVal << 8) | SingleChar;
9188         }
9189         Value *NL = ConstantInt::get(StrVal);
9190         return IC.ReplaceInstUsesWith(LI, NL);
9191       }
9192     }
9193   }
9194
9195   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9196   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9197     const Type *SrcPTy = SrcTy->getElementType();
9198
9199     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9200          isa<VectorType>(DestPTy)) {
9201       // If the source is an array, the code below will not succeed.  Check to
9202       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9203       // constants.
9204       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9205         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9206           if (ASrcTy->getNumElements() != 0) {
9207             Value *Idxs[2];
9208             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9209             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9210             SrcTy = cast<PointerType>(CastOp->getType());
9211             SrcPTy = SrcTy->getElementType();
9212           }
9213
9214       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9215             isa<VectorType>(SrcPTy)) &&
9216           // Do not allow turning this into a load of an integer, which is then
9217           // casted to a pointer, this pessimizes pointer analysis a lot.
9218           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9219           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9220                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9221
9222         // Okay, we are casting from one integer or pointer type to another of
9223         // the same size.  Instead of casting the pointer before the load, cast
9224         // the result of the loaded value.
9225         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9226                                                              CI->getName(),
9227                                                          LI.isVolatile()),LI);
9228         // Now cast the result of the load.
9229         return new BitCastInst(NewLoad, LI.getType());
9230       }
9231     }
9232   }
9233   return 0;
9234 }
9235
9236 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9237 /// from this value cannot trap.  If it is not obviously safe to load from the
9238 /// specified pointer, we do a quick local scan of the basic block containing
9239 /// ScanFrom, to determine if the address is already accessed.
9240 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9241   // If it is an alloca it is always safe to load from.
9242   if (isa<AllocaInst>(V)) return true;
9243
9244   // If it is a global variable it is mostly safe to load from.
9245   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9246     // Don't try to evaluate aliases.  External weak GV can be null.
9247     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9248
9249   // Otherwise, be a little bit agressive by scanning the local block where we
9250   // want to check to see if the pointer is already being loaded or stored
9251   // from/to.  If so, the previous load or store would have already trapped,
9252   // so there is no harm doing an extra load (also, CSE will later eliminate
9253   // the load entirely).
9254   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9255
9256   while (BBI != E) {
9257     --BBI;
9258
9259     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9260       if (LI->getOperand(0) == V) return true;
9261     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9262       if (SI->getOperand(1) == V) return true;
9263
9264   }
9265   return false;
9266 }
9267
9268 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9269 /// until we find the underlying object a pointer is referring to or something
9270 /// we don't understand.  Note that the returned pointer may be offset from the
9271 /// input, because we ignore GEP indices.
9272 static Value *GetUnderlyingObject(Value *Ptr) {
9273   while (1) {
9274     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9275       if (CE->getOpcode() == Instruction::BitCast ||
9276           CE->getOpcode() == Instruction::GetElementPtr)
9277         Ptr = CE->getOperand(0);
9278       else
9279         return Ptr;
9280     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9281       Ptr = BCI->getOperand(0);
9282     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9283       Ptr = GEP->getOperand(0);
9284     } else {
9285       return Ptr;
9286     }
9287   }
9288 }
9289
9290 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9291   Value *Op = LI.getOperand(0);
9292
9293   // Attempt to improve the alignment.
9294   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9295   if (KnownAlign > LI.getAlignment())
9296     LI.setAlignment(KnownAlign);
9297
9298   // load (cast X) --> cast (load X) iff safe
9299   if (isa<CastInst>(Op))
9300     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9301       return Res;
9302
9303   // None of the following transforms are legal for volatile loads.
9304   if (LI.isVolatile()) return 0;
9305   
9306   if (&LI.getParent()->front() != &LI) {
9307     BasicBlock::iterator BBI = &LI; --BBI;
9308     // If the instruction immediately before this is a store to the same
9309     // address, do a simple form of store->load forwarding.
9310     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9311       if (SI->getOperand(1) == LI.getOperand(0))
9312         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9313     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9314       if (LIB->getOperand(0) == LI.getOperand(0))
9315         return ReplaceInstUsesWith(LI, LIB);
9316   }
9317
9318   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
9319     if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
9320       // Insert a new store to null instruction before the load to indicate
9321       // that this code is not reachable.  We do this instead of inserting
9322       // an unreachable instruction directly because we cannot modify the
9323       // CFG.
9324       new StoreInst(UndefValue::get(LI.getType()),
9325                     Constant::getNullValue(Op->getType()), &LI);
9326       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9327     }
9328
9329   if (Constant *C = dyn_cast<Constant>(Op)) {
9330     // load null/undef -> undef
9331     if ((C->isNullValue() || isa<UndefValue>(C))) {
9332       // Insert a new store to null instruction before the load to indicate that
9333       // this code is not reachable.  We do this instead of inserting an
9334       // unreachable instruction directly because we cannot modify the CFG.
9335       new StoreInst(UndefValue::get(LI.getType()),
9336                     Constant::getNullValue(Op->getType()), &LI);
9337       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9338     }
9339
9340     // Instcombine load (constant global) into the value loaded.
9341     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9342       if (GV->isConstant() && !GV->isDeclaration())
9343         return ReplaceInstUsesWith(LI, GV->getInitializer());
9344
9345     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9346     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9347       if (CE->getOpcode() == Instruction::GetElementPtr) {
9348         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9349           if (GV->isConstant() && !GV->isDeclaration())
9350             if (Constant *V = 
9351                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9352               return ReplaceInstUsesWith(LI, V);
9353         if (CE->getOperand(0)->isNullValue()) {
9354           // Insert a new store to null instruction before the load to indicate
9355           // that this code is not reachable.  We do this instead of inserting
9356           // an unreachable instruction directly because we cannot modify the
9357           // CFG.
9358           new StoreInst(UndefValue::get(LI.getType()),
9359                         Constant::getNullValue(Op->getType()), &LI);
9360           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9361         }
9362
9363       } else if (CE->isCast()) {
9364         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9365           return Res;
9366       }
9367   }
9368     
9369   // If this load comes from anywhere in a constant global, and if the global
9370   // is all undef or zero, we know what it loads.
9371   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9372     if (GV->isConstant() && GV->hasInitializer()) {
9373       if (GV->getInitializer()->isNullValue())
9374         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9375       else if (isa<UndefValue>(GV->getInitializer()))
9376         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9377     }
9378   }
9379
9380   if (Op->hasOneUse()) {
9381     // Change select and PHI nodes to select values instead of addresses: this
9382     // helps alias analysis out a lot, allows many others simplifications, and
9383     // exposes redundancy in the code.
9384     //
9385     // Note that we cannot do the transformation unless we know that the
9386     // introduced loads cannot trap!  Something like this is valid as long as
9387     // the condition is always false: load (select bool %C, int* null, int* %G),
9388     // but it would not be valid if we transformed it to load from null
9389     // unconditionally.
9390     //
9391     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9392       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9393       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9394           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9395         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9396                                      SI->getOperand(1)->getName()+".val"), LI);
9397         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9398                                      SI->getOperand(2)->getName()+".val"), LI);
9399         return new SelectInst(SI->getCondition(), V1, V2);
9400       }
9401
9402       // load (select (cond, null, P)) -> load P
9403       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9404         if (C->isNullValue()) {
9405           LI.setOperand(0, SI->getOperand(2));
9406           return &LI;
9407         }
9408
9409       // load (select (cond, P, null)) -> load P
9410       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9411         if (C->isNullValue()) {
9412           LI.setOperand(0, SI->getOperand(1));
9413           return &LI;
9414         }
9415     }
9416   }
9417   return 0;
9418 }
9419
9420 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9421 /// when possible.
9422 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9423   User *CI = cast<User>(SI.getOperand(1));
9424   Value *CastOp = CI->getOperand(0);
9425
9426   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9427   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9428     const Type *SrcPTy = SrcTy->getElementType();
9429
9430     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9431       // If the source is an array, the code below will not succeed.  Check to
9432       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9433       // constants.
9434       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9435         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9436           if (ASrcTy->getNumElements() != 0) {
9437             Value* Idxs[2];
9438             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9439             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9440             SrcTy = cast<PointerType>(CastOp->getType());
9441             SrcPTy = SrcTy->getElementType();
9442           }
9443
9444       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9445           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9446                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9447
9448         // Okay, we are casting from one integer or pointer type to another of
9449         // the same size.  Instead of casting the pointer before 
9450         // the store, cast the value to be stored.
9451         Value *NewCast;
9452         Value *SIOp0 = SI.getOperand(0);
9453         Instruction::CastOps opcode = Instruction::BitCast;
9454         const Type* CastSrcTy = SIOp0->getType();
9455         const Type* CastDstTy = SrcPTy;
9456         if (isa<PointerType>(CastDstTy)) {
9457           if (CastSrcTy->isInteger())
9458             opcode = Instruction::IntToPtr;
9459         } else if (isa<IntegerType>(CastDstTy)) {
9460           if (isa<PointerType>(SIOp0->getType()))
9461             opcode = Instruction::PtrToInt;
9462         }
9463         if (Constant *C = dyn_cast<Constant>(SIOp0))
9464           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9465         else
9466           NewCast = IC.InsertNewInstBefore(
9467             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9468             SI);
9469         return new StoreInst(NewCast, CastOp);
9470       }
9471     }
9472   }
9473   return 0;
9474 }
9475
9476 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9477   Value *Val = SI.getOperand(0);
9478   Value *Ptr = SI.getOperand(1);
9479
9480   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9481     EraseInstFromFunction(SI);
9482     ++NumCombined;
9483     return 0;
9484   }
9485   
9486   // If the RHS is an alloca with a single use, zapify the store, making the
9487   // alloca dead.
9488   if (Ptr->hasOneUse()) {
9489     if (isa<AllocaInst>(Ptr)) {
9490       EraseInstFromFunction(SI);
9491       ++NumCombined;
9492       return 0;
9493     }
9494     
9495     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9496       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9497           GEP->getOperand(0)->hasOneUse()) {
9498         EraseInstFromFunction(SI);
9499         ++NumCombined;
9500         return 0;
9501       }
9502   }
9503
9504   // Attempt to improve the alignment.
9505   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9506   if (KnownAlign > SI.getAlignment())
9507     SI.setAlignment(KnownAlign);
9508
9509   // Do really simple DSE, to catch cases where there are several consequtive
9510   // stores to the same location, separated by a few arithmetic operations. This
9511   // situation often occurs with bitfield accesses.
9512   BasicBlock::iterator BBI = &SI;
9513   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9514        --ScanInsts) {
9515     --BBI;
9516     
9517     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9518       // Prev store isn't volatile, and stores to the same location?
9519       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9520         ++NumDeadStore;
9521         ++BBI;
9522         EraseInstFromFunction(*PrevSI);
9523         continue;
9524       }
9525       break;
9526     }
9527     
9528     // If this is a load, we have to stop.  However, if the loaded value is from
9529     // the pointer we're loading and is producing the pointer we're storing,
9530     // then *this* store is dead (X = load P; store X -> P).
9531     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9532       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
9533         EraseInstFromFunction(SI);
9534         ++NumCombined;
9535         return 0;
9536       }
9537       // Otherwise, this is a load from some other location.  Stores before it
9538       // may not be dead.
9539       break;
9540     }
9541     
9542     // Don't skip over loads or things that can modify memory.
9543     if (BBI->mayWriteToMemory())
9544       break;
9545   }
9546   
9547   
9548   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9549
9550   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9551   if (isa<ConstantPointerNull>(Ptr)) {
9552     if (!isa<UndefValue>(Val)) {
9553       SI.setOperand(0, UndefValue::get(Val->getType()));
9554       if (Instruction *U = dyn_cast<Instruction>(Val))
9555         AddToWorkList(U);  // Dropped a use.
9556       ++NumCombined;
9557     }
9558     return 0;  // Do not modify these!
9559   }
9560
9561   // store undef, Ptr -> noop
9562   if (isa<UndefValue>(Val)) {
9563     EraseInstFromFunction(SI);
9564     ++NumCombined;
9565     return 0;
9566   }
9567
9568   // If the pointer destination is a cast, see if we can fold the cast into the
9569   // source instead.
9570   if (isa<CastInst>(Ptr))
9571     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9572       return Res;
9573   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9574     if (CE->isCast())
9575       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9576         return Res;
9577
9578   
9579   // If this store is the last instruction in the basic block, and if the block
9580   // ends with an unconditional branch, try to move it to the successor block.
9581   BBI = &SI; ++BBI;
9582   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9583     if (BI->isUnconditional())
9584       if (SimplifyStoreAtEndOfBlock(SI))
9585         return 0;  // xform done!
9586   
9587   return 0;
9588 }
9589
9590 /// SimplifyStoreAtEndOfBlock - Turn things like:
9591 ///   if () { *P = v1; } else { *P = v2 }
9592 /// into a phi node with a store in the successor.
9593 ///
9594 /// Simplify things like:
9595 ///   *P = v1; if () { *P = v2; }
9596 /// into a phi node with a store in the successor.
9597 ///
9598 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9599   BasicBlock *StoreBB = SI.getParent();
9600   
9601   // Check to see if the successor block has exactly two incoming edges.  If
9602   // so, see if the other predecessor contains a store to the same location.
9603   // if so, insert a PHI node (if needed) and move the stores down.
9604   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9605   
9606   // Determine whether Dest has exactly two predecessors and, if so, compute
9607   // the other predecessor.
9608   pred_iterator PI = pred_begin(DestBB);
9609   BasicBlock *OtherBB = 0;
9610   if (*PI != StoreBB)
9611     OtherBB = *PI;
9612   ++PI;
9613   if (PI == pred_end(DestBB))
9614     return false;
9615   
9616   if (*PI != StoreBB) {
9617     if (OtherBB)
9618       return false;
9619     OtherBB = *PI;
9620   }
9621   if (++PI != pred_end(DestBB))
9622     return false;
9623   
9624   
9625   // Verify that the other block ends in a branch and is not otherwise empty.
9626   BasicBlock::iterator BBI = OtherBB->getTerminator();
9627   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9628   if (!OtherBr || BBI == OtherBB->begin())
9629     return false;
9630   
9631   // If the other block ends in an unconditional branch, check for the 'if then
9632   // else' case.  there is an instruction before the branch.
9633   StoreInst *OtherStore = 0;
9634   if (OtherBr->isUnconditional()) {
9635     // If this isn't a store, or isn't a store to the same location, bail out.
9636     --BBI;
9637     OtherStore = dyn_cast<StoreInst>(BBI);
9638     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9639       return false;
9640   } else {
9641     // Otherwise, the other block ended with a conditional branch. If one of the
9642     // destinations is StoreBB, then we have the if/then case.
9643     if (OtherBr->getSuccessor(0) != StoreBB && 
9644         OtherBr->getSuccessor(1) != StoreBB)
9645       return false;
9646     
9647     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9648     // if/then triangle.  See if there is a store to the same ptr as SI that
9649     // lives in OtherBB.
9650     for (;; --BBI) {
9651       // Check to see if we find the matching store.
9652       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9653         if (OtherStore->getOperand(1) != SI.getOperand(1))
9654           return false;
9655         break;
9656       }
9657       // If we find something that may be using the stored value, or if we run
9658       // out of instructions, we can't do the xform.
9659       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9660           BBI == OtherBB->begin())
9661         return false;
9662     }
9663     
9664     // In order to eliminate the store in OtherBr, we have to
9665     // make sure nothing reads the stored value in StoreBB.
9666     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9667       // FIXME: This should really be AA driven.
9668       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9669         return false;
9670     }
9671   }
9672   
9673   // Insert a PHI node now if we need it.
9674   Value *MergedVal = OtherStore->getOperand(0);
9675   if (MergedVal != SI.getOperand(0)) {
9676     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9677     PN->reserveOperandSpace(2);
9678     PN->addIncoming(SI.getOperand(0), SI.getParent());
9679     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9680     MergedVal = InsertNewInstBefore(PN, DestBB->front());
9681   }
9682   
9683   // Advance to a place where it is safe to insert the new store and
9684   // insert it.
9685   BBI = DestBB->begin();
9686   while (isa<PHINode>(BBI)) ++BBI;
9687   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9688                                     OtherStore->isVolatile()), *BBI);
9689   
9690   // Nuke the old stores.
9691   EraseInstFromFunction(SI);
9692   EraseInstFromFunction(*OtherStore);
9693   ++NumCombined;
9694   return true;
9695 }
9696
9697
9698 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9699   // Change br (not X), label True, label False to: br X, label False, True
9700   Value *X = 0;
9701   BasicBlock *TrueDest;
9702   BasicBlock *FalseDest;
9703   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9704       !isa<Constant>(X)) {
9705     // Swap Destinations and condition...
9706     BI.setCondition(X);
9707     BI.setSuccessor(0, FalseDest);
9708     BI.setSuccessor(1, TrueDest);
9709     return &BI;
9710   }
9711
9712   // Cannonicalize fcmp_one -> fcmp_oeq
9713   FCmpInst::Predicate FPred; Value *Y;
9714   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
9715                              TrueDest, FalseDest)))
9716     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9717          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9718       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9719       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9720       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9721       NewSCC->takeName(I);
9722       // Swap Destinations and condition...
9723       BI.setCondition(NewSCC);
9724       BI.setSuccessor(0, FalseDest);
9725       BI.setSuccessor(1, TrueDest);
9726       RemoveFromWorkList(I);
9727       I->eraseFromParent();
9728       AddToWorkList(NewSCC);
9729       return &BI;
9730     }
9731
9732   // Cannonicalize icmp_ne -> icmp_eq
9733   ICmpInst::Predicate IPred;
9734   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9735                       TrueDest, FalseDest)))
9736     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
9737          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9738          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9739       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9740       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9741       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9742       NewSCC->takeName(I);
9743       // Swap Destinations and condition...
9744       BI.setCondition(NewSCC);
9745       BI.setSuccessor(0, FalseDest);
9746       BI.setSuccessor(1, TrueDest);
9747       RemoveFromWorkList(I);
9748       I->eraseFromParent();;
9749       AddToWorkList(NewSCC);
9750       return &BI;
9751     }
9752
9753   return 0;
9754 }
9755
9756 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9757   Value *Cond = SI.getCondition();
9758   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9759     if (I->getOpcode() == Instruction::Add)
9760       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9761         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9762         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9763           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9764                                                 AddRHS));
9765         SI.setOperand(0, I->getOperand(0));
9766         AddToWorkList(I);
9767         return &SI;
9768       }
9769   }
9770   return 0;
9771 }
9772
9773 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9774 /// is to leave as a vector operation.
9775 static bool CheapToScalarize(Value *V, bool isConstant) {
9776   if (isa<ConstantAggregateZero>(V)) 
9777     return true;
9778   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9779     if (isConstant) return true;
9780     // If all elts are the same, we can extract.
9781     Constant *Op0 = C->getOperand(0);
9782     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9783       if (C->getOperand(i) != Op0)
9784         return false;
9785     return true;
9786   }
9787   Instruction *I = dyn_cast<Instruction>(V);
9788   if (!I) return false;
9789   
9790   // Insert element gets simplified to the inserted element or is deleted if
9791   // this is constant idx extract element and its a constant idx insertelt.
9792   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9793       isa<ConstantInt>(I->getOperand(2)))
9794     return true;
9795   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9796     return true;
9797   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9798     if (BO->hasOneUse() &&
9799         (CheapToScalarize(BO->getOperand(0), isConstant) ||
9800          CheapToScalarize(BO->getOperand(1), isConstant)))
9801       return true;
9802   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9803     if (CI->hasOneUse() &&
9804         (CheapToScalarize(CI->getOperand(0), isConstant) ||
9805          CheapToScalarize(CI->getOperand(1), isConstant)))
9806       return true;
9807   
9808   return false;
9809 }
9810
9811 /// Read and decode a shufflevector mask.
9812 ///
9813 /// It turns undef elements into values that are larger than the number of
9814 /// elements in the input.
9815 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9816   unsigned NElts = SVI->getType()->getNumElements();
9817   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9818     return std::vector<unsigned>(NElts, 0);
9819   if (isa<UndefValue>(SVI->getOperand(2)))
9820     return std::vector<unsigned>(NElts, 2*NElts);
9821
9822   std::vector<unsigned> Result;
9823   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9824   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9825     if (isa<UndefValue>(CP->getOperand(i)))
9826       Result.push_back(NElts*2);  // undef -> 8
9827     else
9828       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9829   return Result;
9830 }
9831
9832 /// FindScalarElement - Given a vector and an element number, see if the scalar
9833 /// value is already around as a register, for example if it were inserted then
9834 /// extracted from the vector.
9835 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9836   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9837   const VectorType *PTy = cast<VectorType>(V->getType());
9838   unsigned Width = PTy->getNumElements();
9839   if (EltNo >= Width)  // Out of range access.
9840     return UndefValue::get(PTy->getElementType());
9841   
9842   if (isa<UndefValue>(V))
9843     return UndefValue::get(PTy->getElementType());
9844   else if (isa<ConstantAggregateZero>(V))
9845     return Constant::getNullValue(PTy->getElementType());
9846   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9847     return CP->getOperand(EltNo);
9848   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9849     // If this is an insert to a variable element, we don't know what it is.
9850     if (!isa<ConstantInt>(III->getOperand(2))) 
9851       return 0;
9852     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9853     
9854     // If this is an insert to the element we are looking for, return the
9855     // inserted value.
9856     if (EltNo == IIElt) 
9857       return III->getOperand(1);
9858     
9859     // Otherwise, the insertelement doesn't modify the value, recurse on its
9860     // vector input.
9861     return FindScalarElement(III->getOperand(0), EltNo);
9862   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9863     unsigned InEl = getShuffleMask(SVI)[EltNo];
9864     if (InEl < Width)
9865       return FindScalarElement(SVI->getOperand(0), InEl);
9866     else if (InEl < Width*2)
9867       return FindScalarElement(SVI->getOperand(1), InEl - Width);
9868     else
9869       return UndefValue::get(PTy->getElementType());
9870   }
9871   
9872   // Otherwise, we don't know.
9873   return 0;
9874 }
9875
9876 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9877
9878   // If vector val is undef, replace extract with scalar undef.
9879   if (isa<UndefValue>(EI.getOperand(0)))
9880     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9881
9882   // If vector val is constant 0, replace extract with scalar 0.
9883   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9884     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9885   
9886   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9887     // If vector val is constant with uniform operands, replace EI
9888     // with that operand
9889     Constant *op0 = C->getOperand(0);
9890     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9891       if (C->getOperand(i) != op0) {
9892         op0 = 0; 
9893         break;
9894       }
9895     if (op0)
9896       return ReplaceInstUsesWith(EI, op0);
9897   }
9898   
9899   // If extracting a specified index from the vector, see if we can recursively
9900   // find a previously computed scalar that was inserted into the vector.
9901   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9902     unsigned IndexVal = IdxC->getZExtValue();
9903     unsigned VectorWidth = 
9904       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9905       
9906     // If this is extracting an invalid index, turn this into undef, to avoid
9907     // crashing the code below.
9908     if (IndexVal >= VectorWidth)
9909       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9910     
9911     // This instruction only demands the single element from the input vector.
9912     // If the input vector has a single use, simplify it based on this use
9913     // property.
9914     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
9915       uint64_t UndefElts;
9916       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9917                                                 1 << IndexVal,
9918                                                 UndefElts)) {
9919         EI.setOperand(0, V);
9920         return &EI;
9921       }
9922     }
9923     
9924     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9925       return ReplaceInstUsesWith(EI, Elt);
9926     
9927     // If the this extractelement is directly using a bitcast from a vector of
9928     // the same number of elements, see if we can find the source element from
9929     // it.  In this case, we will end up needing to bitcast the scalars.
9930     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9931       if (const VectorType *VT = 
9932               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9933         if (VT->getNumElements() == VectorWidth)
9934           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9935             return new BitCastInst(Elt, EI.getType());
9936     }
9937   }
9938   
9939   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9940     if (I->hasOneUse()) {
9941       // Push extractelement into predecessor operation if legal and
9942       // profitable to do so
9943       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9944         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9945         if (CheapToScalarize(BO, isConstantElt)) {
9946           ExtractElementInst *newEI0 = 
9947             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9948                                    EI.getName()+".lhs");
9949           ExtractElementInst *newEI1 =
9950             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9951                                    EI.getName()+".rhs");
9952           InsertNewInstBefore(newEI0, EI);
9953           InsertNewInstBefore(newEI1, EI);
9954           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9955         }
9956       } else if (isa<LoadInst>(I)) {
9957         unsigned AS = 
9958           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
9959         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9960                                       PointerType::get(EI.getType(), AS), EI);
9961         GetElementPtrInst *GEP = 
9962           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9963         InsertNewInstBefore(GEP, EI);
9964         return new LoadInst(GEP);
9965       }
9966     }
9967     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9968       // Extracting the inserted element?
9969       if (IE->getOperand(2) == EI.getOperand(1))
9970         return ReplaceInstUsesWith(EI, IE->getOperand(1));
9971       // If the inserted and extracted elements are constants, they must not
9972       // be the same value, extract from the pre-inserted value instead.
9973       if (isa<Constant>(IE->getOperand(2)) &&
9974           isa<Constant>(EI.getOperand(1))) {
9975         AddUsesToWorkList(EI);
9976         EI.setOperand(0, IE->getOperand(0));
9977         return &EI;
9978       }
9979     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9980       // If this is extracting an element from a shufflevector, figure out where
9981       // it came from and extract from the appropriate input element instead.
9982       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9983         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9984         Value *Src;
9985         if (SrcIdx < SVI->getType()->getNumElements())
9986           Src = SVI->getOperand(0);
9987         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9988           SrcIdx -= SVI->getType()->getNumElements();
9989           Src = SVI->getOperand(1);
9990         } else {
9991           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9992         }
9993         return new ExtractElementInst(Src, SrcIdx);
9994       }
9995     }
9996   }
9997   return 0;
9998 }
9999
10000 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10001 /// elements from either LHS or RHS, return the shuffle mask and true. 
10002 /// Otherwise, return false.
10003 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10004                                          std::vector<Constant*> &Mask) {
10005   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10006          "Invalid CollectSingleShuffleElements");
10007   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10008
10009   if (isa<UndefValue>(V)) {
10010     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10011     return true;
10012   } else if (V == LHS) {
10013     for (unsigned i = 0; i != NumElts; ++i)
10014       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10015     return true;
10016   } else if (V == RHS) {
10017     for (unsigned i = 0; i != NumElts; ++i)
10018       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10019     return true;
10020   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10021     // If this is an insert of an extract from some other vector, include it.
10022     Value *VecOp    = IEI->getOperand(0);
10023     Value *ScalarOp = IEI->getOperand(1);
10024     Value *IdxOp    = IEI->getOperand(2);
10025     
10026     if (!isa<ConstantInt>(IdxOp))
10027       return false;
10028     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10029     
10030     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10031       // Okay, we can handle this if the vector we are insertinting into is
10032       // transitively ok.
10033       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10034         // If so, update the mask to reflect the inserted undef.
10035         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10036         return true;
10037       }      
10038     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10039       if (isa<ConstantInt>(EI->getOperand(1)) &&
10040           EI->getOperand(0)->getType() == V->getType()) {
10041         unsigned ExtractedIdx =
10042           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10043         
10044         // This must be extracting from either LHS or RHS.
10045         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10046           // Okay, we can handle this if the vector we are insertinting into is
10047           // transitively ok.
10048           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10049             // If so, update the mask to reflect the inserted value.
10050             if (EI->getOperand(0) == LHS) {
10051               Mask[InsertedIdx & (NumElts-1)] = 
10052                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10053             } else {
10054               assert(EI->getOperand(0) == RHS);
10055               Mask[InsertedIdx & (NumElts-1)] = 
10056                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10057               
10058             }
10059             return true;
10060           }
10061         }
10062       }
10063     }
10064   }
10065   // TODO: Handle shufflevector here!
10066   
10067   return false;
10068 }
10069
10070 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10071 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10072 /// that computes V and the LHS value of the shuffle.
10073 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10074                                      Value *&RHS) {
10075   assert(isa<VectorType>(V->getType()) && 
10076          (RHS == 0 || V->getType() == RHS->getType()) &&
10077          "Invalid shuffle!");
10078   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10079
10080   if (isa<UndefValue>(V)) {
10081     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10082     return V;
10083   } else if (isa<ConstantAggregateZero>(V)) {
10084     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10085     return V;
10086   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10087     // If this is an insert of an extract from some other vector, include it.
10088     Value *VecOp    = IEI->getOperand(0);
10089     Value *ScalarOp = IEI->getOperand(1);
10090     Value *IdxOp    = IEI->getOperand(2);
10091     
10092     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10093       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10094           EI->getOperand(0)->getType() == V->getType()) {
10095         unsigned ExtractedIdx =
10096           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10097         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10098         
10099         // Either the extracted from or inserted into vector must be RHSVec,
10100         // otherwise we'd end up with a shuffle of three inputs.
10101         if (EI->getOperand(0) == RHS || RHS == 0) {
10102           RHS = EI->getOperand(0);
10103           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10104           Mask[InsertedIdx & (NumElts-1)] = 
10105             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10106           return V;
10107         }
10108         
10109         if (VecOp == RHS) {
10110           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10111           // Everything but the extracted element is replaced with the RHS.
10112           for (unsigned i = 0; i != NumElts; ++i) {
10113             if (i != InsertedIdx)
10114               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10115           }
10116           return V;
10117         }
10118         
10119         // If this insertelement is a chain that comes from exactly these two
10120         // vectors, return the vector and the effective shuffle.
10121         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10122           return EI->getOperand(0);
10123         
10124       }
10125     }
10126   }
10127   // TODO: Handle shufflevector here!
10128   
10129   // Otherwise, can't do anything fancy.  Return an identity vector.
10130   for (unsigned i = 0; i != NumElts; ++i)
10131     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10132   return V;
10133 }
10134
10135 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10136   Value *VecOp    = IE.getOperand(0);
10137   Value *ScalarOp = IE.getOperand(1);
10138   Value *IdxOp    = IE.getOperand(2);
10139   
10140   // Inserting an undef or into an undefined place, remove this.
10141   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10142     ReplaceInstUsesWith(IE, VecOp);
10143   
10144   // If the inserted element was extracted from some other vector, and if the 
10145   // indexes are constant, try to turn this into a shufflevector operation.
10146   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10147     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10148         EI->getOperand(0)->getType() == IE.getType()) {
10149       unsigned NumVectorElts = IE.getType()->getNumElements();
10150       unsigned ExtractedIdx =
10151         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10152       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10153       
10154       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10155         return ReplaceInstUsesWith(IE, VecOp);
10156       
10157       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10158         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10159       
10160       // If we are extracting a value from a vector, then inserting it right
10161       // back into the same place, just use the input vector.
10162       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10163         return ReplaceInstUsesWith(IE, VecOp);      
10164       
10165       // We could theoretically do this for ANY input.  However, doing so could
10166       // turn chains of insertelement instructions into a chain of shufflevector
10167       // instructions, and right now we do not merge shufflevectors.  As such,
10168       // only do this in a situation where it is clear that there is benefit.
10169       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10170         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10171         // the values of VecOp, except then one read from EIOp0.
10172         // Build a new shuffle mask.
10173         std::vector<Constant*> Mask;
10174         if (isa<UndefValue>(VecOp))
10175           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10176         else {
10177           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10178           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10179                                                        NumVectorElts));
10180         } 
10181         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10182         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10183                                      ConstantVector::get(Mask));
10184       }
10185       
10186       // If this insertelement isn't used by some other insertelement, turn it
10187       // (and any insertelements it points to), into one big shuffle.
10188       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10189         std::vector<Constant*> Mask;
10190         Value *RHS = 0;
10191         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10192         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10193         // We now have a shuffle of LHS, RHS, Mask.
10194         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10195       }
10196     }
10197   }
10198
10199   return 0;
10200 }
10201
10202
10203 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10204   Value *LHS = SVI.getOperand(0);
10205   Value *RHS = SVI.getOperand(1);
10206   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10207
10208   bool MadeChange = false;
10209   
10210   // Undefined shuffle mask -> undefined value.
10211   if (isa<UndefValue>(SVI.getOperand(2)))
10212     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10213   
10214   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10215   // the undef, change them to undefs.
10216   if (isa<UndefValue>(SVI.getOperand(1))) {
10217     // Scan to see if there are any references to the RHS.  If so, replace them
10218     // with undef element refs and set MadeChange to true.
10219     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10220       if (Mask[i] >= e && Mask[i] != 2*e) {
10221         Mask[i] = 2*e;
10222         MadeChange = true;
10223       }
10224     }
10225     
10226     if (MadeChange) {
10227       // Remap any references to RHS to use LHS.
10228       std::vector<Constant*> Elts;
10229       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10230         if (Mask[i] == 2*e)
10231           Elts.push_back(UndefValue::get(Type::Int32Ty));
10232         else
10233           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10234       }
10235       SVI.setOperand(2, ConstantVector::get(Elts));
10236     }
10237   }
10238   
10239   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10240   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10241   if (LHS == RHS || isa<UndefValue>(LHS)) {
10242     if (isa<UndefValue>(LHS) && LHS == RHS) {
10243       // shuffle(undef,undef,mask) -> undef.
10244       return ReplaceInstUsesWith(SVI, LHS);
10245     }
10246     
10247     // Remap any references to RHS to use LHS.
10248     std::vector<Constant*> Elts;
10249     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10250       if (Mask[i] >= 2*e)
10251         Elts.push_back(UndefValue::get(Type::Int32Ty));
10252       else {
10253         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10254             (Mask[i] <  e && isa<UndefValue>(LHS)))
10255           Mask[i] = 2*e;     // Turn into undef.
10256         else
10257           Mask[i] &= (e-1);  // Force to LHS.
10258         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10259       }
10260     }
10261     SVI.setOperand(0, SVI.getOperand(1));
10262     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10263     SVI.setOperand(2, ConstantVector::get(Elts));
10264     LHS = SVI.getOperand(0);
10265     RHS = SVI.getOperand(1);
10266     MadeChange = true;
10267   }
10268   
10269   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10270   bool isLHSID = true, isRHSID = true;
10271     
10272   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10273     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10274     // Is this an identity shuffle of the LHS value?
10275     isLHSID &= (Mask[i] == i);
10276       
10277     // Is this an identity shuffle of the RHS value?
10278     isRHSID &= (Mask[i]-e == i);
10279   }
10280
10281   // Eliminate identity shuffles.
10282   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10283   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10284   
10285   // If the LHS is a shufflevector itself, see if we can combine it with this
10286   // one without producing an unusual shuffle.  Here we are really conservative:
10287   // we are absolutely afraid of producing a shuffle mask not in the input
10288   // program, because the code gen may not be smart enough to turn a merged
10289   // shuffle into two specific shuffles: it may produce worse code.  As such,
10290   // we only merge two shuffles if the result is one of the two input shuffle
10291   // masks.  In this case, merging the shuffles just removes one instruction,
10292   // which we know is safe.  This is good for things like turning:
10293   // (splat(splat)) -> splat.
10294   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10295     if (isa<UndefValue>(RHS)) {
10296       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10297
10298       std::vector<unsigned> NewMask;
10299       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10300         if (Mask[i] >= 2*e)
10301           NewMask.push_back(2*e);
10302         else
10303           NewMask.push_back(LHSMask[Mask[i]]);
10304       
10305       // If the result mask is equal to the src shuffle or this shuffle mask, do
10306       // the replacement.
10307       if (NewMask == LHSMask || NewMask == Mask) {
10308         std::vector<Constant*> Elts;
10309         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10310           if (NewMask[i] >= e*2) {
10311             Elts.push_back(UndefValue::get(Type::Int32Ty));
10312           } else {
10313             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10314           }
10315         }
10316         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10317                                      LHSSVI->getOperand(1),
10318                                      ConstantVector::get(Elts));
10319       }
10320     }
10321   }
10322
10323   return MadeChange ? &SVI : 0;
10324 }
10325
10326
10327
10328
10329 /// TryToSinkInstruction - Try to move the specified instruction from its
10330 /// current block into the beginning of DestBlock, which can only happen if it's
10331 /// safe to move the instruction past all of the instructions between it and the
10332 /// end of its block.
10333 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10334   assert(I->hasOneUse() && "Invariants didn't hold!");
10335
10336   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10337   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10338
10339   // Do not sink alloca instructions out of the entry block.
10340   if (isa<AllocaInst>(I) && I->getParent() ==
10341         &DestBlock->getParent()->getEntryBlock())
10342     return false;
10343
10344   // We can only sink load instructions if there is nothing between the load and
10345   // the end of block that could change the value.
10346   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10347     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10348          Scan != E; ++Scan)
10349       if (Scan->mayWriteToMemory())
10350         return false;
10351   }
10352
10353   BasicBlock::iterator InsertPos = DestBlock->begin();
10354   while (isa<PHINode>(InsertPos)) ++InsertPos;
10355
10356   I->moveBefore(InsertPos);
10357   ++NumSunkInst;
10358   return true;
10359 }
10360
10361
10362 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10363 /// all reachable code to the worklist.
10364 ///
10365 /// This has a couple of tricks to make the code faster and more powerful.  In
10366 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10367 /// them to the worklist (this significantly speeds up instcombine on code where
10368 /// many instructions are dead or constant).  Additionally, if we find a branch
10369 /// whose condition is a known constant, we only visit the reachable successors.
10370 ///
10371 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10372                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10373                                        InstCombiner &IC,
10374                                        const TargetData *TD) {
10375   std::vector<BasicBlock*> Worklist;
10376   Worklist.push_back(BB);
10377
10378   while (!Worklist.empty()) {
10379     BB = Worklist.back();
10380     Worklist.pop_back();
10381     
10382     // We have now visited this block!  If we've already been here, ignore it.
10383     if (!Visited.insert(BB)) continue;
10384     
10385     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10386       Instruction *Inst = BBI++;
10387       
10388       // DCE instruction if trivially dead.
10389       if (isInstructionTriviallyDead(Inst)) {
10390         ++NumDeadInst;
10391         DOUT << "IC: DCE: " << *Inst;
10392         Inst->eraseFromParent();
10393         continue;
10394       }
10395       
10396       // ConstantProp instruction if trivially constant.
10397       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10398         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10399         Inst->replaceAllUsesWith(C);
10400         ++NumConstProp;
10401         Inst->eraseFromParent();
10402         continue;
10403       }
10404      
10405       IC.AddToWorkList(Inst);
10406     }
10407
10408     // Recursively visit successors.  If this is a branch or switch on a
10409     // constant, only visit the reachable successor.
10410     TerminatorInst *TI = BB->getTerminator();
10411     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10412       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10413         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10414         Worklist.push_back(BI->getSuccessor(!CondVal));
10415         continue;
10416       }
10417     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10418       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10419         // See if this is an explicit destination.
10420         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10421           if (SI->getCaseValue(i) == Cond) {
10422             Worklist.push_back(SI->getSuccessor(i));
10423             continue;
10424           }
10425         
10426         // Otherwise it is the default destination.
10427         Worklist.push_back(SI->getSuccessor(0));
10428         continue;
10429       }
10430     }
10431     
10432     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10433       Worklist.push_back(TI->getSuccessor(i));
10434   }
10435 }
10436
10437 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10438   bool Changed = false;
10439   TD = &getAnalysis<TargetData>();
10440   
10441   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10442              << F.getNameStr() << "\n");
10443
10444   {
10445     // Do a depth-first traversal of the function, populate the worklist with
10446     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10447     // track of which blocks we visit.
10448     SmallPtrSet<BasicBlock*, 64> Visited;
10449     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10450
10451     // Do a quick scan over the function.  If we find any blocks that are
10452     // unreachable, remove any instructions inside of them.  This prevents
10453     // the instcombine code from having to deal with some bad special cases.
10454     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10455       if (!Visited.count(BB)) {
10456         Instruction *Term = BB->getTerminator();
10457         while (Term != BB->begin()) {   // Remove instrs bottom-up
10458           BasicBlock::iterator I = Term; --I;
10459
10460           DOUT << "IC: DCE: " << *I;
10461           ++NumDeadInst;
10462
10463           if (!I->use_empty())
10464             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10465           I->eraseFromParent();
10466         }
10467       }
10468   }
10469
10470   while (!Worklist.empty()) {
10471     Instruction *I = RemoveOneFromWorkList();
10472     if (I == 0) continue;  // skip null values.
10473
10474     // Check to see if we can DCE the instruction.
10475     if (isInstructionTriviallyDead(I)) {
10476       // Add operands to the worklist.
10477       if (I->getNumOperands() < 4)
10478         AddUsesToWorkList(*I);
10479       ++NumDeadInst;
10480
10481       DOUT << "IC: DCE: " << *I;
10482
10483       I->eraseFromParent();
10484       RemoveFromWorkList(I);
10485       continue;
10486     }
10487
10488     // Instruction isn't dead, see if we can constant propagate it.
10489     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10490       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10491
10492       // Add operands to the worklist.
10493       AddUsesToWorkList(*I);
10494       ReplaceInstUsesWith(*I, C);
10495
10496       ++NumConstProp;
10497       I->eraseFromParent();
10498       RemoveFromWorkList(I);
10499       continue;
10500     }
10501
10502     // See if we can trivially sink this instruction to a successor basic block.
10503     if (I->hasOneUse()) {
10504       BasicBlock *BB = I->getParent();
10505       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10506       if (UserParent != BB) {
10507         bool UserIsSuccessor = false;
10508         // See if the user is one of our successors.
10509         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10510           if (*SI == UserParent) {
10511             UserIsSuccessor = true;
10512             break;
10513           }
10514
10515         // If the user is one of our immediate successors, and if that successor
10516         // only has us as a predecessors (we'd have to split the critical edge
10517         // otherwise), we can keep going.
10518         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10519             next(pred_begin(UserParent)) == pred_end(UserParent))
10520           // Okay, the CFG is simple enough, try to sink this instruction.
10521           Changed |= TryToSinkInstruction(I, UserParent);
10522       }
10523     }
10524
10525     // Now that we have an instruction, try combining it to simplify it...
10526 #ifndef NDEBUG
10527     std::string OrigI;
10528 #endif
10529     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10530     if (Instruction *Result = visit(*I)) {
10531       ++NumCombined;
10532       // Should we replace the old instruction with a new one?
10533       if (Result != I) {
10534         DOUT << "IC: Old = " << *I
10535              << "    New = " << *Result;
10536
10537         // Everything uses the new instruction now.
10538         I->replaceAllUsesWith(Result);
10539
10540         // Push the new instruction and any users onto the worklist.
10541         AddToWorkList(Result);
10542         AddUsersToWorkList(*Result);
10543
10544         // Move the name to the new instruction first.
10545         Result->takeName(I);
10546
10547         // Insert the new instruction into the basic block...
10548         BasicBlock *InstParent = I->getParent();
10549         BasicBlock::iterator InsertPos = I;
10550
10551         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10552           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10553             ++InsertPos;
10554
10555         InstParent->getInstList().insert(InsertPos, Result);
10556
10557         // Make sure that we reprocess all operands now that we reduced their
10558         // use counts.
10559         AddUsesToWorkList(*I);
10560
10561         // Instructions can end up on the worklist more than once.  Make sure
10562         // we do not process an instruction that has been deleted.
10563         RemoveFromWorkList(I);
10564
10565         // Erase the old instruction.
10566         InstParent->getInstList().erase(I);
10567       } else {
10568 #ifndef NDEBUG
10569         DOUT << "IC: Mod = " << OrigI
10570              << "    New = " << *I;
10571 #endif
10572
10573         // If the instruction was modified, it's possible that it is now dead.
10574         // if so, remove it.
10575         if (isInstructionTriviallyDead(I)) {
10576           // Make sure we process all operands now that we are reducing their
10577           // use counts.
10578           AddUsesToWorkList(*I);
10579
10580           // Instructions may end up in the worklist more than once.  Erase all
10581           // occurrences of this instruction.
10582           RemoveFromWorkList(I);
10583           I->eraseFromParent();
10584         } else {
10585           AddToWorkList(I);
10586           AddUsersToWorkList(*I);
10587         }
10588       }
10589       Changed = true;
10590     }
10591   }
10592
10593   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10594     
10595   // Do an explicit clear, this shrinks the map if needed.
10596   WorklistMap.clear();
10597   return Changed;
10598 }
10599
10600
10601 bool InstCombiner::runOnFunction(Function &F) {
10602   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10603   
10604   bool EverMadeChange = false;
10605
10606   // Iterate while there is work to do.
10607   unsigned Iteration = 0;
10608   while (DoOneIteration(F, Iteration++)) 
10609     EverMadeChange = true;
10610   return EverMadeChange;
10611 }
10612
10613 FunctionPass *llvm::createInstructionCombiningPass() {
10614   return new InstCombiner();
10615 }
10616