Optimize alignment of loads and stores.
[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/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/ADT/DenseMap.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <sstream>
60 using namespace llvm;
61 using namespace llvm::PatternMatch;
62
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
68
69 namespace {
70   class VISIBILITY_HIDDEN InstCombiner
71     : public FunctionPass,
72       public InstVisitor<InstCombiner, Instruction*> {
73     // Worklist of all of the instructions that need to be simplified.
74     std::vector<Instruction*> Worklist;
75     DenseMap<Instruction*, unsigned> WorklistMap;
76     TargetData *TD;
77     bool MustPreserveLCSSA;
78   public:
79     static char ID; // Pass identification, replacement for typeid
80     InstCombiner() : FunctionPass((intptr_t)&ID) {}
81
82     /// AddToWorkList - Add the specified instruction to the worklist if it
83     /// isn't already in it.
84     void AddToWorkList(Instruction *I) {
85       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
86         Worklist.push_back(I);
87     }
88     
89     // RemoveFromWorkList - remove I from the worklist if it exists.
90     void RemoveFromWorkList(Instruction *I) {
91       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
92       if (It == WorklistMap.end()) return; // Not in worklist.
93       
94       // Don't bother moving everything down, just null out the slot.
95       Worklist[It->second] = 0;
96       
97       WorklistMap.erase(It);
98     }
99     
100     Instruction *RemoveOneFromWorkList() {
101       Instruction *I = Worklist.back();
102       Worklist.pop_back();
103       WorklistMap.erase(I);
104       return I;
105     }
106
107     
108     /// AddUsersToWorkList - When an instruction is simplified, add all users of
109     /// the instruction to the work lists because they might get more simplified
110     /// now.
111     ///
112     void AddUsersToWorkList(Value &I) {
113       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
114            UI != UE; ++UI)
115         AddToWorkList(cast<Instruction>(*UI));
116     }
117
118     /// AddUsesToWorkList - When an instruction is simplified, add operands to
119     /// the work lists because they might get more simplified now.
120     ///
121     void AddUsesToWorkList(Instruction &I) {
122       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
123         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
124           AddToWorkList(Op);
125     }
126     
127     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
128     /// dead.  Add all of its operands to the worklist, turning them into
129     /// undef's to reduce the number of uses of those instructions.
130     ///
131     /// Return the specified operand before it is turned into an undef.
132     ///
133     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
134       Value *R = I.getOperand(op);
135       
136       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
137         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
138           AddToWorkList(Op);
139           // Set the operand to undef to drop the use.
140           I.setOperand(i, UndefValue::get(Op->getType()));
141         }
142       
143       return R;
144     }
145
146   public:
147     virtual bool runOnFunction(Function &F);
148     
149     bool DoOneIteration(Function &F, unsigned ItNum);
150
151     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152       AU.addRequired<TargetData>();
153       AU.addPreservedID(LCSSAID);
154       AU.setPreservesCFG();
155     }
156
157     TargetData &getTargetData() const { return *TD; }
158
159     // Visitation implementation - Implement instruction combining for different
160     // instruction types.  The semantics are as follows:
161     // Return Value:
162     //    null        - No change was made
163     //     I          - Change was made, I is still valid, I may be dead though
164     //   otherwise    - Change was made, replace I with returned instruction
165     //
166     Instruction *visitAdd(BinaryOperator &I);
167     Instruction *visitSub(BinaryOperator &I);
168     Instruction *visitMul(BinaryOperator &I);
169     Instruction *visitURem(BinaryOperator &I);
170     Instruction *visitSRem(BinaryOperator &I);
171     Instruction *visitFRem(BinaryOperator &I);
172     Instruction *commonRemTransforms(BinaryOperator &I);
173     Instruction *commonIRemTransforms(BinaryOperator &I);
174     Instruction *commonDivTransforms(BinaryOperator &I);
175     Instruction *commonIDivTransforms(BinaryOperator &I);
176     Instruction *visitUDiv(BinaryOperator &I);
177     Instruction *visitSDiv(BinaryOperator &I);
178     Instruction *visitFDiv(BinaryOperator &I);
179     Instruction *visitAnd(BinaryOperator &I);
180     Instruction *visitOr (BinaryOperator &I);
181     Instruction *visitXor(BinaryOperator &I);
182     Instruction *visitShl(BinaryOperator &I);
183     Instruction *visitAShr(BinaryOperator &I);
184     Instruction *visitLShr(BinaryOperator &I);
185     Instruction *commonShiftTransforms(BinaryOperator &I);
186     Instruction *visitFCmpInst(FCmpInst &I);
187     Instruction *visitICmpInst(ICmpInst &I);
188     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
189     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
190                                                 Instruction *LHS,
191                                                 ConstantInt *RHS);
192     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
193                                 ConstantInt *DivRHS);
194
195     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
196                              ICmpInst::Predicate Cond, Instruction &I);
197     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
198                                      BinaryOperator &I);
199     Instruction *commonCastTransforms(CastInst &CI);
200     Instruction *commonIntCastTransforms(CastInst &CI);
201     Instruction *commonPointerCastTransforms(CastInst &CI);
202     Instruction *visitTrunc(TruncInst &CI);
203     Instruction *visitZExt(ZExtInst &CI);
204     Instruction *visitSExt(SExtInst &CI);
205     Instruction *visitFPTrunc(CastInst &CI);
206     Instruction *visitFPExt(CastInst &CI);
207     Instruction *visitFPToUI(CastInst &CI);
208     Instruction *visitFPToSI(CastInst &CI);
209     Instruction *visitUIToFP(CastInst &CI);
210     Instruction *visitSIToFP(CastInst &CI);
211     Instruction *visitPtrToInt(CastInst &CI);
212     Instruction *visitIntToPtr(CastInst &CI);
213     Instruction *visitBitCast(BitCastInst &CI);
214     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
215                                 Instruction *FI);
216     Instruction *visitSelectInst(SelectInst &CI);
217     Instruction *visitCallInst(CallInst &CI);
218     Instruction *visitInvokeInst(InvokeInst &II);
219     Instruction *visitPHINode(PHINode &PN);
220     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
221     Instruction *visitAllocationInst(AllocationInst &AI);
222     Instruction *visitFreeInst(FreeInst &FI);
223     Instruction *visitLoadInst(LoadInst &LI);
224     Instruction *visitStoreInst(StoreInst &SI);
225     Instruction *visitBranchInst(BranchInst &BI);
226     Instruction *visitSwitchInst(SwitchInst &SI);
227     Instruction *visitInsertElementInst(InsertElementInst &IE);
228     Instruction *visitExtractElementInst(ExtractElementInst &EI);
229     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
230
231     // visitInstruction - Specify what to return for unhandled instructions...
232     Instruction *visitInstruction(Instruction &I) { return 0; }
233
234   private:
235     Instruction *visitCallSite(CallSite CS);
236     bool transformConstExprCastCall(CallSite CS);
237
238   public:
239     // InsertNewInstBefore - insert an instruction New before instruction Old
240     // in the program.  Add the new instruction to the worklist.
241     //
242     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
243       assert(New && New->getParent() == 0 &&
244              "New instruction already inserted into a basic block!");
245       BasicBlock *BB = Old.getParent();
246       BB->getInstList().insert(&Old, New);  // Insert inst
247       AddToWorkList(New);
248       return New;
249     }
250
251     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
252     /// This also adds the cast to the worklist.  Finally, this returns the
253     /// cast.
254     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
255                             Instruction &Pos) {
256       if (V->getType() == Ty) return V;
257
258       if (Constant *CV = dyn_cast<Constant>(V))
259         return ConstantExpr::getCast(opc, CV, Ty);
260       
261       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
262       AddToWorkList(C);
263       return C;
264     }
265
266     // ReplaceInstUsesWith - This method is to be used when an instruction is
267     // found to be dead, replacable with another preexisting expression.  Here
268     // we add all uses of I to the worklist, replace all uses of I with the new
269     // value, then return I, so that the inst combiner will know that I was
270     // modified.
271     //
272     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
273       AddUsersToWorkList(I);         // Add all modified instrs to worklist
274       if (&I != V) {
275         I.replaceAllUsesWith(V);
276         return &I;
277       } else {
278         // If we are replacing the instruction with itself, this must be in a
279         // segment of unreachable code, so just clobber the instruction.
280         I.replaceAllUsesWith(UndefValue::get(I.getType()));
281         return &I;
282       }
283     }
284
285     // UpdateValueUsesWith - This method is to be used when an value is
286     // found to be replacable with another preexisting expression or was
287     // updated.  Here we add all uses of I to the worklist, replace all uses of
288     // I with the new value (unless the instruction was just updated), then
289     // return true, so that the inst combiner will know that I was modified.
290     //
291     bool UpdateValueUsesWith(Value *Old, Value *New) {
292       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
293       if (Old != New)
294         Old->replaceAllUsesWith(New);
295       if (Instruction *I = dyn_cast<Instruction>(Old))
296         AddToWorkList(I);
297       if (Instruction *I = dyn_cast<Instruction>(New))
298         AddToWorkList(I);
299       return true;
300     }
301     
302     // EraseInstFromFunction - When dealing with an instruction that has side
303     // effects or produces a void value, we can't rely on DCE to delete the
304     // instruction.  Instead, visit methods should return the value returned by
305     // this function.
306     Instruction *EraseInstFromFunction(Instruction &I) {
307       assert(I.use_empty() && "Cannot erase instruction that is used!");
308       AddUsesToWorkList(I);
309       RemoveFromWorkList(&I);
310       I.eraseFromParent();
311       return 0;  // Don't do anything with FI
312     }
313
314   private:
315     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
316     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
317     /// casts that are known to not do anything...
318     ///
319     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
320                                    Value *V, const Type *DestTy,
321                                    Instruction *InsertBefore);
322
323     /// SimplifyCommutative - This performs a few simplifications for 
324     /// commutative operators.
325     bool SimplifyCommutative(BinaryOperator &I);
326
327     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
328     /// most-complex to least-complex order.
329     bool SimplifyCompare(CmpInst &I);
330
331     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
332     /// on the demanded bits.
333     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
334                               APInt& KnownZero, APInt& KnownOne,
335                               unsigned Depth = 0);
336
337     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
338                                       uint64_t &UndefElts, unsigned Depth = 0);
339       
340     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
341     // PHI node as operand #0, see if we can fold the instruction into the PHI
342     // (which is only possible if all operands to the PHI are constants).
343     Instruction *FoldOpIntoPhi(Instruction &I);
344
345     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
346     // operator and they all are only used by the PHI, PHI together their
347     // inputs, and do the operation once, to the result of the PHI.
348     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
349     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
350     
351     
352     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
353                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
354     
355     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
356                               bool isSub, Instruction &I);
357     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
358                                  bool isSigned, bool Inside, Instruction &IB);
359     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
360     Instruction *MatchBSwap(BinaryOperator &I);
361     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
362
363     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
364   };
365
366   char InstCombiner::ID = 0;
367   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
368 }
369
370 // getComplexity:  Assign a complexity or rank value to LLVM Values...
371 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
372 static unsigned getComplexity(Value *V) {
373   if (isa<Instruction>(V)) {
374     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
375       return 3;
376     return 4;
377   }
378   if (isa<Argument>(V)) return 3;
379   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
380 }
381
382 // isOnlyUse - Return true if this instruction will be deleted if we stop using
383 // it.
384 static bool isOnlyUse(Value *V) {
385   return V->hasOneUse() || isa<Constant>(V);
386 }
387
388 // getPromotedType - Return the specified type promoted as it would be to pass
389 // though a va_arg area...
390 static const Type *getPromotedType(const Type *Ty) {
391   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
392     if (ITy->getBitWidth() < 32)
393       return Type::Int32Ty;
394   }
395   return Ty;
396 }
397
398 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
399 /// expression bitcast,  return the operand value, otherwise return null.
400 static Value *getBitCastOperand(Value *V) {
401   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
402     return I->getOperand(0);
403   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
404     if (CE->getOpcode() == Instruction::BitCast)
405       return CE->getOperand(0);
406   return 0;
407 }
408
409 /// This function is a wrapper around CastInst::isEliminableCastPair. It
410 /// simply extracts arguments and returns what that function returns.
411 static Instruction::CastOps 
412 isEliminableCastPair(
413   const CastInst *CI, ///< The first cast instruction
414   unsigned opcode,       ///< The opcode of the second cast instruction
415   const Type *DstTy,     ///< The target type for the second cast instruction
416   TargetData *TD         ///< The target data for pointer size
417 ) {
418   
419   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
420   const Type *MidTy = CI->getType();                  // B from above
421
422   // Get the opcodes of the two Cast instructions
423   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
424   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
425
426   return Instruction::CastOps(
427       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
428                                      DstTy, TD->getIntPtrType()));
429 }
430
431 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
432 /// in any code being generated.  It does not require codegen if V is simple
433 /// enough or if the cast can be folded into other casts.
434 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
435                               const Type *Ty, TargetData *TD) {
436   if (V->getType() == Ty || isa<Constant>(V)) return false;
437   
438   // If this is another cast that can be eliminated, it isn't codegen either.
439   if (const CastInst *CI = dyn_cast<CastInst>(V))
440     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
441       return false;
442   return true;
443 }
444
445 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
446 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
447 /// casts that are known to not do anything...
448 ///
449 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
450                                              Value *V, const Type *DestTy,
451                                              Instruction *InsertBefore) {
452   if (V->getType() == DestTy) return V;
453   if (Constant *C = dyn_cast<Constant>(V))
454     return ConstantExpr::getCast(opcode, C, DestTy);
455   
456   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
457 }
458
459 // SimplifyCommutative - This performs a few simplifications for commutative
460 // operators:
461 //
462 //  1. Order operands such that they are listed from right (least complex) to
463 //     left (most complex).  This puts constants before unary operators before
464 //     binary operators.
465 //
466 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
467 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
468 //
469 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
470   bool Changed = false;
471   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
472     Changed = !I.swapOperands();
473
474   if (!I.isAssociative()) return Changed;
475   Instruction::BinaryOps Opcode = I.getOpcode();
476   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
477     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
478       if (isa<Constant>(I.getOperand(1))) {
479         Constant *Folded = ConstantExpr::get(I.getOpcode(),
480                                              cast<Constant>(I.getOperand(1)),
481                                              cast<Constant>(Op->getOperand(1)));
482         I.setOperand(0, Op->getOperand(0));
483         I.setOperand(1, Folded);
484         return true;
485       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
486         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
487             isOnlyUse(Op) && isOnlyUse(Op1)) {
488           Constant *C1 = cast<Constant>(Op->getOperand(1));
489           Constant *C2 = cast<Constant>(Op1->getOperand(1));
490
491           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
492           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
493           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
494                                                     Op1->getOperand(0),
495                                                     Op1->getName(), &I);
496           AddToWorkList(New);
497           I.setOperand(0, New);
498           I.setOperand(1, Folded);
499           return true;
500         }
501     }
502   return Changed;
503 }
504
505 /// SimplifyCompare - For a CmpInst this function just orders the operands
506 /// so that theyare listed from right (least complex) to left (most complex).
507 /// This puts constants before unary operators before binary operators.
508 bool InstCombiner::SimplifyCompare(CmpInst &I) {
509   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
510     return false;
511   I.swapOperands();
512   // Compare instructions are not associative so there's nothing else we can do.
513   return true;
514 }
515
516 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
517 // if the LHS is a constant zero (which is the 'negate' form).
518 //
519 static inline Value *dyn_castNegVal(Value *V) {
520   if (BinaryOperator::isNeg(V))
521     return BinaryOperator::getNegArgument(V);
522
523   // Constants can be considered to be negated values if they can be folded.
524   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
525     return ConstantExpr::getNeg(C);
526   return 0;
527 }
528
529 static inline Value *dyn_castNotVal(Value *V) {
530   if (BinaryOperator::isNot(V))
531     return BinaryOperator::getNotArgument(V);
532
533   // Constants can be considered to be not'ed values...
534   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535     return ConstantInt::get(~C->getValue());
536   return 0;
537 }
538
539 // dyn_castFoldableMul - If this value is a multiply that can be folded into
540 // other computations (because it has a constant operand), return the
541 // non-constant operand of the multiply, and set CST to point to the multiplier.
542 // Otherwise, return null.
543 //
544 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
545   if (V->hasOneUse() && V->getType()->isInteger())
546     if (Instruction *I = dyn_cast<Instruction>(V)) {
547       if (I->getOpcode() == Instruction::Mul)
548         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
549           return I->getOperand(0);
550       if (I->getOpcode() == Instruction::Shl)
551         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
552           // The multiplier is really 1 << CST.
553           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
554           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
555           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
556           return I->getOperand(0);
557         }
558     }
559   return 0;
560 }
561
562 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
563 /// expression, return it.
564 static User *dyn_castGetElementPtr(Value *V) {
565   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
566   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
567     if (CE->getOpcode() == Instruction::GetElementPtr)
568       return cast<User>(V);
569   return false;
570 }
571
572 /// AddOne - Add one to a ConstantInt
573 static ConstantInt *AddOne(ConstantInt *C) {
574   APInt Val(C->getValue());
575   return ConstantInt::get(++Val);
576 }
577 /// SubOne - Subtract one from a ConstantInt
578 static ConstantInt *SubOne(ConstantInt *C) {
579   APInt Val(C->getValue());
580   return ConstantInt::get(--Val);
581 }
582 /// Add - Add two ConstantInts together
583 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
584   return ConstantInt::get(C1->getValue() + C2->getValue());
585 }
586 /// And - Bitwise AND two ConstantInts together
587 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
588   return ConstantInt::get(C1->getValue() & C2->getValue());
589 }
590 /// Subtract - Subtract one ConstantInt from another
591 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
592   return ConstantInt::get(C1->getValue() - C2->getValue());
593 }
594 /// Multiply - Multiply two ConstantInts together
595 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
596   return ConstantInt::get(C1->getValue() * C2->getValue());
597 }
598
599 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
600 /// known to be either zero or one and return them in the KnownZero/KnownOne
601 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
602 /// processing.
603 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
604 /// we cannot optimize based on the assumption that it is zero without changing
605 /// it to be an explicit zero.  If we don't change it to zero, other code could
606 /// optimized based on the contradictory assumption that it is non-zero.
607 /// Because instcombine aggressively folds operations with undef args anyway,
608 /// this won't lose us code quality.
609 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
610                               APInt& KnownOne, unsigned Depth = 0) {
611   assert(V && "No Value?");
612   assert(Depth <= 6 && "Limit Search Depth");
613   uint32_t BitWidth = Mask.getBitWidth();
614   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
615          KnownZero.getBitWidth() == BitWidth && 
616          KnownOne.getBitWidth() == BitWidth &&
617          "V, Mask, KnownOne and KnownZero should have same BitWidth");
618   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
619     // We know all of the bits for a constant!
620     KnownOne = CI->getValue() & Mask;
621     KnownZero = ~KnownOne & Mask;
622     return;
623   }
624
625   if (Depth == 6 || Mask == 0)
626     return;  // Limit search depth.
627
628   Instruction *I = dyn_cast<Instruction>(V);
629   if (!I) return;
630
631   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
632   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
633   
634   switch (I->getOpcode()) {
635   case Instruction::And: {
636     // If either the LHS or the RHS are Zero, the result is zero.
637     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
638     APInt Mask2(Mask & ~KnownZero);
639     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
640     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
641     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
642     
643     // Output known-1 bits are only known if set in both the LHS & RHS.
644     KnownOne &= KnownOne2;
645     // Output known-0 are known to be clear if zero in either the LHS | RHS.
646     KnownZero |= KnownZero2;
647     return;
648   }
649   case Instruction::Or: {
650     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
651     APInt Mask2(Mask & ~KnownOne);
652     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
653     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
654     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
655     
656     // Output known-0 bits are only known if clear in both the LHS & RHS.
657     KnownZero &= KnownZero2;
658     // Output known-1 are known to be set if set in either the LHS | RHS.
659     KnownOne |= KnownOne2;
660     return;
661   }
662   case Instruction::Xor: {
663     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
664     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
665     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
666     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
667     
668     // Output known-0 bits are known if clear or set in both the LHS & RHS.
669     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
670     // Output known-1 are known to be set if set in only one of the LHS, RHS.
671     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
672     KnownZero = KnownZeroOut;
673     return;
674   }
675   case Instruction::Select:
676     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
677     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
678     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
679     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
680
681     // Only known if known in both the LHS and RHS.
682     KnownOne &= KnownOne2;
683     KnownZero &= KnownZero2;
684     return;
685   case Instruction::FPTrunc:
686   case Instruction::FPExt:
687   case Instruction::FPToUI:
688   case Instruction::FPToSI:
689   case Instruction::SIToFP:
690   case Instruction::PtrToInt:
691   case Instruction::UIToFP:
692   case Instruction::IntToPtr:
693     return; // Can't work with floating point or pointers
694   case Instruction::Trunc: {
695     // All these have integer operands
696     uint32_t SrcBitWidth = 
697       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
698     APInt MaskIn(Mask);
699     MaskIn.zext(SrcBitWidth);
700     KnownZero.zext(SrcBitWidth);
701     KnownOne.zext(SrcBitWidth);
702     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
703     KnownZero.trunc(BitWidth);
704     KnownOne.trunc(BitWidth);
705     return;
706   }
707   case Instruction::BitCast: {
708     const Type *SrcTy = I->getOperand(0)->getType();
709     if (SrcTy->isInteger()) {
710       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
711       return;
712     }
713     break;
714   }
715   case Instruction::ZExt:  {
716     // Compute the bits in the result that are not present in the input.
717     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
718     uint32_t SrcBitWidth = SrcTy->getBitWidth();
719       
720     APInt MaskIn(Mask);
721     MaskIn.trunc(SrcBitWidth);
722     KnownZero.trunc(SrcBitWidth);
723     KnownOne.trunc(SrcBitWidth);
724     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
725     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
726     // The top bits are known to be zero.
727     KnownZero.zext(BitWidth);
728     KnownOne.zext(BitWidth);
729     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
730     return;
731   }
732   case Instruction::SExt: {
733     // Compute the bits in the result that are not present in the input.
734     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
735     uint32_t SrcBitWidth = SrcTy->getBitWidth();
736       
737     APInt MaskIn(Mask); 
738     MaskIn.trunc(SrcBitWidth);
739     KnownZero.trunc(SrcBitWidth);
740     KnownOne.trunc(SrcBitWidth);
741     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
742     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
743     KnownZero.zext(BitWidth);
744     KnownOne.zext(BitWidth);
745
746     // If the sign bit of the input is known set or clear, then we know the
747     // top bits of the result.
748     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
749       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
750     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
751       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
752     return;
753   }
754   case Instruction::Shl:
755     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
756     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
757       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
758       APInt Mask2(Mask.lshr(ShiftAmt));
759       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
760       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
761       KnownZero <<= ShiftAmt;
762       KnownOne  <<= ShiftAmt;
763       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
764       return;
765     }
766     break;
767   case Instruction::LShr:
768     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
769     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
770       // Compute the new bits that are at the top now.
771       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
772       
773       // Unsigned shift right.
774       APInt Mask2(Mask.shl(ShiftAmt));
775       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
776       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
777       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
778       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
779       // high bits known zero.
780       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
781       return;
782     }
783     break;
784   case Instruction::AShr:
785     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
786     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
787       // Compute the new bits that are at the top now.
788       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
789       
790       // Signed shift right.
791       APInt Mask2(Mask.shl(ShiftAmt));
792       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
793       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
794       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
795       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
796         
797       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
798       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
799         KnownZero |= HighBits;
800       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
801         KnownOne |= HighBits;
802       return;
803     }
804     break;
805   }
806 }
807
808 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
809 /// this predicate to simplify operations downstream.  Mask is known to be zero
810 /// for bits that V cannot have.
811 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
812   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
813   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
814   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
815   return (KnownZero & Mask) == Mask;
816 }
817
818 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
819 /// specified instruction is a constant integer.  If so, check to see if there
820 /// are any bits set in the constant that are not demanded.  If so, shrink the
821 /// constant and return true.
822 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
823                                    APInt Demanded) {
824   assert(I && "No instruction?");
825   assert(OpNo < I->getNumOperands() && "Operand index too large");
826
827   // If the operand is not a constant integer, nothing to do.
828   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
829   if (!OpC) return false;
830
831   // If there are no bits set that aren't demanded, nothing to do.
832   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
833   if ((~Demanded & OpC->getValue()) == 0)
834     return false;
835
836   // This instruction is producing bits that are not demanded. Shrink the RHS.
837   Demanded &= OpC->getValue();
838   I->setOperand(OpNo, ConstantInt::get(Demanded));
839   return true;
840 }
841
842 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
843 // set of known zero and one bits, compute the maximum and minimum values that
844 // could have the specified known zero and known one bits, returning them in
845 // min/max.
846 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
847                                                    const APInt& KnownZero,
848                                                    const APInt& KnownOne,
849                                                    APInt& Min, APInt& Max) {
850   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
851   assert(KnownZero.getBitWidth() == BitWidth && 
852          KnownOne.getBitWidth() == BitWidth &&
853          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
854          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
855   APInt UnknownBits = ~(KnownZero|KnownOne);
856
857   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
858   // bit if it is unknown.
859   Min = KnownOne;
860   Max = KnownOne|UnknownBits;
861   
862   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
863     Min.set(BitWidth-1);
864     Max.clear(BitWidth-1);
865   }
866 }
867
868 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
869 // a set of known zero and one bits, compute the maximum and minimum values that
870 // could have the specified known zero and known one bits, returning them in
871 // min/max.
872 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
873                                                      const APInt& KnownZero,
874                                                      const APInt& KnownOne,
875                                                      APInt& Min,
876                                                      APInt& Max) {
877   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
878   assert(KnownZero.getBitWidth() == BitWidth && 
879          KnownOne.getBitWidth() == BitWidth &&
880          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
881          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
882   APInt UnknownBits = ~(KnownZero|KnownOne);
883   
884   // The minimum value is when the unknown bits are all zeros.
885   Min = KnownOne;
886   // The maximum value is when the unknown bits are all ones.
887   Max = KnownOne|UnknownBits;
888 }
889
890 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
891 /// value based on the demanded bits. When this function is called, it is known
892 /// that only the bits set in DemandedMask of the result of V are ever used
893 /// downstream. Consequently, depending on the mask and V, it may be possible
894 /// to replace V with a constant or one of its operands. In such cases, this
895 /// function does the replacement and returns true. In all other cases, it
896 /// returns false after analyzing the expression and setting KnownOne and known
897 /// to be one in the expression. KnownZero contains all the bits that are known
898 /// to be zero in the expression. These are provided to potentially allow the
899 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
900 /// the expression. KnownOne and KnownZero always follow the invariant that 
901 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
902 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
903 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
904 /// and KnownOne must all be the same.
905 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
906                                         APInt& KnownZero, APInt& KnownOne,
907                                         unsigned Depth) {
908   assert(V != 0 && "Null pointer of Value???");
909   assert(Depth <= 6 && "Limit Search Depth");
910   uint32_t BitWidth = DemandedMask.getBitWidth();
911   const IntegerType *VTy = cast<IntegerType>(V->getType());
912   assert(VTy->getBitWidth() == BitWidth && 
913          KnownZero.getBitWidth() == BitWidth && 
914          KnownOne.getBitWidth() == BitWidth &&
915          "Value *V, DemandedMask, KnownZero and KnownOne \
916           must have same BitWidth");
917   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
918     // We know all of the bits for a constant!
919     KnownOne = CI->getValue() & DemandedMask;
920     KnownZero = ~KnownOne & DemandedMask;
921     return false;
922   }
923   
924   KnownZero.clear(); 
925   KnownOne.clear();
926   if (!V->hasOneUse()) {    // Other users may use these bits.
927     if (Depth != 0) {       // Not at the root.
928       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
929       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
930       return false;
931     }
932     // If this is the root being simplified, allow it to have multiple uses,
933     // just set the DemandedMask to all bits.
934     DemandedMask = APInt::getAllOnesValue(BitWidth);
935   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
936     if (V != UndefValue::get(VTy))
937       return UpdateValueUsesWith(V, UndefValue::get(VTy));
938     return false;
939   } else if (Depth == 6) {        // Limit search depth.
940     return false;
941   }
942   
943   Instruction *I = dyn_cast<Instruction>(V);
944   if (!I) return false;        // Only analyze instructions.
945
946   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
947   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
948   switch (I->getOpcode()) {
949   default: break;
950   case Instruction::And:
951     // If either the LHS or the RHS are Zero, the result is zero.
952     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
953                              RHSKnownZero, RHSKnownOne, Depth+1))
954       return true;
955     assert((RHSKnownZero & RHSKnownOne) == 0 && 
956            "Bits known to be one AND zero?"); 
957
958     // If something is known zero on the RHS, the bits aren't demanded on the
959     // LHS.
960     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
961                              LHSKnownZero, LHSKnownOne, Depth+1))
962       return true;
963     assert((LHSKnownZero & LHSKnownOne) == 0 && 
964            "Bits known to be one AND zero?"); 
965
966     // If all of the demanded bits are known 1 on one side, return the other.
967     // These bits cannot contribute to the result of the 'and'.
968     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
969         (DemandedMask & ~LHSKnownZero))
970       return UpdateValueUsesWith(I, I->getOperand(0));
971     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
972         (DemandedMask & ~RHSKnownZero))
973       return UpdateValueUsesWith(I, I->getOperand(1));
974     
975     // If all of the demanded bits in the inputs are known zeros, return zero.
976     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
977       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
978       
979     // If the RHS is a constant, see if we can simplify it.
980     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
981       return UpdateValueUsesWith(I, I);
982       
983     // Output known-1 bits are only known if set in both the LHS & RHS.
984     RHSKnownOne &= LHSKnownOne;
985     // Output known-0 are known to be clear if zero in either the LHS | RHS.
986     RHSKnownZero |= LHSKnownZero;
987     break;
988   case Instruction::Or:
989     // If either the LHS or the RHS are One, the result is One.
990     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
991                              RHSKnownZero, RHSKnownOne, Depth+1))
992       return true;
993     assert((RHSKnownZero & RHSKnownOne) == 0 && 
994            "Bits known to be one AND zero?"); 
995     // If something is known one on the RHS, the bits aren't demanded on the
996     // LHS.
997     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
998                              LHSKnownZero, LHSKnownOne, Depth+1))
999       return true;
1000     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1001            "Bits known to be one AND zero?"); 
1002     
1003     // If all of the demanded bits are known zero on one side, return the other.
1004     // These bits cannot contribute to the result of the 'or'.
1005     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1006         (DemandedMask & ~LHSKnownOne))
1007       return UpdateValueUsesWith(I, I->getOperand(0));
1008     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1009         (DemandedMask & ~RHSKnownOne))
1010       return UpdateValueUsesWith(I, I->getOperand(1));
1011
1012     // If all of the potentially set bits on one side are known to be set on
1013     // the other side, just use the 'other' side.
1014     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1015         (DemandedMask & (~RHSKnownZero)))
1016       return UpdateValueUsesWith(I, I->getOperand(0));
1017     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1018         (DemandedMask & (~LHSKnownZero)))
1019       return UpdateValueUsesWith(I, I->getOperand(1));
1020         
1021     // If the RHS is a constant, see if we can simplify it.
1022     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023       return UpdateValueUsesWith(I, I);
1024           
1025     // Output known-0 bits are only known if clear in both the LHS & RHS.
1026     RHSKnownZero &= LHSKnownZero;
1027     // Output known-1 are known to be set if set in either the LHS | RHS.
1028     RHSKnownOne |= LHSKnownOne;
1029     break;
1030   case Instruction::Xor: {
1031     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1032                              RHSKnownZero, RHSKnownOne, Depth+1))
1033       return true;
1034     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1035            "Bits known to be one AND zero?"); 
1036     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1037                              LHSKnownZero, LHSKnownOne, Depth+1))
1038       return true;
1039     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1040            "Bits known to be one AND zero?"); 
1041     
1042     // If all of the demanded bits are known zero on one side, return the other.
1043     // These bits cannot contribute to the result of the 'xor'.
1044     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1045       return UpdateValueUsesWith(I, I->getOperand(0));
1046     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1047       return UpdateValueUsesWith(I, I->getOperand(1));
1048     
1049     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1050     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1051                          (RHSKnownOne & LHSKnownOne);
1052     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1053     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1054                         (RHSKnownOne & LHSKnownZero);
1055     
1056     // If all of the demanded bits are known to be zero on one side or the
1057     // other, turn this into an *inclusive* or.
1058     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1059     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1060       Instruction *Or =
1061         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1062                                  I->getName());
1063       InsertNewInstBefore(Or, *I);
1064       return UpdateValueUsesWith(I, Or);
1065     }
1066     
1067     // If all of the demanded bits on one side are known, and all of the set
1068     // bits on that side are also known to be set on the other side, turn this
1069     // into an AND, as we know the bits will be cleared.
1070     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1071     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1072       // all known
1073       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1074         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1075         Instruction *And = 
1076           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1077         InsertNewInstBefore(And, *I);
1078         return UpdateValueUsesWith(I, And);
1079       }
1080     }
1081     
1082     // If the RHS is a constant, see if we can simplify it.
1083     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1084     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1085       return UpdateValueUsesWith(I, I);
1086     
1087     RHSKnownZero = KnownZeroOut;
1088     RHSKnownOne  = KnownOneOut;
1089     break;
1090   }
1091   case Instruction::Select:
1092     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1093                              RHSKnownZero, RHSKnownOne, Depth+1))
1094       return true;
1095     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1096                              LHSKnownZero, LHSKnownOne, Depth+1))
1097       return true;
1098     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1099            "Bits known to be one AND zero?"); 
1100     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1101            "Bits known to be one AND zero?"); 
1102     
1103     // If the operands are constants, see if we can simplify them.
1104     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1105       return UpdateValueUsesWith(I, I);
1106     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1107       return UpdateValueUsesWith(I, I);
1108     
1109     // Only known if known in both the LHS and RHS.
1110     RHSKnownOne &= LHSKnownOne;
1111     RHSKnownZero &= LHSKnownZero;
1112     break;
1113   case Instruction::Trunc: {
1114     uint32_t truncBf = 
1115       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1116     DemandedMask.zext(truncBf);
1117     RHSKnownZero.zext(truncBf);
1118     RHSKnownOne.zext(truncBf);
1119     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1120                              RHSKnownZero, RHSKnownOne, Depth+1))
1121       return true;
1122     DemandedMask.trunc(BitWidth);
1123     RHSKnownZero.trunc(BitWidth);
1124     RHSKnownOne.trunc(BitWidth);
1125     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1126            "Bits known to be one AND zero?"); 
1127     break;
1128   }
1129   case Instruction::BitCast:
1130     if (!I->getOperand(0)->getType()->isInteger())
1131       return false;
1132       
1133     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1134                              RHSKnownZero, RHSKnownOne, Depth+1))
1135       return true;
1136     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1137            "Bits known to be one AND zero?"); 
1138     break;
1139   case Instruction::ZExt: {
1140     // Compute the bits in the result that are not present in the input.
1141     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1142     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1143     
1144     DemandedMask.trunc(SrcBitWidth);
1145     RHSKnownZero.trunc(SrcBitWidth);
1146     RHSKnownOne.trunc(SrcBitWidth);
1147     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1148                              RHSKnownZero, RHSKnownOne, Depth+1))
1149       return true;
1150     DemandedMask.zext(BitWidth);
1151     RHSKnownZero.zext(BitWidth);
1152     RHSKnownOne.zext(BitWidth);
1153     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1154            "Bits known to be one AND zero?"); 
1155     // The top bits are known to be zero.
1156     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1157     break;
1158   }
1159   case Instruction::SExt: {
1160     // Compute the bits in the result that are not present in the input.
1161     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1162     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1163     
1164     APInt InputDemandedBits = DemandedMask & 
1165                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1166
1167     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1168     // If any of the sign extended bits are demanded, we know that the sign
1169     // bit is demanded.
1170     if ((NewBits & DemandedMask) != 0)
1171       InputDemandedBits.set(SrcBitWidth-1);
1172       
1173     InputDemandedBits.trunc(SrcBitWidth);
1174     RHSKnownZero.trunc(SrcBitWidth);
1175     RHSKnownOne.trunc(SrcBitWidth);
1176     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1177                              RHSKnownZero, RHSKnownOne, Depth+1))
1178       return true;
1179     InputDemandedBits.zext(BitWidth);
1180     RHSKnownZero.zext(BitWidth);
1181     RHSKnownOne.zext(BitWidth);
1182     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1183            "Bits known to be one AND zero?"); 
1184       
1185     // If the sign bit of the input is known set or clear, then we know the
1186     // top bits of the result.
1187
1188     // If the input sign bit is known zero, or if the NewBits are not demanded
1189     // convert this into a zero extension.
1190     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1191     {
1192       // Convert to ZExt cast
1193       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1194       return UpdateValueUsesWith(I, NewCast);
1195     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1196       RHSKnownOne |= NewBits;
1197     }
1198     break;
1199   }
1200   case Instruction::Add: {
1201     // Figure out what the input bits are.  If the top bits of the and result
1202     // are not demanded, then the add doesn't demand them from its input
1203     // either.
1204     uint32_t NLZ = DemandedMask.countLeadingZeros();
1205       
1206     // If there is a constant on the RHS, there are a variety of xformations
1207     // we can do.
1208     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1209       // If null, this should be simplified elsewhere.  Some of the xforms here
1210       // won't work if the RHS is zero.
1211       if (RHS->isZero())
1212         break;
1213       
1214       // If the top bit of the output is demanded, demand everything from the
1215       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1216       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1217
1218       // Find information about known zero/one bits in the input.
1219       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1220                                LHSKnownZero, LHSKnownOne, Depth+1))
1221         return true;
1222
1223       // If the RHS of the add has bits set that can't affect the input, reduce
1224       // the constant.
1225       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1226         return UpdateValueUsesWith(I, I);
1227       
1228       // Avoid excess work.
1229       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1230         break;
1231       
1232       // Turn it into OR if input bits are zero.
1233       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1234         Instruction *Or =
1235           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1236                                    I->getName());
1237         InsertNewInstBefore(Or, *I);
1238         return UpdateValueUsesWith(I, Or);
1239       }
1240       
1241       // We can say something about the output known-zero and known-one bits,
1242       // depending on potential carries from the input constant and the
1243       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1244       // bits set and the RHS constant is 0x01001, then we know we have a known
1245       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1246       
1247       // To compute this, we first compute the potential carry bits.  These are
1248       // the bits which may be modified.  I'm not aware of a better way to do
1249       // this scan.
1250       const APInt& RHSVal = RHS->getValue();
1251       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1252       
1253       // Now that we know which bits have carries, compute the known-1/0 sets.
1254       
1255       // Bits are known one if they are known zero in one operand and one in the
1256       // other, and there is no input carry.
1257       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1258                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1259       
1260       // Bits are known zero if they are known zero in both operands and there
1261       // is no input carry.
1262       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1263     } else {
1264       // If the high-bits of this ADD are not demanded, then it does not demand
1265       // the high bits of its LHS or RHS.
1266       if (DemandedMask[BitWidth-1] == 0) {
1267         // Right fill the mask of bits for this ADD to demand the most
1268         // significant bit and all those below it.
1269         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1270         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1271                                  LHSKnownZero, LHSKnownOne, Depth+1))
1272           return true;
1273         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1274                                  LHSKnownZero, LHSKnownOne, Depth+1))
1275           return true;
1276       }
1277     }
1278     break;
1279   }
1280   case Instruction::Sub:
1281     // If the high-bits of this SUB are not demanded, then it does not demand
1282     // the high bits of its LHS or RHS.
1283     if (DemandedMask[BitWidth-1] == 0) {
1284       // Right fill the mask of bits for this SUB to demand the most
1285       // significant bit and all those below it.
1286       uint32_t NLZ = DemandedMask.countLeadingZeros();
1287       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1288       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1289                                LHSKnownZero, LHSKnownOne, Depth+1))
1290         return true;
1291       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1292                                LHSKnownZero, LHSKnownOne, Depth+1))
1293         return true;
1294     }
1295     break;
1296   case Instruction::Shl:
1297     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1298       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1299       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1300       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1301                                RHSKnownZero, RHSKnownOne, Depth+1))
1302         return true;
1303       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1304              "Bits known to be one AND zero?"); 
1305       RHSKnownZero <<= ShiftAmt;
1306       RHSKnownOne  <<= ShiftAmt;
1307       // low bits known zero.
1308       if (ShiftAmt)
1309         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1310     }
1311     break;
1312   case Instruction::LShr:
1313     // For a logical shift right
1314     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1315       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1316       
1317       // Unsigned shift right.
1318       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1319       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1320                                RHSKnownZero, RHSKnownOne, Depth+1))
1321         return true;
1322       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1323              "Bits known to be one AND zero?"); 
1324       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1325       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1326       if (ShiftAmt) {
1327         // Compute the new bits that are at the top now.
1328         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1329         RHSKnownZero |= HighBits;  // high bits known zero.
1330       }
1331     }
1332     break;
1333   case Instruction::AShr:
1334     // If this is an arithmetic shift right and only the low-bit is set, we can
1335     // always convert this into a logical shr, even if the shift amount is
1336     // variable.  The low bit of the shift cannot be an input sign bit unless
1337     // the shift amount is >= the size of the datatype, which is undefined.
1338     if (DemandedMask == 1) {
1339       // Perform the logical shift right.
1340       Value *NewVal = BinaryOperator::createLShr(
1341                         I->getOperand(0), I->getOperand(1), I->getName());
1342       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1343       return UpdateValueUsesWith(I, NewVal);
1344     }    
1345
1346     // If the sign bit is the only bit demanded by this ashr, then there is no
1347     // need to do it, the shift doesn't change the high bit.
1348     if (DemandedMask.isSignBit())
1349       return UpdateValueUsesWith(I, I->getOperand(0));
1350     
1351     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1352       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1353       
1354       // Signed shift right.
1355       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1356       // If any of the "high bits" are demanded, we should set the sign bit as
1357       // demanded.
1358       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1359         DemandedMaskIn.set(BitWidth-1);
1360       if (SimplifyDemandedBits(I->getOperand(0),
1361                                DemandedMaskIn,
1362                                RHSKnownZero, RHSKnownOne, Depth+1))
1363         return true;
1364       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1365              "Bits known to be one AND zero?"); 
1366       // Compute the new bits that are at the top now.
1367       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1368       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1369       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1370         
1371       // Handle the sign bits.
1372       APInt SignBit(APInt::getSignBit(BitWidth));
1373       // Adjust to where it is now in the mask.
1374       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1375         
1376       // If the input sign bit is known to be zero, or if none of the top bits
1377       // are demanded, turn this into an unsigned shift right.
1378       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1379           (HighBits & ~DemandedMask) == HighBits) {
1380         // Perform the logical shift right.
1381         Value *NewVal = BinaryOperator::createLShr(
1382                           I->getOperand(0), SA, I->getName());
1383         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1384         return UpdateValueUsesWith(I, NewVal);
1385       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1386         RHSKnownOne |= HighBits;
1387       }
1388     }
1389     break;
1390   }
1391   
1392   // If the client is only demanding bits that we know, return the known
1393   // constant.
1394   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1395     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1396   return false;
1397 }
1398
1399
1400 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1401 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1402 /// actually used by the caller.  This method analyzes which elements of the
1403 /// operand are undef and returns that information in UndefElts.
1404 ///
1405 /// If the information about demanded elements can be used to simplify the
1406 /// operation, the operation is simplified, then the resultant value is
1407 /// returned.  This returns null if no change was made.
1408 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1409                                                 uint64_t &UndefElts,
1410                                                 unsigned Depth) {
1411   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1412   assert(VWidth <= 64 && "Vector too wide to analyze!");
1413   uint64_t EltMask = ~0ULL >> (64-VWidth);
1414   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1415          "Invalid DemandedElts!");
1416
1417   if (isa<UndefValue>(V)) {
1418     // If the entire vector is undefined, just return this info.
1419     UndefElts = EltMask;
1420     return 0;
1421   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1422     UndefElts = EltMask;
1423     return UndefValue::get(V->getType());
1424   }
1425   
1426   UndefElts = 0;
1427   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1428     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1429     Constant *Undef = UndefValue::get(EltTy);
1430
1431     std::vector<Constant*> Elts;
1432     for (unsigned i = 0; i != VWidth; ++i)
1433       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1434         Elts.push_back(Undef);
1435         UndefElts |= (1ULL << i);
1436       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1437         Elts.push_back(Undef);
1438         UndefElts |= (1ULL << i);
1439       } else {                               // Otherwise, defined.
1440         Elts.push_back(CP->getOperand(i));
1441       }
1442         
1443     // If we changed the constant, return it.
1444     Constant *NewCP = ConstantVector::get(Elts);
1445     return NewCP != CP ? NewCP : 0;
1446   } else if (isa<ConstantAggregateZero>(V)) {
1447     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1448     // set to undef.
1449     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1450     Constant *Zero = Constant::getNullValue(EltTy);
1451     Constant *Undef = UndefValue::get(EltTy);
1452     std::vector<Constant*> Elts;
1453     for (unsigned i = 0; i != VWidth; ++i)
1454       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1455     UndefElts = DemandedElts ^ EltMask;
1456     return ConstantVector::get(Elts);
1457   }
1458   
1459   if (!V->hasOneUse()) {    // Other users may use these bits.
1460     if (Depth != 0) {       // Not at the root.
1461       // TODO: Just compute the UndefElts information recursively.
1462       return false;
1463     }
1464     return false;
1465   } else if (Depth == 10) {        // Limit search depth.
1466     return false;
1467   }
1468   
1469   Instruction *I = dyn_cast<Instruction>(V);
1470   if (!I) return false;        // Only analyze instructions.
1471   
1472   bool MadeChange = false;
1473   uint64_t UndefElts2;
1474   Value *TmpV;
1475   switch (I->getOpcode()) {
1476   default: break;
1477     
1478   case Instruction::InsertElement: {
1479     // If this is a variable index, we don't know which element it overwrites.
1480     // demand exactly the same input as we produce.
1481     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1482     if (Idx == 0) {
1483       // Note that we can't propagate undef elt info, because we don't know
1484       // which elt is getting updated.
1485       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1486                                         UndefElts2, Depth+1);
1487       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1488       break;
1489     }
1490     
1491     // If this is inserting an element that isn't demanded, remove this
1492     // insertelement.
1493     unsigned IdxNo = Idx->getZExtValue();
1494     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1495       return AddSoonDeadInstToWorklist(*I, 0);
1496     
1497     // Otherwise, the element inserted overwrites whatever was there, so the
1498     // input demanded set is simpler than the output set.
1499     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1500                                       DemandedElts & ~(1ULL << IdxNo),
1501                                       UndefElts, Depth+1);
1502     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1503
1504     // The inserted element is defined.
1505     UndefElts |= 1ULL << IdxNo;
1506     break;
1507   }
1508   case Instruction::BitCast: {
1509     // Vector->vector casts only.
1510     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1511     if (!VTy) break;
1512     unsigned InVWidth = VTy->getNumElements();
1513     uint64_t InputDemandedElts = 0;
1514     unsigned Ratio;
1515
1516     if (VWidth == InVWidth) {
1517       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1518       // elements as are demanded of us.
1519       Ratio = 1;
1520       InputDemandedElts = DemandedElts;
1521     } else if (VWidth > InVWidth) {
1522       // Untested so far.
1523       break;
1524       
1525       // If there are more elements in the result than there are in the source,
1526       // then an input element is live if any of the corresponding output
1527       // elements are live.
1528       Ratio = VWidth/InVWidth;
1529       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1530         if (DemandedElts & (1ULL << OutIdx))
1531           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1532       }
1533     } else {
1534       // Untested so far.
1535       break;
1536       
1537       // If there are more elements in the source than there are in the result,
1538       // then an input element is live if the corresponding output element is
1539       // live.
1540       Ratio = InVWidth/VWidth;
1541       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1542         if (DemandedElts & (1ULL << InIdx/Ratio))
1543           InputDemandedElts |= 1ULL << InIdx;
1544     }
1545     
1546     // div/rem demand all inputs, because they don't want divide by zero.
1547     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1548                                       UndefElts2, Depth+1);
1549     if (TmpV) {
1550       I->setOperand(0, TmpV);
1551       MadeChange = true;
1552     }
1553     
1554     UndefElts = UndefElts2;
1555     if (VWidth > InVWidth) {
1556       assert(0 && "Unimp");
1557       // If there are more elements in the result than there are in the source,
1558       // then an output element is undef if the corresponding input element is
1559       // undef.
1560       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1561         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1562           UndefElts |= 1ULL << OutIdx;
1563     } else if (VWidth < InVWidth) {
1564       assert(0 && "Unimp");
1565       // If there are more elements in the source than there are in the result,
1566       // then a result element is undef if all of the corresponding input
1567       // elements are undef.
1568       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1569       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1570         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1571           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1572     }
1573     break;
1574   }
1575   case Instruction::And:
1576   case Instruction::Or:
1577   case Instruction::Xor:
1578   case Instruction::Add:
1579   case Instruction::Sub:
1580   case Instruction::Mul:
1581     // div/rem demand all inputs, because they don't want divide by zero.
1582     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1583                                       UndefElts, Depth+1);
1584     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1585     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1586                                       UndefElts2, Depth+1);
1587     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1588       
1589     // Output elements are undefined if both are undefined.  Consider things
1590     // like undef&0.  The result is known zero, not undef.
1591     UndefElts &= UndefElts2;
1592     break;
1593     
1594   case Instruction::Call: {
1595     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1596     if (!II) break;
1597     switch (II->getIntrinsicID()) {
1598     default: break;
1599       
1600     // Binary vector operations that work column-wise.  A dest element is a
1601     // function of the corresponding input elements from the two inputs.
1602     case Intrinsic::x86_sse_sub_ss:
1603     case Intrinsic::x86_sse_mul_ss:
1604     case Intrinsic::x86_sse_min_ss:
1605     case Intrinsic::x86_sse_max_ss:
1606     case Intrinsic::x86_sse2_sub_sd:
1607     case Intrinsic::x86_sse2_mul_sd:
1608     case Intrinsic::x86_sse2_min_sd:
1609     case Intrinsic::x86_sse2_max_sd:
1610       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1611                                         UndefElts, Depth+1);
1612       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1613       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1614                                         UndefElts2, Depth+1);
1615       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1616
1617       // If only the low elt is demanded and this is a scalarizable intrinsic,
1618       // scalarize it now.
1619       if (DemandedElts == 1) {
1620         switch (II->getIntrinsicID()) {
1621         default: break;
1622         case Intrinsic::x86_sse_sub_ss:
1623         case Intrinsic::x86_sse_mul_ss:
1624         case Intrinsic::x86_sse2_sub_sd:
1625         case Intrinsic::x86_sse2_mul_sd:
1626           // TODO: Lower MIN/MAX/ABS/etc
1627           Value *LHS = II->getOperand(1);
1628           Value *RHS = II->getOperand(2);
1629           // Extract the element as scalars.
1630           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1631           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1632           
1633           switch (II->getIntrinsicID()) {
1634           default: assert(0 && "Case stmts out of sync!");
1635           case Intrinsic::x86_sse_sub_ss:
1636           case Intrinsic::x86_sse2_sub_sd:
1637             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1638                                                         II->getName()), *II);
1639             break;
1640           case Intrinsic::x86_sse_mul_ss:
1641           case Intrinsic::x86_sse2_mul_sd:
1642             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1643                                                          II->getName()), *II);
1644             break;
1645           }
1646           
1647           Instruction *New =
1648             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1649                                   II->getName());
1650           InsertNewInstBefore(New, *II);
1651           AddSoonDeadInstToWorklist(*II, 0);
1652           return New;
1653         }            
1654       }
1655         
1656       // Output elements are undefined if both are undefined.  Consider things
1657       // like undef&0.  The result is known zero, not undef.
1658       UndefElts &= UndefElts2;
1659       break;
1660     }
1661     break;
1662   }
1663   }
1664   return MadeChange ? I : 0;
1665 }
1666
1667 /// @returns true if the specified compare instruction is
1668 /// true when both operands are equal...
1669 /// @brief Determine if the ICmpInst returns true if both operands are equal
1670 static bool isTrueWhenEqual(ICmpInst &ICI) {
1671   ICmpInst::Predicate pred = ICI.getPredicate();
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 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1678 /// function is designed to check a chain of associative operators for a
1679 /// potential to apply a certain optimization.  Since the optimization may be
1680 /// applicable if the expression was reassociated, this checks the chain, then
1681 /// reassociates the expression as necessary to expose the optimization
1682 /// opportunity.  This makes use of a special Functor, which must define
1683 /// 'shouldApply' and 'apply' methods.
1684 ///
1685 template<typename Functor>
1686 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1687   unsigned Opcode = Root.getOpcode();
1688   Value *LHS = Root.getOperand(0);
1689
1690   // Quick check, see if the immediate LHS matches...
1691   if (F.shouldApply(LHS))
1692     return F.apply(Root);
1693
1694   // Otherwise, if the LHS is not of the same opcode as the root, return.
1695   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1696   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1697     // Should we apply this transform to the RHS?
1698     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1699
1700     // If not to the RHS, check to see if we should apply to the LHS...
1701     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1702       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1703       ShouldApply = true;
1704     }
1705
1706     // If the functor wants to apply the optimization to the RHS of LHSI,
1707     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1708     if (ShouldApply) {
1709       BasicBlock *BB = Root.getParent();
1710
1711       // Now all of the instructions are in the current basic block, go ahead
1712       // and perform the reassociation.
1713       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1714
1715       // First move the selected RHS to the LHS of the root...
1716       Root.setOperand(0, LHSI->getOperand(1));
1717
1718       // Make what used to be the LHS of the root be the user of the root...
1719       Value *ExtraOperand = TmpLHSI->getOperand(1);
1720       if (&Root == TmpLHSI) {
1721         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1722         return 0;
1723       }
1724       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1725       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1726       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1727       BasicBlock::iterator ARI = &Root; ++ARI;
1728       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1729       ARI = Root;
1730
1731       // Now propagate the ExtraOperand down the chain of instructions until we
1732       // get to LHSI.
1733       while (TmpLHSI != LHSI) {
1734         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1735         // Move the instruction to immediately before the chain we are
1736         // constructing to avoid breaking dominance properties.
1737         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1738         BB->getInstList().insert(ARI, NextLHSI);
1739         ARI = NextLHSI;
1740
1741         Value *NextOp = NextLHSI->getOperand(1);
1742         NextLHSI->setOperand(1, ExtraOperand);
1743         TmpLHSI = NextLHSI;
1744         ExtraOperand = NextOp;
1745       }
1746
1747       // Now that the instructions are reassociated, have the functor perform
1748       // the transformation...
1749       return F.apply(Root);
1750     }
1751
1752     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1753   }
1754   return 0;
1755 }
1756
1757
1758 // AddRHS - Implements: X + X --> X << 1
1759 struct AddRHS {
1760   Value *RHS;
1761   AddRHS(Value *rhs) : RHS(rhs) {}
1762   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1763   Instruction *apply(BinaryOperator &Add) const {
1764     return BinaryOperator::createShl(Add.getOperand(0),
1765                                   ConstantInt::get(Add.getType(), 1));
1766   }
1767 };
1768
1769 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1770 //                 iff C1&C2 == 0
1771 struct AddMaskingAnd {
1772   Constant *C2;
1773   AddMaskingAnd(Constant *c) : C2(c) {}
1774   bool shouldApply(Value *LHS) const {
1775     ConstantInt *C1;
1776     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1777            ConstantExpr::getAnd(C1, C2)->isNullValue();
1778   }
1779   Instruction *apply(BinaryOperator &Add) const {
1780     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1781   }
1782 };
1783
1784 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1785                                              InstCombiner *IC) {
1786   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1787     if (Constant *SOC = dyn_cast<Constant>(SO))
1788       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1789
1790     return IC->InsertNewInstBefore(CastInst::create(
1791           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1792   }
1793
1794   // Figure out if the constant is the left or the right argument.
1795   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1796   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1797
1798   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1799     if (ConstIsRHS)
1800       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1801     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1802   }
1803
1804   Value *Op0 = SO, *Op1 = ConstOperand;
1805   if (!ConstIsRHS)
1806     std::swap(Op0, Op1);
1807   Instruction *New;
1808   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1809     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1810   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1811     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1812                           SO->getName()+".cmp");
1813   else {
1814     assert(0 && "Unknown binary instruction type!");
1815     abort();
1816   }
1817   return IC->InsertNewInstBefore(New, I);
1818 }
1819
1820 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1821 // constant as the other operand, try to fold the binary operator into the
1822 // select arguments.  This also works for Cast instructions, which obviously do
1823 // not have a second operand.
1824 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1825                                      InstCombiner *IC) {
1826   // Don't modify shared select instructions
1827   if (!SI->hasOneUse()) return 0;
1828   Value *TV = SI->getOperand(1);
1829   Value *FV = SI->getOperand(2);
1830
1831   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1832     // Bool selects with constant operands can be folded to logical ops.
1833     if (SI->getType() == Type::Int1Ty) return 0;
1834
1835     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1836     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1837
1838     return new SelectInst(SI->getCondition(), SelectTrueVal,
1839                           SelectFalseVal);
1840   }
1841   return 0;
1842 }
1843
1844
1845 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1846 /// node as operand #0, see if we can fold the instruction into the PHI (which
1847 /// is only possible if all operands to the PHI are constants).
1848 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1849   PHINode *PN = cast<PHINode>(I.getOperand(0));
1850   unsigned NumPHIValues = PN->getNumIncomingValues();
1851   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1852
1853   // Check to see if all of the operands of the PHI are constants.  If there is
1854   // one non-constant value, remember the BB it is.  If there is more than one
1855   // or if *it* is a PHI, bail out.
1856   BasicBlock *NonConstBB = 0;
1857   for (unsigned i = 0; i != NumPHIValues; ++i)
1858     if (!isa<Constant>(PN->getIncomingValue(i))) {
1859       if (NonConstBB) return 0;  // More than one non-const value.
1860       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1861       NonConstBB = PN->getIncomingBlock(i);
1862       
1863       // If the incoming non-constant value is in I's block, we have an infinite
1864       // loop.
1865       if (NonConstBB == I.getParent())
1866         return 0;
1867     }
1868   
1869   // If there is exactly one non-constant value, we can insert a copy of the
1870   // operation in that block.  However, if this is a critical edge, we would be
1871   // inserting the computation one some other paths (e.g. inside a loop).  Only
1872   // do this if the pred block is unconditionally branching into the phi block.
1873   if (NonConstBB) {
1874     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1875     if (!BI || !BI->isUnconditional()) return 0;
1876   }
1877
1878   // Okay, we can do the transformation: create the new PHI node.
1879   PHINode *NewPN = new PHINode(I.getType(), "");
1880   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1881   InsertNewInstBefore(NewPN, *PN);
1882   NewPN->takeName(PN);
1883
1884   // Next, add all of the operands to the PHI.
1885   if (I.getNumOperands() == 2) {
1886     Constant *C = cast<Constant>(I.getOperand(1));
1887     for (unsigned i = 0; i != NumPHIValues; ++i) {
1888       Value *InV;
1889       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1890         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1891           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1892         else
1893           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1894       } else {
1895         assert(PN->getIncomingBlock(i) == NonConstBB);
1896         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1897           InV = BinaryOperator::create(BO->getOpcode(),
1898                                        PN->getIncomingValue(i), C, "phitmp",
1899                                        NonConstBB->getTerminator());
1900         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1901           InV = CmpInst::create(CI->getOpcode(), 
1902                                 CI->getPredicate(),
1903                                 PN->getIncomingValue(i), C, "phitmp",
1904                                 NonConstBB->getTerminator());
1905         else
1906           assert(0 && "Unknown binop!");
1907         
1908         AddToWorkList(cast<Instruction>(InV));
1909       }
1910       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1911     }
1912   } else { 
1913     CastInst *CI = cast<CastInst>(&I);
1914     const Type *RetTy = CI->getType();
1915     for (unsigned i = 0; i != NumPHIValues; ++i) {
1916       Value *InV;
1917       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1918         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1919       } else {
1920         assert(PN->getIncomingBlock(i) == NonConstBB);
1921         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1922                                I.getType(), "phitmp", 
1923                                NonConstBB->getTerminator());
1924         AddToWorkList(cast<Instruction>(InV));
1925       }
1926       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1927     }
1928   }
1929   return ReplaceInstUsesWith(I, NewPN);
1930 }
1931
1932 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1933   bool Changed = SimplifyCommutative(I);
1934   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1935
1936   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1937     // X + undef -> undef
1938     if (isa<UndefValue>(RHS))
1939       return ReplaceInstUsesWith(I, RHS);
1940
1941     // X + 0 --> X
1942     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1943       if (RHSC->isNullValue())
1944         return ReplaceInstUsesWith(I, LHS);
1945     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1946       if (CFP->isExactlyValue(-0.0))
1947         return ReplaceInstUsesWith(I, LHS);
1948     }
1949
1950     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1951       // X + (signbit) --> X ^ signbit
1952       const APInt& Val = CI->getValue();
1953       uint32_t BitWidth = Val.getBitWidth();
1954       if (Val == APInt::getSignBit(BitWidth))
1955         return BinaryOperator::createXor(LHS, RHS);
1956       
1957       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1958       // (X & 254)+1 -> (X&254)|1
1959       if (!isa<VectorType>(I.getType())) {
1960         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1961         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1962                                  KnownZero, KnownOne))
1963           return &I;
1964       }
1965     }
1966
1967     if (isa<PHINode>(LHS))
1968       if (Instruction *NV = FoldOpIntoPhi(I))
1969         return NV;
1970     
1971     ConstantInt *XorRHS = 0;
1972     Value *XorLHS = 0;
1973     if (isa<ConstantInt>(RHSC) &&
1974         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1975       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1976       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1977       
1978       uint32_t Size = TySizeBits / 2;
1979       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1980       APInt CFF80Val(-C0080Val);
1981       do {
1982         if (TySizeBits > Size) {
1983           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1984           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1985           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1986               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1987             // This is a sign extend if the top bits are known zero.
1988             if (!MaskedValueIsZero(XorLHS, 
1989                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1990               Size = 0;  // Not a sign ext, but can't be any others either.
1991             break;
1992           }
1993         }
1994         Size >>= 1;
1995         C0080Val = APIntOps::lshr(C0080Val, Size);
1996         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1997       } while (Size >= 1);
1998       
1999       // FIXME: This shouldn't be necessary. When the backends can handle types
2000       // with funny bit widths then this whole cascade of if statements should
2001       // be removed. It is just here to get the size of the "middle" type back
2002       // up to something that the back ends can handle.
2003       const Type *MiddleType = 0;
2004       switch (Size) {
2005         default: break;
2006         case 32: MiddleType = Type::Int32Ty; break;
2007         case 16: MiddleType = Type::Int16Ty; break;
2008         case  8: MiddleType = Type::Int8Ty; break;
2009       }
2010       if (MiddleType) {
2011         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2012         InsertNewInstBefore(NewTrunc, I);
2013         return new SExtInst(NewTrunc, I.getType(), I.getName());
2014       }
2015     }
2016   }
2017
2018   // X + X --> X << 1
2019   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2020     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2021
2022     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2023       if (RHSI->getOpcode() == Instruction::Sub)
2024         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2025           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2026     }
2027     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2028       if (LHSI->getOpcode() == Instruction::Sub)
2029         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2030           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2031     }
2032   }
2033
2034   // -A + B  -->  B - A
2035   if (Value *V = dyn_castNegVal(LHS))
2036     return BinaryOperator::createSub(RHS, V);
2037
2038   // A + -B  -->  A - B
2039   if (!isa<Constant>(RHS))
2040     if (Value *V = dyn_castNegVal(RHS))
2041       return BinaryOperator::createSub(LHS, V);
2042
2043
2044   ConstantInt *C2;
2045   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2046     if (X == RHS)   // X*C + X --> X * (C+1)
2047       return BinaryOperator::createMul(RHS, AddOne(C2));
2048
2049     // X*C1 + X*C2 --> X * (C1+C2)
2050     ConstantInt *C1;
2051     if (X == dyn_castFoldableMul(RHS, C1))
2052       return BinaryOperator::createMul(X, Add(C1, C2));
2053   }
2054
2055   // X + X*C --> X * (C+1)
2056   if (dyn_castFoldableMul(RHS, C2) == LHS)
2057     return BinaryOperator::createMul(LHS, AddOne(C2));
2058
2059   // X + ~X --> -1   since   ~X = -X-1
2060   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2061     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2062   
2063
2064   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2065   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2066     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2067       return R;
2068
2069   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2070     Value *X = 0;
2071     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2072       return BinaryOperator::createSub(SubOne(CRHS), X);
2073
2074     // (X & FF00) + xx00  -> (X+xx00) & FF00
2075     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2076       Constant *Anded = And(CRHS, C2);
2077       if (Anded == CRHS) {
2078         // See if all bits from the first bit set in the Add RHS up are included
2079         // in the mask.  First, get the rightmost bit.
2080         const APInt& AddRHSV = CRHS->getValue();
2081
2082         // Form a mask of all bits from the lowest bit added through the top.
2083         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2084
2085         // See if the and mask includes all of these bits.
2086         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2087
2088         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2089           // Okay, the xform is safe.  Insert the new add pronto.
2090           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2091                                                             LHS->getName()), I);
2092           return BinaryOperator::createAnd(NewAdd, C2);
2093         }
2094       }
2095     }
2096
2097     // Try to fold constant add into select arguments.
2098     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2099       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2100         return R;
2101   }
2102
2103   // add (cast *A to intptrtype) B -> 
2104   //   cast (GEP (cast *A to sbyte*) B) -> 
2105   //     intptrtype
2106   {
2107     CastInst *CI = dyn_cast<CastInst>(LHS);
2108     Value *Other = RHS;
2109     if (!CI) {
2110       CI = dyn_cast<CastInst>(RHS);
2111       Other = LHS;
2112     }
2113     if (CI && CI->getType()->isSized() && 
2114         (CI->getType()->getPrimitiveSizeInBits() == 
2115          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2116         && isa<PointerType>(CI->getOperand(0)->getType())) {
2117       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2118                                    PointerType::get(Type::Int8Ty), I);
2119       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2120       return new PtrToIntInst(I2, CI->getType());
2121     }
2122   }
2123
2124   return Changed ? &I : 0;
2125 }
2126
2127 // isSignBit - Return true if the value represented by the constant only has the
2128 // highest order bit set.
2129 static bool isSignBit(ConstantInt *CI) {
2130   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2131   return CI->getValue() == APInt::getSignBit(NumBits);
2132 }
2133
2134 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2135   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2136
2137   if (Op0 == Op1)         // sub X, X  -> 0
2138     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2139
2140   // If this is a 'B = x-(-A)', change to B = x+A...
2141   if (Value *V = dyn_castNegVal(Op1))
2142     return BinaryOperator::createAdd(Op0, V);
2143
2144   if (isa<UndefValue>(Op0))
2145     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2146   if (isa<UndefValue>(Op1))
2147     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2148
2149   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2150     // Replace (-1 - A) with (~A)...
2151     if (C->isAllOnesValue())
2152       return BinaryOperator::createNot(Op1);
2153
2154     // C - ~X == X + (1+C)
2155     Value *X = 0;
2156     if (match(Op1, m_Not(m_Value(X))))
2157       return BinaryOperator::createAdd(X, AddOne(C));
2158
2159     // -(X >>u 31) -> (X >>s 31)
2160     // -(X >>s 31) -> (X >>u 31)
2161     if (C->isZero()) {
2162       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2163         if (SI->getOpcode() == Instruction::LShr) {
2164           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2165             // Check to see if we are shifting out everything but the sign bit.
2166             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2167                 SI->getType()->getPrimitiveSizeInBits()-1) {
2168               // Ok, the transformation is safe.  Insert AShr.
2169               return BinaryOperator::create(Instruction::AShr, 
2170                                           SI->getOperand(0), CU, SI->getName());
2171             }
2172           }
2173         }
2174         else if (SI->getOpcode() == Instruction::AShr) {
2175           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2176             // Check to see if we are shifting out everything but the sign bit.
2177             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2178                 SI->getType()->getPrimitiveSizeInBits()-1) {
2179               // Ok, the transformation is safe.  Insert LShr. 
2180               return BinaryOperator::createLShr(
2181                                           SI->getOperand(0), CU, SI->getName());
2182             }
2183           }
2184         } 
2185     }
2186
2187     // Try to fold constant sub into select arguments.
2188     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2189       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2190         return R;
2191
2192     if (isa<PHINode>(Op0))
2193       if (Instruction *NV = FoldOpIntoPhi(I))
2194         return NV;
2195   }
2196
2197   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2198     if (Op1I->getOpcode() == Instruction::Add &&
2199         !Op0->getType()->isFPOrFPVector()) {
2200       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2201         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2202       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2203         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2204       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2205         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2206           // C1-(X+C2) --> (C1-C2)-X
2207           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2208                                            Op1I->getOperand(0));
2209       }
2210     }
2211
2212     if (Op1I->hasOneUse()) {
2213       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2214       // is not used by anyone else...
2215       //
2216       if (Op1I->getOpcode() == Instruction::Sub &&
2217           !Op1I->getType()->isFPOrFPVector()) {
2218         // Swap the two operands of the subexpr...
2219         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2220         Op1I->setOperand(0, IIOp1);
2221         Op1I->setOperand(1, IIOp0);
2222
2223         // Create the new top level add instruction...
2224         return BinaryOperator::createAdd(Op0, Op1);
2225       }
2226
2227       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2228       //
2229       if (Op1I->getOpcode() == Instruction::And &&
2230           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2231         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2232
2233         Value *NewNot =
2234           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2235         return BinaryOperator::createAnd(Op0, NewNot);
2236       }
2237
2238       // 0 - (X sdiv C)  -> (X sdiv -C)
2239       if (Op1I->getOpcode() == Instruction::SDiv)
2240         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2241           if (CSI->isZero())
2242             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2243               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2244                                                ConstantExpr::getNeg(DivRHS));
2245
2246       // X - X*C --> X * (1-C)
2247       ConstantInt *C2 = 0;
2248       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2249         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2250         return BinaryOperator::createMul(Op0, CP1);
2251       }
2252     }
2253   }
2254
2255   if (!Op0->getType()->isFPOrFPVector())
2256     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2257       if (Op0I->getOpcode() == Instruction::Add) {
2258         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2259           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2260         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2261           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2262       } else if (Op0I->getOpcode() == Instruction::Sub) {
2263         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2264           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2265       }
2266
2267   ConstantInt *C1;
2268   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2269     if (X == Op1)  // X*C - X --> X * (C-1)
2270       return BinaryOperator::createMul(Op1, SubOne(C1));
2271
2272     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2273     if (X == dyn_castFoldableMul(Op1, C2))
2274       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2275   }
2276   return 0;
2277 }
2278
2279 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2280 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2281 /// TrueIfSigned if the result of the comparison is true when the input value is
2282 /// signed.
2283 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2284                            bool &TrueIfSigned) {
2285   switch (pred) {
2286   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2287     TrueIfSigned = true;
2288     return RHS->isZero();
2289   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2290     TrueIfSigned = true;
2291     return RHS->isAllOnesValue();
2292   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2293     TrueIfSigned = false;
2294     return RHS->isAllOnesValue();
2295   case ICmpInst::ICMP_UGT:
2296     // True if LHS u> RHS and RHS == high-bit-mask - 1
2297     TrueIfSigned = true;
2298     return RHS->getValue() ==
2299       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2300   case ICmpInst::ICMP_UGE: 
2301     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2302     TrueIfSigned = true;
2303     return RHS->getValue() == 
2304       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2305   default:
2306     return false;
2307   }
2308 }
2309
2310 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2311   bool Changed = SimplifyCommutative(I);
2312   Value *Op0 = I.getOperand(0);
2313
2314   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2315     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2316
2317   // Simplify mul instructions with a constant RHS...
2318   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2319     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2320
2321       // ((X << C1)*C2) == (X * (C2 << C1))
2322       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2323         if (SI->getOpcode() == Instruction::Shl)
2324           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2325             return BinaryOperator::createMul(SI->getOperand(0),
2326                                              ConstantExpr::getShl(CI, ShOp));
2327
2328       if (CI->isZero())
2329         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2330       if (CI->equalsInt(1))                  // X * 1  == X
2331         return ReplaceInstUsesWith(I, Op0);
2332       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2333         return BinaryOperator::createNeg(Op0, I.getName());
2334
2335       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2336       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2337         return BinaryOperator::createShl(Op0,
2338                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2339       }
2340     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2341       if (Op1F->isNullValue())
2342         return ReplaceInstUsesWith(I, Op1);
2343
2344       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2345       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2346       if (Op1F->getValue() == 1.0)
2347         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2348     }
2349     
2350     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2351       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2352           isa<ConstantInt>(Op0I->getOperand(1))) {
2353         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2354         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2355                                                      Op1, "tmp");
2356         InsertNewInstBefore(Add, I);
2357         Value *C1C2 = ConstantExpr::getMul(Op1, 
2358                                            cast<Constant>(Op0I->getOperand(1)));
2359         return BinaryOperator::createAdd(Add, C1C2);
2360         
2361       }
2362
2363     // Try to fold constant mul into select arguments.
2364     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2365       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2366         return R;
2367
2368     if (isa<PHINode>(Op0))
2369       if (Instruction *NV = FoldOpIntoPhi(I))
2370         return NV;
2371   }
2372
2373   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2374     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2375       return BinaryOperator::createMul(Op0v, Op1v);
2376
2377   // If one of the operands of the multiply is a cast from a boolean value, then
2378   // we know the bool is either zero or one, so this is a 'masking' multiply.
2379   // See if we can simplify things based on how the boolean was originally
2380   // formed.
2381   CastInst *BoolCast = 0;
2382   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2383     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2384       BoolCast = CI;
2385   if (!BoolCast)
2386     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2387       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2388         BoolCast = CI;
2389   if (BoolCast) {
2390     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2391       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2392       const Type *SCOpTy = SCIOp0->getType();
2393       bool TIS = false;
2394       
2395       // If the icmp is true iff the sign bit of X is set, then convert this
2396       // multiply into a shift/and combination.
2397       if (isa<ConstantInt>(SCIOp1) &&
2398           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2399           TIS) {
2400         // Shift the X value right to turn it into "all signbits".
2401         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2402                                           SCOpTy->getPrimitiveSizeInBits()-1);
2403         Value *V =
2404           InsertNewInstBefore(
2405             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2406                                             BoolCast->getOperand(0)->getName()+
2407                                             ".mask"), I);
2408
2409         // If the multiply type is not the same as the source type, sign extend
2410         // or truncate to the multiply type.
2411         if (I.getType() != V->getType()) {
2412           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2413           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2414           Instruction::CastOps opcode = 
2415             (SrcBits == DstBits ? Instruction::BitCast : 
2416              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2417           V = InsertCastBefore(opcode, V, I.getType(), I);
2418         }
2419
2420         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2421         return BinaryOperator::createAnd(V, OtherOp);
2422       }
2423     }
2424   }
2425
2426   return Changed ? &I : 0;
2427 }
2428
2429 /// This function implements the transforms on div instructions that work
2430 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2431 /// used by the visitors to those instructions.
2432 /// @brief Transforms common to all three div instructions
2433 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2434   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2435
2436   // undef / X -> 0
2437   if (isa<UndefValue>(Op0))
2438     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2439
2440   // X / undef -> undef
2441   if (isa<UndefValue>(Op1))
2442     return ReplaceInstUsesWith(I, Op1);
2443
2444   // Handle cases involving: div X, (select Cond, Y, Z)
2445   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2446     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2447     // same basic block, then we replace the select with Y, and the condition 
2448     // of the select with false (if the cond value is in the same BB).  If the
2449     // select has uses other than the div, this allows them to be simplified
2450     // also. Note that div X, Y is just as good as div X, 0 (undef)
2451     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2452       if (ST->isNullValue()) {
2453         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2454         if (CondI && CondI->getParent() == I.getParent())
2455           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2456         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2457           I.setOperand(1, SI->getOperand(2));
2458         else
2459           UpdateValueUsesWith(SI, SI->getOperand(2));
2460         return &I;
2461       }
2462
2463     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2464     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2465       if (ST->isNullValue()) {
2466         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2467         if (CondI && CondI->getParent() == I.getParent())
2468           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2469         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2470           I.setOperand(1, SI->getOperand(1));
2471         else
2472           UpdateValueUsesWith(SI, SI->getOperand(1));
2473         return &I;
2474       }
2475   }
2476
2477   return 0;
2478 }
2479
2480 /// This function implements the transforms common to both integer division
2481 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2482 /// division instructions.
2483 /// @brief Common integer divide transforms
2484 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2485   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2486
2487   if (Instruction *Common = commonDivTransforms(I))
2488     return Common;
2489
2490   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2491     // div X, 1 == X
2492     if (RHS->equalsInt(1))
2493       return ReplaceInstUsesWith(I, Op0);
2494
2495     // (X / C1) / C2  -> X / (C1*C2)
2496     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2497       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2498         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2499           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2500                                         Multiply(RHS, LHSRHS));
2501         }
2502
2503     if (!RHS->isZero()) { // avoid X udiv 0
2504       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2505         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2506           return R;
2507       if (isa<PHINode>(Op0))
2508         if (Instruction *NV = FoldOpIntoPhi(I))
2509           return NV;
2510     }
2511   }
2512
2513   // 0 / X == 0, we don't need to preserve faults!
2514   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2515     if (LHS->equalsInt(0))
2516       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
2518   return 0;
2519 }
2520
2521 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2522   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2523
2524   // Handle the integer div common cases
2525   if (Instruction *Common = commonIDivTransforms(I))
2526     return Common;
2527
2528   // X udiv C^2 -> X >> C
2529   // Check to see if this is an unsigned division with an exact power of 2,
2530   // if so, convert to a right shift.
2531   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2532     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2533       return BinaryOperator::createLShr(Op0, 
2534                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2535   }
2536
2537   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2538   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2539     if (RHSI->getOpcode() == Instruction::Shl &&
2540         isa<ConstantInt>(RHSI->getOperand(0))) {
2541       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2542       if (C1.isPowerOf2()) {
2543         Value *N = RHSI->getOperand(1);
2544         const Type *NTy = N->getType();
2545         if (uint32_t C2 = C1.logBase2()) {
2546           Constant *C2V = ConstantInt::get(NTy, C2);
2547           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2548         }
2549         return BinaryOperator::createLShr(Op0, N);
2550       }
2551     }
2552   }
2553   
2554   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2555   // where C1&C2 are powers of two.
2556   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2557     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2558       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2559         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2560         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2561           // Compute the shift amounts
2562           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2563           // Construct the "on true" case of the select
2564           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2565           Instruction *TSI = BinaryOperator::createLShr(
2566                                                  Op0, TC, SI->getName()+".t");
2567           TSI = InsertNewInstBefore(TSI, I);
2568   
2569           // Construct the "on false" case of the select
2570           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2571           Instruction *FSI = BinaryOperator::createLShr(
2572                                                  Op0, FC, SI->getName()+".f");
2573           FSI = InsertNewInstBefore(FSI, I);
2574
2575           // construct the select instruction and return it.
2576           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2577         }
2578       }
2579   return 0;
2580 }
2581
2582 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2583   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2584
2585   // Handle the integer div common cases
2586   if (Instruction *Common = commonIDivTransforms(I))
2587     return Common;
2588
2589   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2590     // sdiv X, -1 == -X
2591     if (RHS->isAllOnesValue())
2592       return BinaryOperator::createNeg(Op0);
2593
2594     // -X/C -> X/-C
2595     if (Value *LHSNeg = dyn_castNegVal(Op0))
2596       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2597   }
2598
2599   // If the sign bits of both operands are zero (i.e. we can prove they are
2600   // unsigned inputs), turn this into a udiv.
2601   if (I.getType()->isInteger()) {
2602     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2603     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2604       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2605     }
2606   }      
2607   
2608   return 0;
2609 }
2610
2611 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2612   return commonDivTransforms(I);
2613 }
2614
2615 /// GetFactor - If we can prove that the specified value is at least a multiple
2616 /// of some factor, return that factor.
2617 static Constant *GetFactor(Value *V) {
2618   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2619     return CI;
2620   
2621   // Unless we can be tricky, we know this is a multiple of 1.
2622   Constant *Result = ConstantInt::get(V->getType(), 1);
2623   
2624   Instruction *I = dyn_cast<Instruction>(V);
2625   if (!I) return Result;
2626   
2627   if (I->getOpcode() == Instruction::Mul) {
2628     // Handle multiplies by a constant, etc.
2629     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2630                                 GetFactor(I->getOperand(1)));
2631   } else if (I->getOpcode() == Instruction::Shl) {
2632     // (X<<C) -> X * (1 << C)
2633     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2634       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2635       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2636     }
2637   } else if (I->getOpcode() == Instruction::And) {
2638     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2639       // X & 0xFFF0 is known to be a multiple of 16.
2640       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2641       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2642         return ConstantExpr::getShl(Result, 
2643                                     ConstantInt::get(Result->getType(), Zeros));
2644     }
2645   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2646     // Only handle int->int casts.
2647     if (!CI->isIntegerCast())
2648       return Result;
2649     Value *Op = CI->getOperand(0);
2650     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2651   }    
2652   return Result;
2653 }
2654
2655 /// This function implements the transforms on rem instructions that work
2656 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2657 /// is used by the visitors to those instructions.
2658 /// @brief Transforms common to all three rem instructions
2659 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2660   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2661
2662   // 0 % X == 0, we don't need to preserve faults!
2663   if (Constant *LHS = dyn_cast<Constant>(Op0))
2664     if (LHS->isNullValue())
2665       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2666
2667   if (isa<UndefValue>(Op0))              // undef % X -> 0
2668     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2669   if (isa<UndefValue>(Op1))
2670     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2671
2672   // Handle cases involving: rem X, (select Cond, Y, Z)
2673   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2674     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2675     // the same basic block, then we replace the select with Y, and the
2676     // condition of the select with false (if the cond value is in the same
2677     // BB).  If the select has uses other than the div, this allows them to be
2678     // simplified also.
2679     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2680       if (ST->isNullValue()) {
2681         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2682         if (CondI && CondI->getParent() == I.getParent())
2683           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2684         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2685           I.setOperand(1, SI->getOperand(2));
2686         else
2687           UpdateValueUsesWith(SI, SI->getOperand(2));
2688         return &I;
2689       }
2690     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2691     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2692       if (ST->isNullValue()) {
2693         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2694         if (CondI && CondI->getParent() == I.getParent())
2695           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2696         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2697           I.setOperand(1, SI->getOperand(1));
2698         else
2699           UpdateValueUsesWith(SI, SI->getOperand(1));
2700         return &I;
2701       }
2702   }
2703
2704   return 0;
2705 }
2706
2707 /// This function implements the transforms common to both integer remainder
2708 /// instructions (urem and srem). It is called by the visitors to those integer
2709 /// remainder instructions.
2710 /// @brief Common integer remainder transforms
2711 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2712   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2713
2714   if (Instruction *common = commonRemTransforms(I))
2715     return common;
2716
2717   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2718     // X % 0 == undef, we don't need to preserve faults!
2719     if (RHS->equalsInt(0))
2720       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2721     
2722     if (RHS->equalsInt(1))  // X % 1 == 0
2723       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2724
2725     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2726       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2727         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2728           return R;
2729       } else if (isa<PHINode>(Op0I)) {
2730         if (Instruction *NV = FoldOpIntoPhi(I))
2731           return NV;
2732       }
2733       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2734       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2735         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2736     }
2737   }
2738
2739   return 0;
2740 }
2741
2742 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2743   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2744
2745   if (Instruction *common = commonIRemTransforms(I))
2746     return common;
2747   
2748   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2749     // X urem C^2 -> X and C
2750     // Check to see if this is an unsigned remainder with an exact power of 2,
2751     // if so, convert to a bitwise and.
2752     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2753       if (C->getValue().isPowerOf2())
2754         return BinaryOperator::createAnd(Op0, SubOne(C));
2755   }
2756
2757   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2758     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2759     if (RHSI->getOpcode() == Instruction::Shl &&
2760         isa<ConstantInt>(RHSI->getOperand(0))) {
2761       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2762         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2763         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2764                                                                    "tmp"), I);
2765         return BinaryOperator::createAnd(Op0, Add);
2766       }
2767     }
2768   }
2769
2770   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2771   // where C1&C2 are powers of two.
2772   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2773     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2774       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2775         // STO == 0 and SFO == 0 handled above.
2776         if ((STO->getValue().isPowerOf2()) && 
2777             (SFO->getValue().isPowerOf2())) {
2778           Value *TrueAnd = InsertNewInstBefore(
2779             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2780           Value *FalseAnd = InsertNewInstBefore(
2781             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2782           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2783         }
2784       }
2785   }
2786   
2787   return 0;
2788 }
2789
2790 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2791   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2792
2793   if (Instruction *common = commonIRemTransforms(I))
2794     return common;
2795   
2796   if (Value *RHSNeg = dyn_castNegVal(Op1))
2797     if (!isa<ConstantInt>(RHSNeg) || 
2798         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2799       // X % -Y -> X % Y
2800       AddUsesToWorkList(I);
2801       I.setOperand(1, RHSNeg);
2802       return &I;
2803     }
2804  
2805   // If the top bits of both operands are zero (i.e. we can prove they are
2806   // unsigned inputs), turn this into a urem.
2807   APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2808   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2809     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2810     return BinaryOperator::createURem(Op0, Op1, I.getName());
2811   }
2812
2813   return 0;
2814 }
2815
2816 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2817   return commonRemTransforms(I);
2818 }
2819
2820 // isMaxValueMinusOne - return true if this is Max-1
2821 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2822   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2823   if (!isSigned)
2824     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2825   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2826 }
2827
2828 // isMinValuePlusOne - return true if this is Min+1
2829 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2830   if (!isSigned)
2831     return C->getValue() == 1; // unsigned
2832     
2833   // Calculate 1111111111000000000000
2834   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2835   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2836 }
2837
2838 // isOneBitSet - Return true if there is exactly one bit set in the specified
2839 // constant.
2840 static bool isOneBitSet(const ConstantInt *CI) {
2841   return CI->getValue().isPowerOf2();
2842 }
2843
2844 // isHighOnes - Return true if the constant is of the form 1+0+.
2845 // This is the same as lowones(~X).
2846 static bool isHighOnes(const ConstantInt *CI) {
2847   return (~CI->getValue() + 1).isPowerOf2();
2848 }
2849
2850 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2851 /// are carefully arranged to allow folding of expressions such as:
2852 ///
2853 ///      (A < B) | (A > B) --> (A != B)
2854 ///
2855 /// Note that this is only valid if the first and second predicates have the
2856 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2857 ///
2858 /// Three bits are used to represent the condition, as follows:
2859 ///   0  A > B
2860 ///   1  A == B
2861 ///   2  A < B
2862 ///
2863 /// <=>  Value  Definition
2864 /// 000     0   Always false
2865 /// 001     1   A >  B
2866 /// 010     2   A == B
2867 /// 011     3   A >= B
2868 /// 100     4   A <  B
2869 /// 101     5   A != B
2870 /// 110     6   A <= B
2871 /// 111     7   Always true
2872 ///  
2873 static unsigned getICmpCode(const ICmpInst *ICI) {
2874   switch (ICI->getPredicate()) {
2875     // False -> 0
2876   case ICmpInst::ICMP_UGT: return 1;  // 001
2877   case ICmpInst::ICMP_SGT: return 1;  // 001
2878   case ICmpInst::ICMP_EQ:  return 2;  // 010
2879   case ICmpInst::ICMP_UGE: return 3;  // 011
2880   case ICmpInst::ICMP_SGE: return 3;  // 011
2881   case ICmpInst::ICMP_ULT: return 4;  // 100
2882   case ICmpInst::ICMP_SLT: return 4;  // 100
2883   case ICmpInst::ICMP_NE:  return 5;  // 101
2884   case ICmpInst::ICMP_ULE: return 6;  // 110
2885   case ICmpInst::ICMP_SLE: return 6;  // 110
2886     // True -> 7
2887   default:
2888     assert(0 && "Invalid ICmp predicate!");
2889     return 0;
2890   }
2891 }
2892
2893 /// getICmpValue - This is the complement of getICmpCode, which turns an
2894 /// opcode and two operands into either a constant true or false, or a brand 
2895 /// new /// ICmp instruction. The sign is passed in to determine which kind
2896 /// of predicate to use in new icmp instructions.
2897 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2898   switch (code) {
2899   default: assert(0 && "Illegal ICmp code!");
2900   case  0: return ConstantInt::getFalse();
2901   case  1: 
2902     if (sign)
2903       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2904     else
2905       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2906   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2907   case  3: 
2908     if (sign)
2909       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2910     else
2911       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2912   case  4: 
2913     if (sign)
2914       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2915     else
2916       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2917   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2918   case  6: 
2919     if (sign)
2920       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2921     else
2922       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2923   case  7: return ConstantInt::getTrue();
2924   }
2925 }
2926
2927 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2928   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2929     (ICmpInst::isSignedPredicate(p1) && 
2930      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2931     (ICmpInst::isSignedPredicate(p2) && 
2932      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2933 }
2934
2935 namespace { 
2936 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2937 struct FoldICmpLogical {
2938   InstCombiner &IC;
2939   Value *LHS, *RHS;
2940   ICmpInst::Predicate pred;
2941   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2942     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2943       pred(ICI->getPredicate()) {}
2944   bool shouldApply(Value *V) const {
2945     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2946       if (PredicatesFoldable(pred, ICI->getPredicate()))
2947         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2948                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2949     return false;
2950   }
2951   Instruction *apply(Instruction &Log) const {
2952     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2953     if (ICI->getOperand(0) != LHS) {
2954       assert(ICI->getOperand(1) == LHS);
2955       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2956     }
2957
2958     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2959     unsigned LHSCode = getICmpCode(ICI);
2960     unsigned RHSCode = getICmpCode(RHSICI);
2961     unsigned Code;
2962     switch (Log.getOpcode()) {
2963     case Instruction::And: Code = LHSCode & RHSCode; break;
2964     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2965     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2966     default: assert(0 && "Illegal logical opcode!"); return 0;
2967     }
2968
2969     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
2970                     ICmpInst::isSignedPredicate(ICI->getPredicate());
2971       
2972     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
2973     if (Instruction *I = dyn_cast<Instruction>(RV))
2974       return I;
2975     // Otherwise, it's a constant boolean value...
2976     return IC.ReplaceInstUsesWith(Log, RV);
2977   }
2978 };
2979 } // end anonymous namespace
2980
2981 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2982 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2983 // guaranteed to be a binary operator.
2984 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2985                                     ConstantInt *OpRHS,
2986                                     ConstantInt *AndRHS,
2987                                     BinaryOperator &TheAnd) {
2988   Value *X = Op->getOperand(0);
2989   Constant *Together = 0;
2990   if (!Op->isShift())
2991     Together = And(AndRHS, OpRHS);
2992
2993   switch (Op->getOpcode()) {
2994   case Instruction::Xor:
2995     if (Op->hasOneUse()) {
2996       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2997       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
2998       InsertNewInstBefore(And, TheAnd);
2999       And->takeName(Op);
3000       return BinaryOperator::createXor(And, Together);
3001     }
3002     break;
3003   case Instruction::Or:
3004     if (Together == AndRHS) // (X | C) & C --> C
3005       return ReplaceInstUsesWith(TheAnd, AndRHS);
3006
3007     if (Op->hasOneUse() && Together != OpRHS) {
3008       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3009       Instruction *Or = BinaryOperator::createOr(X, Together);
3010       InsertNewInstBefore(Or, TheAnd);
3011       Or->takeName(Op);
3012       return BinaryOperator::createAnd(Or, AndRHS);
3013     }
3014     break;
3015   case Instruction::Add:
3016     if (Op->hasOneUse()) {
3017       // Adding a one to a single bit bit-field should be turned into an XOR
3018       // of the bit.  First thing to check is to see if this AND is with a
3019       // single bit constant.
3020       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3021
3022       // If there is only one bit set...
3023       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3024         // Ok, at this point, we know that we are masking the result of the
3025         // ADD down to exactly one bit.  If the constant we are adding has
3026         // no bits set below this bit, then we can eliminate the ADD.
3027         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3028
3029         // Check to see if any bits below the one bit set in AndRHSV are set.
3030         if ((AddRHS & (AndRHSV-1)) == 0) {
3031           // If not, the only thing that can effect the output of the AND is
3032           // the bit specified by AndRHSV.  If that bit is set, the effect of
3033           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3034           // no effect.
3035           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3036             TheAnd.setOperand(0, X);
3037             return &TheAnd;
3038           } else {
3039             // Pull the XOR out of the AND.
3040             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3041             InsertNewInstBefore(NewAnd, TheAnd);
3042             NewAnd->takeName(Op);
3043             return BinaryOperator::createXor(NewAnd, AndRHS);
3044           }
3045         }
3046       }
3047     }
3048     break;
3049
3050   case Instruction::Shl: {
3051     // We know that the AND will not produce any of the bits shifted in, so if
3052     // the anded constant includes them, clear them now!
3053     //
3054     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3055     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3056     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3057     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3058
3059     if (CI->getValue() == ShlMask) { 
3060     // Masking out bits that the shift already masks
3061       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3062     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3063       TheAnd.setOperand(1, CI);
3064       return &TheAnd;
3065     }
3066     break;
3067   }
3068   case Instruction::LShr:
3069   {
3070     // We know that the AND will not produce any of the bits shifted in, so if
3071     // the anded constant includes them, clear them now!  This only applies to
3072     // unsigned shifts, because a signed shr may bring in set bits!
3073     //
3074     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3075     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3076     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3077     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3078
3079     if (CI->getValue() == ShrMask) {   
3080     // Masking out bits that the shift already masks.
3081       return ReplaceInstUsesWith(TheAnd, Op);
3082     } else if (CI != AndRHS) {
3083       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3084       return &TheAnd;
3085     }
3086     break;
3087   }
3088   case Instruction::AShr:
3089     // Signed shr.
3090     // See if this is shifting in some sign extension, then masking it out
3091     // with an and.
3092     if (Op->hasOneUse()) {
3093       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3094       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3095       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3096       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3097       if (C == AndRHS) {          // Masking out bits shifted in.
3098         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3099         // Make the argument unsigned.
3100         Value *ShVal = Op->getOperand(0);
3101         ShVal = InsertNewInstBefore(
3102             BinaryOperator::createLShr(ShVal, OpRHS, 
3103                                    Op->getName()), TheAnd);
3104         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3105       }
3106     }
3107     break;
3108   }
3109   return 0;
3110 }
3111
3112
3113 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3114 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3115 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3116 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3117 /// insert new instructions.
3118 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3119                                            bool isSigned, bool Inside, 
3120                                            Instruction &IB) {
3121   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3122             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3123          "Lo is not <= Hi in range emission code!");
3124     
3125   if (Inside) {
3126     if (Lo == Hi)  // Trivially false.
3127       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3128
3129     // V >= Min && V < Hi --> V < Hi
3130     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3131       ICmpInst::Predicate pred = (isSigned ? 
3132         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3133       return new ICmpInst(pred, V, Hi);
3134     }
3135
3136     // Emit V-Lo <u Hi-Lo
3137     Constant *NegLo = ConstantExpr::getNeg(Lo);
3138     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3139     InsertNewInstBefore(Add, IB);
3140     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3141     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3142   }
3143
3144   if (Lo == Hi)  // Trivially true.
3145     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3146
3147   // V < Min || V >= Hi -> V > Hi-1
3148   Hi = SubOne(cast<ConstantInt>(Hi));
3149   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3150     ICmpInst::Predicate pred = (isSigned ? 
3151         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3152     return new ICmpInst(pred, V, Hi);
3153   }
3154
3155   // Emit V-Lo >u Hi-1-Lo
3156   // Note that Hi has already had one subtracted from it, above.
3157   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3158   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3159   InsertNewInstBefore(Add, IB);
3160   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3161   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3162 }
3163
3164 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3165 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3166 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3167 // not, since all 1s are not contiguous.
3168 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3169   const APInt& V = Val->getValue();
3170   uint32_t BitWidth = Val->getType()->getBitWidth();
3171   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3172
3173   // look for the first zero bit after the run of ones
3174   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3175   // look for the first non-zero bit
3176   ME = V.getActiveBits(); 
3177   return true;
3178 }
3179
3180 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3181 /// where isSub determines whether the operator is a sub.  If we can fold one of
3182 /// the following xforms:
3183 /// 
3184 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3185 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3186 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3187 ///
3188 /// return (A +/- B).
3189 ///
3190 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3191                                         ConstantInt *Mask, bool isSub,
3192                                         Instruction &I) {
3193   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3194   if (!LHSI || LHSI->getNumOperands() != 2 ||
3195       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3196
3197   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3198
3199   switch (LHSI->getOpcode()) {
3200   default: return 0;
3201   case Instruction::And:
3202     if (And(N, Mask) == Mask) {
3203       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3204       if ((Mask->getValue().countLeadingZeros() + 
3205            Mask->getValue().countPopulation()) == 
3206           Mask->getValue().getBitWidth())
3207         break;
3208
3209       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3210       // part, we don't need any explicit masks to take them out of A.  If that
3211       // is all N is, ignore it.
3212       uint32_t MB = 0, ME = 0;
3213       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3214         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3215         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3216         if (MaskedValueIsZero(RHS, Mask))
3217           break;
3218       }
3219     }
3220     return 0;
3221   case Instruction::Or:
3222   case Instruction::Xor:
3223     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3224     if ((Mask->getValue().countLeadingZeros() + 
3225          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3226         && And(N, Mask)->isZero())
3227       break;
3228     return 0;
3229   }
3230   
3231   Instruction *New;
3232   if (isSub)
3233     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3234   else
3235     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3236   return InsertNewInstBefore(New, I);
3237 }
3238
3239 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3240   bool Changed = SimplifyCommutative(I);
3241   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
3243   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3244     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3245
3246   // and X, X = X
3247   if (Op0 == Op1)
3248     return ReplaceInstUsesWith(I, Op1);
3249
3250   // See if we can simplify any instructions used by the instruction whose sole 
3251   // purpose is to compute bits we don't care about.
3252   if (!isa<VectorType>(I.getType())) {
3253     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3254     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3255     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3256                              KnownZero, KnownOne))
3257       return &I;
3258   } else {
3259     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3260       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3261         return ReplaceInstUsesWith(I, I.getOperand(0));
3262     } else if (isa<ConstantAggregateZero>(Op1)) {
3263       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3264     }
3265   }
3266   
3267   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3268     const APInt& AndRHSMask = AndRHS->getValue();
3269     APInt NotAndRHS(~AndRHSMask);
3270
3271     // Optimize a variety of ((val OP C1) & C2) combinations...
3272     if (isa<BinaryOperator>(Op0)) {
3273       Instruction *Op0I = cast<Instruction>(Op0);
3274       Value *Op0LHS = Op0I->getOperand(0);
3275       Value *Op0RHS = Op0I->getOperand(1);
3276       switch (Op0I->getOpcode()) {
3277       case Instruction::Xor:
3278       case Instruction::Or:
3279         // If the mask is only needed on one incoming arm, push it up.
3280         if (Op0I->hasOneUse()) {
3281           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3282             // Not masking anything out for the LHS, move to RHS.
3283             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3284                                                    Op0RHS->getName()+".masked");
3285             InsertNewInstBefore(NewRHS, I);
3286             return BinaryOperator::create(
3287                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3288           }
3289           if (!isa<Constant>(Op0RHS) &&
3290               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3291             // Not masking anything out for the RHS, move to LHS.
3292             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3293                                                    Op0LHS->getName()+".masked");
3294             InsertNewInstBefore(NewLHS, I);
3295             return BinaryOperator::create(
3296                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3297           }
3298         }
3299
3300         break;
3301       case Instruction::Add:
3302         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3303         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3304         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3305         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3306           return BinaryOperator::createAnd(V, AndRHS);
3307         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3308           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3309         break;
3310
3311       case Instruction::Sub:
3312         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3313         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3314         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3315         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3316           return BinaryOperator::createAnd(V, AndRHS);
3317         break;
3318       }
3319
3320       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3321         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3322           return Res;
3323     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3324       // If this is an integer truncation or change from signed-to-unsigned, and
3325       // if the source is an and/or with immediate, transform it.  This
3326       // frequently occurs for bitfield accesses.
3327       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3328         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3329             CastOp->getNumOperands() == 2)
3330           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3331             if (CastOp->getOpcode() == Instruction::And) {
3332               // Change: and (cast (and X, C1) to T), C2
3333               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3334               // This will fold the two constants together, which may allow 
3335               // other simplifications.
3336               Instruction *NewCast = CastInst::createTruncOrBitCast(
3337                 CastOp->getOperand(0), I.getType(), 
3338                 CastOp->getName()+".shrunk");
3339               NewCast = InsertNewInstBefore(NewCast, I);
3340               // trunc_or_bitcast(C1)&C2
3341               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3342               C3 = ConstantExpr::getAnd(C3, AndRHS);
3343               return BinaryOperator::createAnd(NewCast, C3);
3344             } else if (CastOp->getOpcode() == Instruction::Or) {
3345               // Change: and (cast (or X, C1) to T), C2
3346               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3347               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3348               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3349                 return ReplaceInstUsesWith(I, AndRHS);
3350             }
3351       }
3352     }
3353
3354     // Try to fold constant and into select arguments.
3355     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3356       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3357         return R;
3358     if (isa<PHINode>(Op0))
3359       if (Instruction *NV = FoldOpIntoPhi(I))
3360         return NV;
3361   }
3362
3363   Value *Op0NotVal = dyn_castNotVal(Op0);
3364   Value *Op1NotVal = dyn_castNotVal(Op1);
3365
3366   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3367     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3368
3369   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3370   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3371     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3372                                                I.getName()+".demorgan");
3373     InsertNewInstBefore(Or, I);
3374     return BinaryOperator::createNot(Or);
3375   }
3376   
3377   {
3378     Value *A = 0, *B = 0, *C = 0, *D = 0;
3379     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3380       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3381         return ReplaceInstUsesWith(I, Op1);
3382     
3383       // (A|B) & ~(A&B) -> A^B
3384       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3385         if ((A == C && B == D) || (A == D && B == C))
3386           return BinaryOperator::createXor(A, B);
3387       }
3388     }
3389     
3390     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3391       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3392         return ReplaceInstUsesWith(I, Op0);
3393
3394       // ~(A&B) & (A|B) -> A^B
3395       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3396         if ((A == C && B == D) || (A == D && B == C))
3397           return BinaryOperator::createXor(A, B);
3398       }
3399     }
3400     
3401     if (Op0->hasOneUse() &&
3402         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3403       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3404         I.swapOperands();     // Simplify below
3405         std::swap(Op0, Op1);
3406       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3407         cast<BinaryOperator>(Op0)->swapOperands();
3408         I.swapOperands();     // Simplify below
3409         std::swap(Op0, Op1);
3410       }
3411     }
3412     if (Op1->hasOneUse() &&
3413         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3414       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3415         cast<BinaryOperator>(Op1)->swapOperands();
3416         std::swap(A, B);
3417       }
3418       if (A == Op0) {                                // A&(A^B) -> A & ~B
3419         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3420         InsertNewInstBefore(NotB, I);
3421         return BinaryOperator::createAnd(A, NotB);
3422       }
3423     }
3424   }
3425   
3426   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3427     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3428     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3429       return R;
3430
3431     Value *LHSVal, *RHSVal;
3432     ConstantInt *LHSCst, *RHSCst;
3433     ICmpInst::Predicate LHSCC, RHSCC;
3434     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3435       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3436         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3437             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3438             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3439             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3440             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3441             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3442           // Ensure that the larger constant is on the RHS.
3443           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3444             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3445           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3446           ICmpInst *LHS = cast<ICmpInst>(Op0);
3447           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3448             std::swap(LHS, RHS);
3449             std::swap(LHSCst, RHSCst);
3450             std::swap(LHSCC, RHSCC);
3451           }
3452
3453           // At this point, we know we have have two icmp instructions
3454           // comparing a value against two constants and and'ing the result
3455           // together.  Because of the above check, we know that we only have
3456           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3457           // (from the FoldICmpLogical check above), that the two constants 
3458           // are not equal and that the larger constant is on the RHS
3459           assert(LHSCst != RHSCst && "Compares not folded above?");
3460
3461           switch (LHSCC) {
3462           default: assert(0 && "Unknown integer condition code!");
3463           case ICmpInst::ICMP_EQ:
3464             switch (RHSCC) {
3465             default: assert(0 && "Unknown integer condition code!");
3466             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3467             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3468             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3469               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3470             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3471             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3472             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3473               return ReplaceInstUsesWith(I, LHS);
3474             }
3475           case ICmpInst::ICMP_NE:
3476             switch (RHSCC) {
3477             default: assert(0 && "Unknown integer condition code!");
3478             case ICmpInst::ICMP_ULT:
3479               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3480                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3481               break;                        // (X != 13 & X u< 15) -> no change
3482             case ICmpInst::ICMP_SLT:
3483               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3484                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3485               break;                        // (X != 13 & X s< 15) -> no change
3486             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3487             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3488             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3489               return ReplaceInstUsesWith(I, RHS);
3490             case ICmpInst::ICMP_NE:
3491               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3492                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3493                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3494                                                       LHSVal->getName()+".off");
3495                 InsertNewInstBefore(Add, I);
3496                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3497                                     ConstantInt::get(Add->getType(), 1));
3498               }
3499               break;                        // (X != 13 & X != 15) -> no change
3500             }
3501             break;
3502           case ICmpInst::ICMP_ULT:
3503             switch (RHSCC) {
3504             default: assert(0 && "Unknown integer condition code!");
3505             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3506             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3507               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3508             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3509               break;
3510             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3511             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3512               return ReplaceInstUsesWith(I, LHS);
3513             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3514               break;
3515             }
3516             break;
3517           case ICmpInst::ICMP_SLT:
3518             switch (RHSCC) {
3519             default: assert(0 && "Unknown integer condition code!");
3520             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3521             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3522               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3523             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3524               break;
3525             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3526             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3527               return ReplaceInstUsesWith(I, LHS);
3528             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3529               break;
3530             }
3531             break;
3532           case ICmpInst::ICMP_UGT:
3533             switch (RHSCC) {
3534             default: assert(0 && "Unknown integer condition code!");
3535             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3536               return ReplaceInstUsesWith(I, LHS);
3537             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3538               return ReplaceInstUsesWith(I, RHS);
3539             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3540               break;
3541             case ICmpInst::ICMP_NE:
3542               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3543                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3544               break;                        // (X u> 13 & X != 15) -> no change
3545             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3546               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3547                                      true, I);
3548             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3549               break;
3550             }
3551             break;
3552           case ICmpInst::ICMP_SGT:
3553             switch (RHSCC) {
3554             default: assert(0 && "Unknown integer condition code!");
3555             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3556               return ReplaceInstUsesWith(I, LHS);
3557             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3558               return ReplaceInstUsesWith(I, RHS);
3559             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3560               break;
3561             case ICmpInst::ICMP_NE:
3562               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3563                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3564               break;                        // (X s> 13 & X != 15) -> no change
3565             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3566               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3567                                      true, I);
3568             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3569               break;
3570             }
3571             break;
3572           }
3573         }
3574   }
3575
3576   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3577   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3578     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3579       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3580         const Type *SrcTy = Op0C->getOperand(0)->getType();
3581         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3582             // Only do this if the casts both really cause code to be generated.
3583             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3584                               I.getType(), TD) &&
3585             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3586                               I.getType(), TD)) {
3587           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3588                                                          Op1C->getOperand(0),
3589                                                          I.getName());
3590           InsertNewInstBefore(NewOp, I);
3591           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3592         }
3593       }
3594     
3595   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3596   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3597     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3598       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3599           SI0->getOperand(1) == SI1->getOperand(1) &&
3600           (SI0->hasOneUse() || SI1->hasOneUse())) {
3601         Instruction *NewOp =
3602           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3603                                                         SI1->getOperand(0),
3604                                                         SI0->getName()), I);
3605         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3606                                       SI1->getOperand(1));
3607       }
3608   }
3609
3610   return Changed ? &I : 0;
3611 }
3612
3613 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3614 /// in the result.  If it does, and if the specified byte hasn't been filled in
3615 /// yet, fill it in and return false.
3616 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3617   Instruction *I = dyn_cast<Instruction>(V);
3618   if (I == 0) return true;
3619
3620   // If this is an or instruction, it is an inner node of the bswap.
3621   if (I->getOpcode() == Instruction::Or)
3622     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3623            CollectBSwapParts(I->getOperand(1), ByteValues);
3624   
3625   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3626   // If this is a shift by a constant int, and it is "24", then its operand
3627   // defines a byte.  We only handle unsigned types here.
3628   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3629     // Not shifting the entire input by N-1 bytes?
3630     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3631         8*(ByteValues.size()-1))
3632       return true;
3633     
3634     unsigned DestNo;
3635     if (I->getOpcode() == Instruction::Shl) {
3636       // X << 24 defines the top byte with the lowest of the input bytes.
3637       DestNo = ByteValues.size()-1;
3638     } else {
3639       // X >>u 24 defines the low byte with the highest of the input bytes.
3640       DestNo = 0;
3641     }
3642     
3643     // If the destination byte value is already defined, the values are or'd
3644     // together, which isn't a bswap (unless it's an or of the same bits).
3645     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3646       return true;
3647     ByteValues[DestNo] = I->getOperand(0);
3648     return false;
3649   }
3650   
3651   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3652   // don't have this.
3653   Value *Shift = 0, *ShiftLHS = 0;
3654   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3655   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3656       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3657     return true;
3658   Instruction *SI = cast<Instruction>(Shift);
3659
3660   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3661   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3662       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3663     return true;
3664   
3665   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3666   unsigned DestByte;
3667   if (AndAmt->getValue().getActiveBits() > 64)
3668     return true;
3669   uint64_t AndAmtVal = AndAmt->getZExtValue();
3670   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3671     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3672       break;
3673   // Unknown mask for bswap.
3674   if (DestByte == ByteValues.size()) return true;
3675   
3676   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3677   unsigned SrcByte;
3678   if (SI->getOpcode() == Instruction::Shl)
3679     SrcByte = DestByte - ShiftBytes;
3680   else
3681     SrcByte = DestByte + ShiftBytes;
3682   
3683   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3684   if (SrcByte != ByteValues.size()-DestByte-1)
3685     return true;
3686   
3687   // If the destination byte value is already defined, the values are or'd
3688   // together, which isn't a bswap (unless it's an or of the same bits).
3689   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3690     return true;
3691   ByteValues[DestByte] = SI->getOperand(0);
3692   return false;
3693 }
3694
3695 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3696 /// If so, insert the new bswap intrinsic and return it.
3697 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3698   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3699   if (!ITy || ITy->getBitWidth() % 16) 
3700     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3701   
3702   /// ByteValues - For each byte of the result, we keep track of which value
3703   /// defines each byte.
3704   SmallVector<Value*, 8> ByteValues;
3705   ByteValues.resize(ITy->getBitWidth()/8);
3706     
3707   // Try to find all the pieces corresponding to the bswap.
3708   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3709       CollectBSwapParts(I.getOperand(1), ByteValues))
3710     return 0;
3711   
3712   // Check to see if all of the bytes come from the same value.
3713   Value *V = ByteValues[0];
3714   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3715   
3716   // Check to make sure that all of the bytes come from the same value.
3717   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3718     if (ByteValues[i] != V)
3719       return 0;
3720   const Type *Tys[] = { ITy, ITy };
3721   Module *M = I.getParent()->getParent()->getParent();
3722   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
3723   return new CallInst(F, V);
3724 }
3725
3726
3727 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3728   bool Changed = SimplifyCommutative(I);
3729   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3730
3731   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3732     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3733
3734   // or X, X = X
3735   if (Op0 == Op1)
3736     return ReplaceInstUsesWith(I, Op0);
3737
3738   // See if we can simplify any instructions used by the instruction whose sole 
3739   // purpose is to compute bits we don't care about.
3740   if (!isa<VectorType>(I.getType())) {
3741     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3742     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3743     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3744                              KnownZero, KnownOne))
3745       return &I;
3746   } else if (isa<ConstantAggregateZero>(Op1)) {
3747     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3748   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3749     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3750       return ReplaceInstUsesWith(I, I.getOperand(1));
3751   }
3752     
3753
3754   
3755   // or X, -1 == -1
3756   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3757     ConstantInt *C1 = 0; Value *X = 0;
3758     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3759     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3760       Instruction *Or = BinaryOperator::createOr(X, RHS);
3761       InsertNewInstBefore(Or, I);
3762       Or->takeName(Op0);
3763       return BinaryOperator::createAnd(Or, 
3764                ConstantInt::get(RHS->getValue() | C1->getValue()));
3765     }
3766
3767     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3768     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3769       Instruction *Or = BinaryOperator::createOr(X, RHS);
3770       InsertNewInstBefore(Or, I);
3771       Or->takeName(Op0);
3772       return BinaryOperator::createXor(Or,
3773                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3774     }
3775
3776     // Try to fold constant and into select arguments.
3777     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3778       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3779         return R;
3780     if (isa<PHINode>(Op0))
3781       if (Instruction *NV = FoldOpIntoPhi(I))
3782         return NV;
3783   }
3784
3785   Value *A = 0, *B = 0;
3786   ConstantInt *C1 = 0, *C2 = 0;
3787
3788   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3789     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3790       return ReplaceInstUsesWith(I, Op1);
3791   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3792     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3793       return ReplaceInstUsesWith(I, Op0);
3794
3795   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3796   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3797   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3798       match(Op1, m_Or(m_Value(), m_Value())) ||
3799       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3800        match(Op1, m_Shift(m_Value(), m_Value())))) {
3801     if (Instruction *BSwap = MatchBSwap(I))
3802       return BSwap;
3803   }
3804   
3805   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3806   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3807       MaskedValueIsZero(Op1, C1->getValue())) {
3808     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3809     InsertNewInstBefore(NOr, I);
3810     NOr->takeName(Op0);
3811     return BinaryOperator::createXor(NOr, C1);
3812   }
3813
3814   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3815   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3816       MaskedValueIsZero(Op0, C1->getValue())) {
3817     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3818     InsertNewInstBefore(NOr, I);
3819     NOr->takeName(Op0);
3820     return BinaryOperator::createXor(NOr, C1);
3821   }
3822
3823   // (A & C)|(B & D)
3824   Value *C = 0, *D = 0;
3825   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3826       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3827     Value *V1 = 0, *V2 = 0, *V3 = 0;
3828     C1 = dyn_cast<ConstantInt>(C);
3829     C2 = dyn_cast<ConstantInt>(D);
3830     if (C1 && C2) {  // (A & C1)|(B & C2)
3831       // If we have: ((V + N) & C1) | (V & C2)
3832       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3833       // replace with V+N.
3834       if (C1->getValue() == ~C2->getValue()) {
3835         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3836             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3837           // Add commutes, try both ways.
3838           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3839             return ReplaceInstUsesWith(I, A);
3840           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3841             return ReplaceInstUsesWith(I, A);
3842         }
3843         // Or commutes, try both ways.
3844         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3845             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3846           // Add commutes, try both ways.
3847           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3848             return ReplaceInstUsesWith(I, B);
3849           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3850             return ReplaceInstUsesWith(I, B);
3851         }
3852       }
3853       V1 = 0; V2 = 0; V3 = 0;
3854     }
3855     
3856     // Check to see if we have any common things being and'ed.  If so, find the
3857     // terms for V1 & (V2|V3).
3858     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3859       if (A == B)      // (A & C)|(A & D) == A & (C|D)
3860         V1 = A, V2 = C, V3 = D;
3861       else if (A == D) // (A & C)|(B & A) == A & (B|C)
3862         V1 = A, V2 = B, V3 = C;
3863       else if (C == B) // (A & C)|(C & D) == C & (A|D)
3864         V1 = C, V2 = A, V3 = D;
3865       else if (C == D) // (A & C)|(B & C) == C & (A|B)
3866         V1 = C, V2 = A, V3 = B;
3867       
3868       if (V1) {
3869         Value *Or =
3870           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3871         return BinaryOperator::createAnd(V1, Or);
3872       }
3873       
3874       // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
3875       if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
3876         // Try all combination of terms to find V3 and ~V3.
3877         if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3878           if (V3 == B)
3879             V1 = D, V2 = C;
3880           else if (V3 == D)
3881             V1 = B, V2 = C;
3882         }
3883         if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3884           if (V3 == A)
3885             V1 = C, V2 = D;
3886           else if (V3 == C)
3887             V1 = A, V2 = D;
3888         }
3889         if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3890           if (V3 == B)
3891             V1 = D, V2 = A;
3892           else if (V3 == D)
3893             V1 = B, V2 = A;
3894         }
3895         if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3896           if (V3 == A)
3897             V1 = C, V2 = B;
3898           else if (V3 == C)
3899             V1 = A, V2 = B;
3900         }
3901         if (V1) {
3902           A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3903           A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3904           return BinaryOperator::createXor(A, V2);
3905         }
3906       }
3907     }
3908   }
3909   
3910   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3911   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3912     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3913       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3914           SI0->getOperand(1) == SI1->getOperand(1) &&
3915           (SI0->hasOneUse() || SI1->hasOneUse())) {
3916         Instruction *NewOp =
3917         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3918                                                      SI1->getOperand(0),
3919                                                      SI0->getName()), I);
3920         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3921                                       SI1->getOperand(1));
3922       }
3923   }
3924
3925   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3926     if (A == Op1)   // ~A | A == -1
3927       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3928   } else {
3929     A = 0;
3930   }
3931   // Note, A is still live here!
3932   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3933     if (Op0 == B)
3934       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3935
3936     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3937     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3938       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3939                                               I.getName()+".demorgan"), I);
3940       return BinaryOperator::createNot(And);
3941     }
3942   }
3943
3944   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3945   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3946     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3947       return R;
3948
3949     Value *LHSVal, *RHSVal;
3950     ConstantInt *LHSCst, *RHSCst;
3951     ICmpInst::Predicate LHSCC, RHSCC;
3952     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3953       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3954         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3955             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3956             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3957             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3958             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3959             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3960             // We can't fold (ugt x, C) | (sgt x, C2).
3961             PredicatesFoldable(LHSCC, RHSCC)) {
3962           // Ensure that the larger constant is on the RHS.
3963           ICmpInst *LHS = cast<ICmpInst>(Op0);
3964           bool NeedsSwap;
3965           if (ICmpInst::isSignedPredicate(LHSCC))
3966             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3967           else
3968             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3969             
3970           if (NeedsSwap) {
3971             std::swap(LHS, RHS);
3972             std::swap(LHSCst, RHSCst);
3973             std::swap(LHSCC, RHSCC);
3974           }
3975
3976           // At this point, we know we have have two icmp instructions
3977           // comparing a value against two constants and or'ing the result
3978           // together.  Because of the above check, we know that we only have
3979           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3980           // FoldICmpLogical check above), that the two constants are not
3981           // equal.
3982           assert(LHSCst != RHSCst && "Compares not folded above?");
3983
3984           switch (LHSCC) {
3985           default: assert(0 && "Unknown integer condition code!");
3986           case ICmpInst::ICMP_EQ:
3987             switch (RHSCC) {
3988             default: assert(0 && "Unknown integer condition code!");
3989             case ICmpInst::ICMP_EQ:
3990               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3991                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3992                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3993                                                       LHSVal->getName()+".off");
3994                 InsertNewInstBefore(Add, I);
3995                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
3996                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3997               }
3998               break;                         // (X == 13 | X == 15) -> no change
3999             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4000             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4001               break;
4002             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4003             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4004             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4005               return ReplaceInstUsesWith(I, RHS);
4006             }
4007             break;
4008           case ICmpInst::ICMP_NE:
4009             switch (RHSCC) {
4010             default: assert(0 && "Unknown integer condition code!");
4011             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4012             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4013             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4014               return ReplaceInstUsesWith(I, LHS);
4015             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4016             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4017             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4018               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4019             }
4020             break;
4021           case ICmpInst::ICMP_ULT:
4022             switch (RHSCC) {
4023             default: assert(0 && "Unknown integer condition code!");
4024             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4025               break;
4026             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4027               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4028                                      false, I);
4029             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4030               break;
4031             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4032             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4033               return ReplaceInstUsesWith(I, RHS);
4034             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4035               break;
4036             }
4037             break;
4038           case ICmpInst::ICMP_SLT:
4039             switch (RHSCC) {
4040             default: assert(0 && "Unknown integer condition code!");
4041             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4042               break;
4043             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4044               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4045                                      false, I);
4046             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4047               break;
4048             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4049             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4050               return ReplaceInstUsesWith(I, RHS);
4051             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4052               break;
4053             }
4054             break;
4055           case ICmpInst::ICMP_UGT:
4056             switch (RHSCC) {
4057             default: assert(0 && "Unknown integer condition code!");
4058             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4059             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4060               return ReplaceInstUsesWith(I, LHS);
4061             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4062               break;
4063             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4064             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4065               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4066             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4067               break;
4068             }
4069             break;
4070           case ICmpInst::ICMP_SGT:
4071             switch (RHSCC) {
4072             default: assert(0 && "Unknown integer condition code!");
4073             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4074             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4075               return ReplaceInstUsesWith(I, LHS);
4076             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4077               break;
4078             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4079             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4080               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4081             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4082               break;
4083             }
4084             break;
4085           }
4086         }
4087   }
4088     
4089   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4090   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4091     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4092       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4093         const Type *SrcTy = Op0C->getOperand(0)->getType();
4094         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4095             // Only do this if the casts both really cause code to be generated.
4096             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4097                               I.getType(), TD) &&
4098             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4099                               I.getType(), TD)) {
4100           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4101                                                         Op1C->getOperand(0),
4102                                                         I.getName());
4103           InsertNewInstBefore(NewOp, I);
4104           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4105         }
4106       }
4107       
4108
4109   return Changed ? &I : 0;
4110 }
4111
4112 // XorSelf - Implements: X ^ X --> 0
4113 struct XorSelf {
4114   Value *RHS;
4115   XorSelf(Value *rhs) : RHS(rhs) {}
4116   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4117   Instruction *apply(BinaryOperator &Xor) const {
4118     return &Xor;
4119   }
4120 };
4121
4122
4123 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4124   bool Changed = SimplifyCommutative(I);
4125   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4126
4127   if (isa<UndefValue>(Op1))
4128     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4129
4130   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4131   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4132     assert(Result == &I && "AssociativeOpt didn't work?");
4133     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4134   }
4135   
4136   // See if we can simplify any instructions used by the instruction whose sole 
4137   // purpose is to compute bits we don't care about.
4138   if (!isa<VectorType>(I.getType())) {
4139     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4140     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4141     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4142                              KnownZero, KnownOne))
4143       return &I;
4144   } else if (isa<ConstantAggregateZero>(Op1)) {
4145     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4146   }
4147
4148   // Is this a ~ operation?
4149   if (Value *NotOp = dyn_castNotVal(&I)) {
4150     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4151     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4152     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4153       if (Op0I->getOpcode() == Instruction::And || 
4154           Op0I->getOpcode() == Instruction::Or) {
4155         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4156         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4157           Instruction *NotY =
4158             BinaryOperator::createNot(Op0I->getOperand(1),
4159                                       Op0I->getOperand(1)->getName()+".not");
4160           InsertNewInstBefore(NotY, I);
4161           if (Op0I->getOpcode() == Instruction::And)
4162             return BinaryOperator::createOr(Op0NotVal, NotY);
4163           else
4164             return BinaryOperator::createAnd(Op0NotVal, NotY);
4165         }
4166       }
4167     }
4168   }
4169   
4170   
4171   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4172     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4173     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4174       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4175         return new ICmpInst(ICI->getInversePredicate(),
4176                             ICI->getOperand(0), ICI->getOperand(1));
4177
4178     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4179       // ~(c-X) == X-c-1 == X+(-c-1)
4180       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4181         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4182           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4183           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4184                                               ConstantInt::get(I.getType(), 1));
4185           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4186         }
4187           
4188       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4189         if (Op0I->getOpcode() == Instruction::Add) {
4190           // ~(X-c) --> (-c-1)-X
4191           if (RHS->isAllOnesValue()) {
4192             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4193             return BinaryOperator::createSub(
4194                            ConstantExpr::getSub(NegOp0CI,
4195                                              ConstantInt::get(I.getType(), 1)),
4196                                           Op0I->getOperand(0));
4197           } else if (RHS->getValue().isSignBit()) {
4198             // (X + C) ^ signbit -> (X + C + signbit)
4199             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4200             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4201
4202           }
4203         } else if (Op0I->getOpcode() == Instruction::Or) {
4204           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4205           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4206             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4207             // Anything in both C1 and C2 is known to be zero, remove it from
4208             // NewRHS.
4209             Constant *CommonBits = And(Op0CI, RHS);
4210             NewRHS = ConstantExpr::getAnd(NewRHS, 
4211                                           ConstantExpr::getNot(CommonBits));
4212             AddToWorkList(Op0I);
4213             I.setOperand(0, Op0I->getOperand(0));
4214             I.setOperand(1, NewRHS);
4215             return &I;
4216           }
4217         }
4218     }
4219
4220     // Try to fold constant and into select arguments.
4221     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4222       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4223         return R;
4224     if (isa<PHINode>(Op0))
4225       if (Instruction *NV = FoldOpIntoPhi(I))
4226         return NV;
4227   }
4228
4229   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4230     if (X == Op1)
4231       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4232
4233   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4234     if (X == Op0)
4235       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4236
4237   
4238   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4239   if (Op1I) {
4240     Value *A, *B;
4241     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4242       if (A == Op0) {              // B^(B|A) == (A|B)^B
4243         Op1I->swapOperands();
4244         I.swapOperands();
4245         std::swap(Op0, Op1);
4246       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4247         I.swapOperands();     // Simplified below.
4248         std::swap(Op0, Op1);
4249       }
4250     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4251       if (Op0 == A)                                          // A^(A^B) == B
4252         return ReplaceInstUsesWith(I, B);
4253       else if (Op0 == B)                                     // A^(B^A) == B
4254         return ReplaceInstUsesWith(I, A);
4255     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4256       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4257         Op1I->swapOperands();
4258         std::swap(A, B);
4259       }
4260       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4261         I.swapOperands();     // Simplified below.
4262         std::swap(Op0, Op1);
4263       }
4264     }
4265   }
4266   
4267   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4268   if (Op0I) {
4269     Value *A, *B;
4270     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4271       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4272         std::swap(A, B);
4273       if (B == Op1) {                                // (A|B)^B == A & ~B
4274         Instruction *NotB =
4275           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4276         return BinaryOperator::createAnd(A, NotB);
4277       }
4278     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4279       if (Op1 == A)                                          // (A^B)^A == B
4280         return ReplaceInstUsesWith(I, B);
4281       else if (Op1 == B)                                     // (B^A)^A == B
4282         return ReplaceInstUsesWith(I, A);
4283     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4284       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4285         std::swap(A, B);
4286       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4287           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4288         Instruction *N =
4289           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4290         return BinaryOperator::createAnd(N, Op1);
4291       }
4292     }
4293   }
4294   
4295   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4296   if (Op0I && Op1I && Op0I->isShift() && 
4297       Op0I->getOpcode() == Op1I->getOpcode() && 
4298       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4299       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4300     Instruction *NewOp =
4301       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4302                                                     Op1I->getOperand(0),
4303                                                     Op0I->getName()), I);
4304     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4305                                   Op1I->getOperand(1));
4306   }
4307     
4308   if (Op0I && Op1I) {
4309     Value *A, *B, *C, *D;
4310     // (A & B)^(A | B) -> A ^ B
4311     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4312         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4313       if ((A == C && B == D) || (A == D && B == C)) 
4314         return BinaryOperator::createXor(A, B);
4315     }
4316     // (A | B)^(A & B) -> A ^ B
4317     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4318         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4319       if ((A == C && B == D) || (A == D && B == C)) 
4320         return BinaryOperator::createXor(A, B);
4321     }
4322     
4323     // (A & B)^(C & D)
4324     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4325         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4326         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4327       // (X & Y)^(X & Y) -> (Y^Z) & X
4328       Value *X = 0, *Y = 0, *Z = 0;
4329       if (A == C)
4330         X = A, Y = B, Z = D;
4331       else if (A == D)
4332         X = A, Y = B, Z = C;
4333       else if (B == C)
4334         X = B, Y = A, Z = D;
4335       else if (B == D)
4336         X = B, Y = A, Z = C;
4337       
4338       if (X) {
4339         Instruction *NewOp =
4340         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4341         return BinaryOperator::createAnd(NewOp, X);
4342       }
4343     }
4344   }
4345     
4346   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4347   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4348     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4349       return R;
4350
4351   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4352   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4353     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4354       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4355         const Type *SrcTy = Op0C->getOperand(0)->getType();
4356         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4357             // Only do this if the casts both really cause code to be generated.
4358             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4359                               I.getType(), TD) &&
4360             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4361                               I.getType(), TD)) {
4362           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4363                                                          Op1C->getOperand(0),
4364                                                          I.getName());
4365           InsertNewInstBefore(NewOp, I);
4366           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4367         }
4368       }
4369
4370   return Changed ? &I : 0;
4371 }
4372
4373 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4374 /// overflowed for this type.
4375 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4376                             ConstantInt *In2, bool IsSigned = false) {
4377   Result = cast<ConstantInt>(Add(In1, In2));
4378
4379   if (IsSigned)
4380     if (In2->getValue().isNegative())
4381       return Result->getValue().sgt(In1->getValue());
4382     else
4383       return Result->getValue().slt(In1->getValue());
4384   else
4385     return Result->getValue().ult(In1->getValue());
4386 }
4387
4388 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4389 /// code necessary to compute the offset from the base pointer (without adding
4390 /// in the base pointer).  Return the result as a signed integer of intptr size.
4391 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4392   TargetData &TD = IC.getTargetData();
4393   gep_type_iterator GTI = gep_type_begin(GEP);
4394   const Type *IntPtrTy = TD.getIntPtrType();
4395   Value *Result = Constant::getNullValue(IntPtrTy);
4396
4397   // Build a mask for high order bits.
4398   unsigned IntPtrWidth = TD.getPointerSize()*8;
4399   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4400
4401   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4402     Value *Op = GEP->getOperand(i);
4403     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4404     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4405       if (OpC->isZero()) continue;
4406       
4407       // Handle a struct index, which adds its field offset to the pointer.
4408       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4409         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4410         
4411         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4412           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4413         else
4414           Result = IC.InsertNewInstBefore(
4415                    BinaryOperator::createAdd(Result,
4416                                              ConstantInt::get(IntPtrTy, Size),
4417                                              GEP->getName()+".offs"), I);
4418         continue;
4419       }
4420       
4421       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4422       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4423       Scale = ConstantExpr::getMul(OC, Scale);
4424       if (Constant *RC = dyn_cast<Constant>(Result))
4425         Result = ConstantExpr::getAdd(RC, Scale);
4426       else {
4427         // Emit an add instruction.
4428         Result = IC.InsertNewInstBefore(
4429            BinaryOperator::createAdd(Result, Scale,
4430                                      GEP->getName()+".offs"), I);
4431       }
4432       continue;
4433     }
4434     // Convert to correct type.
4435     if (Op->getType() != IntPtrTy) {
4436       if (Constant *OpC = dyn_cast<Constant>(Op))
4437         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4438       else
4439         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4440                                                  Op->getName()+".c"), I);
4441     }
4442     if (Size != 1) {
4443       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4444       if (Constant *OpC = dyn_cast<Constant>(Op))
4445         Op = ConstantExpr::getMul(OpC, Scale);
4446       else    // We'll let instcombine(mul) convert this to a shl if possible.
4447         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4448                                                   GEP->getName()+".idx"), I);
4449     }
4450
4451     // Emit an add instruction.
4452     if (isa<Constant>(Op) && isa<Constant>(Result))
4453       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4454                                     cast<Constant>(Result));
4455     else
4456       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4457                                                   GEP->getName()+".offs"), I);
4458   }
4459   return Result;
4460 }
4461
4462 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4463 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4464 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4465                                        ICmpInst::Predicate Cond,
4466                                        Instruction &I) {
4467   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4468
4469   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4470     if (isa<PointerType>(CI->getOperand(0)->getType()))
4471       RHS = CI->getOperand(0);
4472
4473   Value *PtrBase = GEPLHS->getOperand(0);
4474   if (PtrBase == RHS) {
4475     // As an optimization, we don't actually have to compute the actual value of
4476     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4477     // each index is zero or not.
4478     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4479       Instruction *InVal = 0;
4480       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4481       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4482         bool EmitIt = true;
4483         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4484           if (isa<UndefValue>(C))  // undef index -> undef.
4485             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4486           if (C->isNullValue())
4487             EmitIt = false;
4488           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4489             EmitIt = false;  // This is indexing into a zero sized array?
4490           } else if (isa<ConstantInt>(C))
4491             return ReplaceInstUsesWith(I, // No comparison is needed here.
4492                                  ConstantInt::get(Type::Int1Ty, 
4493                                                   Cond == ICmpInst::ICMP_NE));
4494         }
4495
4496         if (EmitIt) {
4497           Instruction *Comp =
4498             new ICmpInst(Cond, GEPLHS->getOperand(i),
4499                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4500           if (InVal == 0)
4501             InVal = Comp;
4502           else {
4503             InVal = InsertNewInstBefore(InVal, I);
4504             InsertNewInstBefore(Comp, I);
4505             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4506               InVal = BinaryOperator::createOr(InVal, Comp);
4507             else                              // True if all are equal
4508               InVal = BinaryOperator::createAnd(InVal, Comp);
4509           }
4510         }
4511       }
4512
4513       if (InVal)
4514         return InVal;
4515       else
4516         // No comparison is needed here, all indexes = 0
4517         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4518                                                 Cond == ICmpInst::ICMP_EQ));
4519     }
4520
4521     // Only lower this if the icmp is the only user of the GEP or if we expect
4522     // the result to fold to a constant!
4523     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4524       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4525       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4526       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4527                           Constant::getNullValue(Offset->getType()));
4528     }
4529   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4530     // If the base pointers are different, but the indices are the same, just
4531     // compare the base pointer.
4532     if (PtrBase != GEPRHS->getOperand(0)) {
4533       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4534       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4535                         GEPRHS->getOperand(0)->getType();
4536       if (IndicesTheSame)
4537         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4538           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4539             IndicesTheSame = false;
4540             break;
4541           }
4542
4543       // If all indices are the same, just compare the base pointers.
4544       if (IndicesTheSame)
4545         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4546                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4547
4548       // Otherwise, the base pointers are different and the indices are
4549       // different, bail out.
4550       return 0;
4551     }
4552
4553     // If one of the GEPs has all zero indices, recurse.
4554     bool AllZeros = true;
4555     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4556       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4557           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4558         AllZeros = false;
4559         break;
4560       }
4561     if (AllZeros)
4562       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4563                           ICmpInst::getSwappedPredicate(Cond), I);
4564
4565     // If the other GEP has all zero indices, recurse.
4566     AllZeros = true;
4567     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4568       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4569           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4570         AllZeros = false;
4571         break;
4572       }
4573     if (AllZeros)
4574       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4575
4576     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4577       // If the GEPs only differ by one index, compare it.
4578       unsigned NumDifferences = 0;  // Keep track of # differences.
4579       unsigned DiffOperand = 0;     // The operand that differs.
4580       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4581         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4582           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4583                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4584             // Irreconcilable differences.
4585             NumDifferences = 2;
4586             break;
4587           } else {
4588             if (NumDifferences++) break;
4589             DiffOperand = i;
4590           }
4591         }
4592
4593       if (NumDifferences == 0)   // SAME GEP?
4594         return ReplaceInstUsesWith(I, // No comparison is needed here.
4595                                    ConstantInt::get(Type::Int1Ty, 
4596                                                     Cond == ICmpInst::ICMP_EQ));
4597       else if (NumDifferences == 1) {
4598         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4599         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4600         // Make sure we do a signed comparison here.
4601         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4602       }
4603     }
4604
4605     // Only lower this if the icmp is the only user of the GEP or if we expect
4606     // the result to fold to a constant!
4607     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4608         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4609       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4610       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4611       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4612       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4613     }
4614   }
4615   return 0;
4616 }
4617
4618 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4619   bool Changed = SimplifyCompare(I);
4620   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4621
4622   // Fold trivial predicates.
4623   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4624     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4625   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4626     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4627   
4628   // Simplify 'fcmp pred X, X'
4629   if (Op0 == Op1) {
4630     switch (I.getPredicate()) {
4631     default: assert(0 && "Unknown predicate!");
4632     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4633     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4634     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4635       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4636     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4637     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4638     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4639       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4640       
4641     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4642     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4643     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4644     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4645       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4646       I.setPredicate(FCmpInst::FCMP_UNO);
4647       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4648       return &I;
4649       
4650     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4651     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4652     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4653     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4654       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4655       I.setPredicate(FCmpInst::FCMP_ORD);
4656       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4657       return &I;
4658     }
4659   }
4660     
4661   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4662     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4663
4664   // Handle fcmp with constant RHS
4665   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4666     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4667       switch (LHSI->getOpcode()) {
4668       case Instruction::PHI:
4669         if (Instruction *NV = FoldOpIntoPhi(I))
4670           return NV;
4671         break;
4672       case Instruction::Select:
4673         // If either operand of the select is a constant, we can fold the
4674         // comparison into the select arms, which will cause one to be
4675         // constant folded and the select turned into a bitwise or.
4676         Value *Op1 = 0, *Op2 = 0;
4677         if (LHSI->hasOneUse()) {
4678           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4679             // Fold the known value into the constant operand.
4680             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4681             // Insert a new FCmp of the other select operand.
4682             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4683                                                       LHSI->getOperand(2), RHSC,
4684                                                       I.getName()), I);
4685           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4686             // Fold the known value into the constant operand.
4687             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4688             // Insert a new FCmp of the other select operand.
4689             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4690                                                       LHSI->getOperand(1), RHSC,
4691                                                       I.getName()), I);
4692           }
4693         }
4694
4695         if (Op1)
4696           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4697         break;
4698       }
4699   }
4700
4701   return Changed ? &I : 0;
4702 }
4703
4704 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4705   bool Changed = SimplifyCompare(I);
4706   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4707   const Type *Ty = Op0->getType();
4708
4709   // icmp X, X
4710   if (Op0 == Op1)
4711     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4712                                                    isTrueWhenEqual(I)));
4713
4714   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4715     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4716
4717   // icmp of GlobalValues can never equal each other as long as they aren't
4718   // external weak linkage type.
4719   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4720     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4721       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4722         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4723                                                        !isTrueWhenEqual(I)));
4724
4725   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4726   // addresses never equal each other!  We already know that Op0 != Op1.
4727   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4728        isa<ConstantPointerNull>(Op0)) &&
4729       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4730        isa<ConstantPointerNull>(Op1)))
4731     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4732                                                    !isTrueWhenEqual(I)));
4733
4734   // icmp's with boolean values can always be turned into bitwise operations
4735   if (Ty == Type::Int1Ty) {
4736     switch (I.getPredicate()) {
4737     default: assert(0 && "Invalid icmp instruction!");
4738     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4739       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4740       InsertNewInstBefore(Xor, I);
4741       return BinaryOperator::createNot(Xor);
4742     }
4743     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4744       return BinaryOperator::createXor(Op0, Op1);
4745
4746     case ICmpInst::ICMP_UGT:
4747     case ICmpInst::ICMP_SGT:
4748       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4749       // FALL THROUGH
4750     case ICmpInst::ICMP_ULT:
4751     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4752       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4753       InsertNewInstBefore(Not, I);
4754       return BinaryOperator::createAnd(Not, Op1);
4755     }
4756     case ICmpInst::ICMP_UGE:
4757     case ICmpInst::ICMP_SGE:
4758       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4759       // FALL THROUGH
4760     case ICmpInst::ICMP_ULE:
4761     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4762       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4763       InsertNewInstBefore(Not, I);
4764       return BinaryOperator::createOr(Not, Op1);
4765     }
4766     }
4767   }
4768
4769   // See if we are doing a comparison between a constant and an instruction that
4770   // can be folded into the comparison.
4771   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4772     switch (I.getPredicate()) {
4773     default: break;
4774     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4775       if (CI->isMinValue(false))
4776         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4777       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4778         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4779       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4780         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4781       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4782       if (CI->isMinValue(true))
4783         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4784                             ConstantInt::getAllOnesValue(Op0->getType()));
4785           
4786       break;
4787
4788     case ICmpInst::ICMP_SLT:
4789       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4790         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4791       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4792         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4793       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4794         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4795       break;
4796
4797     case ICmpInst::ICMP_UGT:
4798       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4799         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4800       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4801         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4802       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4803         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4804         
4805       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4806       if (CI->isMaxValue(true))
4807         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4808                             ConstantInt::getNullValue(Op0->getType()));
4809       break;
4810
4811     case ICmpInst::ICMP_SGT:
4812       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4813         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4814       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4815         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4816       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4817         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4818       break;
4819
4820     case ICmpInst::ICMP_ULE:
4821       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4822         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4823       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4824         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4825       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4826         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4827       break;
4828
4829     case ICmpInst::ICMP_SLE:
4830       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4831         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4832       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4833         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4834       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4835         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4836       break;
4837
4838     case ICmpInst::ICMP_UGE:
4839       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4840         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4841       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4842         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4843       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4844         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4845       break;
4846
4847     case ICmpInst::ICMP_SGE:
4848       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4849         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4850       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4851         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4852       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4853         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4854       break;
4855     }
4856
4857     // If we still have a icmp le or icmp ge instruction, turn it into the
4858     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4859     // already been handled above, this requires little checking.
4860     //
4861     switch (I.getPredicate()) {
4862     default: break;
4863     case ICmpInst::ICMP_ULE: 
4864       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4865     case ICmpInst::ICMP_SLE:
4866       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4867     case ICmpInst::ICMP_UGE:
4868       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4869     case ICmpInst::ICMP_SGE:
4870       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4871     }
4872     
4873     // See if we can fold the comparison based on bits known to be zero or one
4874     // in the input.  If this comparison is a normal comparison, it demands all
4875     // bits, if it is a sign bit comparison, it only demands the sign bit.
4876     
4877     bool UnusedBit;
4878     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4879     
4880     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4881     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4882     if (SimplifyDemandedBits(Op0, 
4883                              isSignBit ? APInt::getSignBit(BitWidth)
4884                                        : APInt::getAllOnesValue(BitWidth),
4885                              KnownZero, KnownOne, 0))
4886       return &I;
4887         
4888     // Given the known and unknown bits, compute a range that the LHS could be
4889     // in.
4890     if ((KnownOne | KnownZero) != 0) {
4891       // Compute the Min, Max and RHS values based on the known bits. For the
4892       // EQ and NE we use unsigned values.
4893       APInt Min(BitWidth, 0), Max(BitWidth, 0);
4894       const APInt& RHSVal = CI->getValue();
4895       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4896         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4897                                                Max);
4898       } else {
4899         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4900                                                  Max);
4901       }
4902       switch (I.getPredicate()) {  // LE/GE have been folded already.
4903       default: assert(0 && "Unknown icmp opcode!");
4904       case ICmpInst::ICMP_EQ:
4905         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4906           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4907         break;
4908       case ICmpInst::ICMP_NE:
4909         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4910           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4911         break;
4912       case ICmpInst::ICMP_ULT:
4913         if (Max.ult(RHSVal))
4914           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4915         if (Min.uge(RHSVal))
4916           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4917         break;
4918       case ICmpInst::ICMP_UGT:
4919         if (Min.ugt(RHSVal))
4920           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4921         if (Max.ule(RHSVal))
4922           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4923         break;
4924       case ICmpInst::ICMP_SLT:
4925         if (Max.slt(RHSVal))
4926           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4927         if (Min.sgt(RHSVal))
4928           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4929         break;
4930       case ICmpInst::ICMP_SGT: 
4931         if (Min.sgt(RHSVal))
4932           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4933         if (Max.sle(RHSVal))
4934           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4935         break;
4936       }
4937     }
4938           
4939     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4940     // instruction, see if that instruction also has constants so that the 
4941     // instruction can be folded into the icmp 
4942     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4943       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4944         return Res;
4945   }
4946
4947   // Handle icmp with constant (but not simple integer constant) RHS
4948   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4949     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4950       switch (LHSI->getOpcode()) {
4951       case Instruction::GetElementPtr:
4952         if (RHSC->isNullValue()) {
4953           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
4954           bool isAllZeros = true;
4955           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4956             if (!isa<Constant>(LHSI->getOperand(i)) ||
4957                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4958               isAllZeros = false;
4959               break;
4960             }
4961           if (isAllZeros)
4962             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4963                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
4964         }
4965         break;
4966
4967       case Instruction::PHI:
4968         if (Instruction *NV = FoldOpIntoPhi(I))
4969           return NV;
4970         break;
4971       case Instruction::Select: {
4972         // If either operand of the select is a constant, we can fold the
4973         // comparison into the select arms, which will cause one to be
4974         // constant folded and the select turned into a bitwise or.
4975         Value *Op1 = 0, *Op2 = 0;
4976         if (LHSI->hasOneUse()) {
4977           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4978             // Fold the known value into the constant operand.
4979             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4980             // Insert a new ICmp of the other select operand.
4981             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4982                                                    LHSI->getOperand(2), RHSC,
4983                                                    I.getName()), I);
4984           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4985             // Fold the known value into the constant operand.
4986             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4987             // Insert a new ICmp of the other select operand.
4988             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4989                                                    LHSI->getOperand(1), RHSC,
4990                                                    I.getName()), I);
4991           }
4992         }
4993
4994         if (Op1)
4995           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4996         break;
4997       }
4998       case Instruction::Malloc:
4999         // If we have (malloc != null), and if the malloc has a single use, we
5000         // can assume it is successful and remove the malloc.
5001         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5002           AddToWorkList(LHSI);
5003           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5004                                                          !isTrueWhenEqual(I)));
5005         }
5006         break;
5007       }
5008   }
5009
5010   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5011   if (User *GEP = dyn_castGetElementPtr(Op0))
5012     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5013       return NI;
5014   if (User *GEP = dyn_castGetElementPtr(Op1))
5015     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5016                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5017       return NI;
5018
5019   // Test to see if the operands of the icmp are casted versions of other
5020   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5021   // now.
5022   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5023     if (isa<PointerType>(Op0->getType()) && 
5024         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5025       // We keep moving the cast from the left operand over to the right
5026       // operand, where it can often be eliminated completely.
5027       Op0 = CI->getOperand(0);
5028
5029       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5030       // so eliminate it as well.
5031       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5032         Op1 = CI2->getOperand(0);
5033
5034       // If Op1 is a constant, we can fold the cast into the constant.
5035       if (Op0->getType() != Op1->getType())
5036         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5037           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5038         } else {
5039           // Otherwise, cast the RHS right before the icmp
5040           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5041         }
5042       return new ICmpInst(I.getPredicate(), Op0, Op1);
5043     }
5044   }
5045   
5046   if (isa<CastInst>(Op0)) {
5047     // Handle the special case of: icmp (cast bool to X), <cst>
5048     // This comes up when you have code like
5049     //   int X = A < B;
5050     //   if (X) ...
5051     // For generality, we handle any zero-extension of any operand comparison
5052     // with a constant or another cast from the same type.
5053     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5054       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5055         return R;
5056   }
5057   
5058   if (I.isEquality()) {
5059     Value *A, *B, *C, *D;
5060     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5061       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5062         Value *OtherVal = A == Op1 ? B : A;
5063         return new ICmpInst(I.getPredicate(), OtherVal,
5064                             Constant::getNullValue(A->getType()));
5065       }
5066
5067       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5068         // A^c1 == C^c2 --> A == C^(c1^c2)
5069         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5070           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5071             if (Op1->hasOneUse()) {
5072               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5073               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5074               return new ICmpInst(I.getPredicate(), A,
5075                                   InsertNewInstBefore(Xor, I));
5076             }
5077         
5078         // A^B == A^D -> B == D
5079         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5080         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5081         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5082         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5083       }
5084     }
5085     
5086     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5087         (A == Op0 || B == Op0)) {
5088       // A == (A^B)  ->  B == 0
5089       Value *OtherVal = A == Op0 ? B : A;
5090       return new ICmpInst(I.getPredicate(), OtherVal,
5091                           Constant::getNullValue(A->getType()));
5092     }
5093     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5094       // (A-B) == A  ->  B == 0
5095       return new ICmpInst(I.getPredicate(), B,
5096                           Constant::getNullValue(B->getType()));
5097     }
5098     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5099       // A == (A-B)  ->  B == 0
5100       return new ICmpInst(I.getPredicate(), B,
5101                           Constant::getNullValue(B->getType()));
5102     }
5103     
5104     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5105     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5106         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5107         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5108       Value *X = 0, *Y = 0, *Z = 0;
5109       
5110       if (A == C) {
5111         X = B; Y = D; Z = A;
5112       } else if (A == D) {
5113         X = B; Y = C; Z = A;
5114       } else if (B == C) {
5115         X = A; Y = D; Z = B;
5116       } else if (B == D) {
5117         X = A; Y = C; Z = B;
5118       }
5119       
5120       if (X) {   // Build (X^Y) & Z
5121         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5122         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5123         I.setOperand(0, Op1);
5124         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5125         return &I;
5126       }
5127     }
5128   }
5129   return Changed ? &I : 0;
5130 }
5131
5132
5133 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5134 /// and CmpRHS are both known to be integer constants.
5135 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5136                                           ConstantInt *DivRHS) {
5137   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5138   const APInt &CmpRHSV = CmpRHS->getValue();
5139   
5140   // FIXME: If the operand types don't match the type of the divide 
5141   // then don't attempt this transform. The code below doesn't have the
5142   // logic to deal with a signed divide and an unsigned compare (and
5143   // vice versa). This is because (x /s C1) <s C2  produces different 
5144   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5145   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5146   // work. :(  The if statement below tests that condition and bails 
5147   // if it finds it. 
5148   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5149   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5150     return 0;
5151   if (DivRHS->isZero())
5152     return 0; // The ProdOV computation fails on divide by zero.
5153
5154   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5155   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5156   // C2 (CI). By solving for X we can turn this into a range check 
5157   // instead of computing a divide. 
5158   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5159
5160   // Determine if the product overflows by seeing if the product is
5161   // not equal to the divide. Make sure we do the same kind of divide
5162   // as in the LHS instruction that we're folding. 
5163   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5164                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5165
5166   // Get the ICmp opcode
5167   ICmpInst::Predicate Pred = ICI.getPredicate();
5168
5169   // Figure out the interval that is being checked.  For example, a comparison
5170   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5171   // Compute this interval based on the constants involved and the signedness of
5172   // the compare/divide.  This computes a half-open interval, keeping track of
5173   // whether either value in the interval overflows.  After analysis each
5174   // overflow variable is set to 0 if it's corresponding bound variable is valid
5175   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5176   int LoOverflow = 0, HiOverflow = 0;
5177   ConstantInt *LoBound = 0, *HiBound = 0;
5178   
5179   
5180   if (!DivIsSigned) {  // udiv
5181     // e.g. X/5 op 3  --> [15, 20)
5182     LoBound = Prod;
5183     HiOverflow = LoOverflow = ProdOV;
5184     if (!HiOverflow)
5185       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5186   } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5187     if (CmpRHSV == 0) {       // (X / pos) op 0
5188       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5189       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5190       HiBound = DivRHS;
5191     } else if (CmpRHSV.isPositive()) {   // (X / pos) op pos
5192       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5193       HiOverflow = LoOverflow = ProdOV;
5194       if (!HiOverflow)
5195         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5196     } else {                       // (X / pos) op neg
5197       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5198       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5199       LoOverflow = AddWithOverflow(LoBound, Prod,
5200                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5201       HiBound = AddOne(Prod);
5202       HiOverflow = ProdOV ? -1 : 0;
5203     }
5204   } else {                         // Divisor is < 0.
5205     if (CmpRHSV == 0) {       // (X / neg) op 0
5206       // e.g. X/-5 op 0  --> [-4, 5)
5207       LoBound = AddOne(DivRHS);
5208       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5209       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5210         HiOverflow = 1;            // [INTMIN+1, overflow)
5211         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5212       }
5213     } else if (CmpRHSV.isPositive()) {   // (X / neg) op pos
5214       // e.g. X/-5 op 3  --> [-19, -14)
5215       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5216       if (!LoOverflow)
5217         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5218       HiBound = AddOne(Prod);
5219     } else {                       // (X / neg) op neg
5220       // e.g. X/-5 op -3  --> [15, 20)
5221       LoBound = Prod;
5222       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5223       HiBound = Subtract(Prod, DivRHS);
5224     }
5225     
5226     // Dividing by a negative swaps the condition.  LT <-> GT
5227     Pred = ICmpInst::getSwappedPredicate(Pred);
5228   }
5229
5230   Value *X = DivI->getOperand(0);
5231   switch (Pred) {
5232   default: assert(0 && "Unhandled icmp opcode!");
5233   case ICmpInst::ICMP_EQ:
5234     if (LoOverflow && HiOverflow)
5235       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5236     else if (HiOverflow)
5237       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5238                           ICmpInst::ICMP_UGE, X, LoBound);
5239     else if (LoOverflow)
5240       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5241                           ICmpInst::ICMP_ULT, X, HiBound);
5242     else
5243       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5244   case ICmpInst::ICMP_NE:
5245     if (LoOverflow && HiOverflow)
5246       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5247     else if (HiOverflow)
5248       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5249                           ICmpInst::ICMP_ULT, X, LoBound);
5250     else if (LoOverflow)
5251       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5252                           ICmpInst::ICMP_UGE, X, HiBound);
5253     else
5254       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5255   case ICmpInst::ICMP_ULT:
5256   case ICmpInst::ICMP_SLT:
5257     if (LoOverflow == +1)   // Low bound is greater than input range.
5258       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5259     if (LoOverflow == -1)   // Low bound is less than input range.
5260       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5261     return new ICmpInst(Pred, X, LoBound);
5262   case ICmpInst::ICMP_UGT:
5263   case ICmpInst::ICMP_SGT:
5264     if (HiOverflow == +1)       // High bound greater than input range.
5265       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5266     else if (HiOverflow == -1)  // High bound less than input range.
5267       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5268     if (Pred == ICmpInst::ICMP_UGT)
5269       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5270     else
5271       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5272   }
5273 }
5274
5275
5276 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5277 ///
5278 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5279                                                           Instruction *LHSI,
5280                                                           ConstantInt *RHS) {
5281   const APInt &RHSV = RHS->getValue();
5282   
5283   switch (LHSI->getOpcode()) {
5284   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5285     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5286       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5287       // fold the xor.
5288       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5289           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5290         Value *CompareVal = LHSI->getOperand(0);
5291         
5292         // If the sign bit of the XorCST is not set, there is no change to
5293         // the operation, just stop using the Xor.
5294         if (!XorCST->getValue().isNegative()) {
5295           ICI.setOperand(0, CompareVal);
5296           AddToWorkList(LHSI);
5297           return &ICI;
5298         }
5299         
5300         // Was the old condition true if the operand is positive?
5301         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5302         
5303         // If so, the new one isn't.
5304         isTrueIfPositive ^= true;
5305         
5306         if (isTrueIfPositive)
5307           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5308         else
5309           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5310       }
5311     }
5312     break;
5313   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5314     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5315         LHSI->getOperand(0)->hasOneUse()) {
5316       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5317       
5318       // If the LHS is an AND of a truncating cast, we can widen the
5319       // and/compare to be the input width without changing the value
5320       // produced, eliminating a cast.
5321       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5322         // We can do this transformation if either the AND constant does not
5323         // have its sign bit set or if it is an equality comparison. 
5324         // Extending a relational comparison when we're checking the sign
5325         // bit would not work.
5326         if (Cast->hasOneUse() &&
5327             (ICI.isEquality() || AndCST->getValue().isPositive() && 
5328              RHSV.isPositive())) {
5329           uint32_t BitWidth = 
5330             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5331           APInt NewCST = AndCST->getValue();
5332           NewCST.zext(BitWidth);
5333           APInt NewCI = RHSV;
5334           NewCI.zext(BitWidth);
5335           Instruction *NewAnd = 
5336             BinaryOperator::createAnd(Cast->getOperand(0),
5337                                       ConstantInt::get(NewCST),LHSI->getName());
5338           InsertNewInstBefore(NewAnd, ICI);
5339           return new ICmpInst(ICI.getPredicate(), NewAnd,
5340                               ConstantInt::get(NewCI));
5341         }
5342       }
5343       
5344       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5345       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5346       // happens a LOT in code produced by the C front-end, for bitfield
5347       // access.
5348       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5349       if (Shift && !Shift->isShift())
5350         Shift = 0;
5351       
5352       ConstantInt *ShAmt;
5353       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5354       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5355       const Type *AndTy = AndCST->getType();          // Type of the and.
5356       
5357       // We can fold this as long as we can't shift unknown bits
5358       // into the mask.  This can only happen with signed shift
5359       // rights, as they sign-extend.
5360       if (ShAmt) {
5361         bool CanFold = Shift->isLogicalShift();
5362         if (!CanFold) {
5363           // To test for the bad case of the signed shr, see if any
5364           // of the bits shifted in could be tested after the mask.
5365           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5366           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5367           
5368           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5369           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5370                AndCST->getValue()) == 0)
5371             CanFold = true;
5372         }
5373         
5374         if (CanFold) {
5375           Constant *NewCst;
5376           if (Shift->getOpcode() == Instruction::Shl)
5377             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5378           else
5379             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5380           
5381           // Check to see if we are shifting out any of the bits being
5382           // compared.
5383           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5384             // If we shifted bits out, the fold is not going to work out.
5385             // As a special case, check to see if this means that the
5386             // result is always true or false now.
5387             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5388               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5389             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5390               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5391           } else {
5392             ICI.setOperand(1, NewCst);
5393             Constant *NewAndCST;
5394             if (Shift->getOpcode() == Instruction::Shl)
5395               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5396             else
5397               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5398             LHSI->setOperand(1, NewAndCST);
5399             LHSI->setOperand(0, Shift->getOperand(0));
5400             AddToWorkList(Shift); // Shift is dead.
5401             AddUsesToWorkList(ICI);
5402             return &ICI;
5403           }
5404         }
5405       }
5406       
5407       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5408       // preferable because it allows the C<<Y expression to be hoisted out
5409       // of a loop if Y is invariant and X is not.
5410       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5411           ICI.isEquality() && !Shift->isArithmeticShift() &&
5412           isa<Instruction>(Shift->getOperand(0))) {
5413         // Compute C << Y.
5414         Value *NS;
5415         if (Shift->getOpcode() == Instruction::LShr) {
5416           NS = BinaryOperator::createShl(AndCST, 
5417                                          Shift->getOperand(1), "tmp");
5418         } else {
5419           // Insert a logical shift.
5420           NS = BinaryOperator::createLShr(AndCST,
5421                                           Shift->getOperand(1), "tmp");
5422         }
5423         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5424         
5425         // Compute X & (C << Y).
5426         Instruction *NewAnd = 
5427           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5428         InsertNewInstBefore(NewAnd, ICI);
5429         
5430         ICI.setOperand(0, NewAnd);
5431         return &ICI;
5432       }
5433     }
5434     break;
5435     
5436   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5437     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5438     if (!ShAmt) break;
5439     
5440     uint32_t TypeBits = RHSV.getBitWidth();
5441     
5442     // Check that the shift amount is in range.  If not, don't perform
5443     // undefined shifts.  When the shift is visited it will be
5444     // simplified.
5445     if (ShAmt->uge(TypeBits))
5446       break;
5447     
5448     if (ICI.isEquality()) {
5449       // If we are comparing against bits always shifted out, the
5450       // comparison cannot succeed.
5451       Constant *Comp =
5452         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5453       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5454         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5455         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5456         return ReplaceInstUsesWith(ICI, Cst);
5457       }
5458       
5459       if (LHSI->hasOneUse()) {
5460         // Otherwise strength reduce the shift into an and.
5461         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5462         Constant *Mask =
5463           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5464         
5465         Instruction *AndI =
5466           BinaryOperator::createAnd(LHSI->getOperand(0),
5467                                     Mask, LHSI->getName()+".mask");
5468         Value *And = InsertNewInstBefore(AndI, ICI);
5469         return new ICmpInst(ICI.getPredicate(), And,
5470                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5471       }
5472     }
5473     
5474     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5475     bool TrueIfSigned = false;
5476     if (LHSI->hasOneUse() &&
5477         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5478       // (X << 31) <s 0  --> (X&1) != 0
5479       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5480                                            (TypeBits-ShAmt->getZExtValue()-1));
5481       Instruction *AndI =
5482         BinaryOperator::createAnd(LHSI->getOperand(0),
5483                                   Mask, LHSI->getName()+".mask");
5484       Value *And = InsertNewInstBefore(AndI, ICI);
5485       
5486       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5487                           And, Constant::getNullValue(And->getType()));
5488     }
5489     break;
5490   }
5491     
5492   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5493   case Instruction::AShr: {
5494     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5495     if (!ShAmt) break;
5496
5497     if (ICI.isEquality()) {
5498       // Check that the shift amount is in range.  If not, don't perform
5499       // undefined shifts.  When the shift is visited it will be
5500       // simplified.
5501       uint32_t TypeBits = RHSV.getBitWidth();
5502       if (ShAmt->uge(TypeBits))
5503         break;
5504       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5505       
5506       // If we are comparing against bits always shifted out, the
5507       // comparison cannot succeed.
5508       APInt Comp = RHSV << ShAmtVal;
5509       if (LHSI->getOpcode() == Instruction::LShr)
5510         Comp = Comp.lshr(ShAmtVal);
5511       else
5512         Comp = Comp.ashr(ShAmtVal);
5513       
5514       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5515         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5516         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5517         return ReplaceInstUsesWith(ICI, Cst);
5518       }
5519       
5520       if (LHSI->hasOneUse() || RHSV == 0) {
5521         // Otherwise strength reduce the shift into an and.
5522         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5523         Constant *Mask = ConstantInt::get(Val);
5524         
5525         Instruction *AndI =
5526           BinaryOperator::createAnd(LHSI->getOperand(0),
5527                                     Mask, LHSI->getName()+".mask");
5528         Value *And = InsertNewInstBefore(AndI, ICI);
5529         return new ICmpInst(ICI.getPredicate(), And,
5530                             ConstantExpr::getShl(RHS, ShAmt));
5531       }
5532     }
5533     break;
5534   }
5535     
5536   case Instruction::SDiv:
5537   case Instruction::UDiv:
5538     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5539     // Fold this div into the comparison, producing a range check. 
5540     // Determine, based on the divide type, what the range is being 
5541     // checked.  If there is an overflow on the low or high side, remember 
5542     // it, otherwise compute the range [low, hi) bounding the new value.
5543     // See: InsertRangeTest above for the kinds of replacements possible.
5544     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5545       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5546                                           DivRHS))
5547         return R;
5548     break;
5549   }
5550   
5551   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5552   if (ICI.isEquality()) {
5553     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5554     
5555     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5556     // the second operand is a constant, simplify a bit.
5557     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5558       switch (BO->getOpcode()) {
5559       case Instruction::SRem:
5560         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5561         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5562           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5563           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5564             Instruction *NewRem =
5565               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5566                                          BO->getName());
5567             InsertNewInstBefore(NewRem, ICI);
5568             return new ICmpInst(ICI.getPredicate(), NewRem, 
5569                                 Constant::getNullValue(BO->getType()));
5570           }
5571         }
5572         break;
5573       case Instruction::Add:
5574         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5575         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5576           if (BO->hasOneUse())
5577             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5578                                 Subtract(RHS, BOp1C));
5579         } else if (RHSV == 0) {
5580           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5581           // efficiently invertible, or if the add has just this one use.
5582           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5583           
5584           if (Value *NegVal = dyn_castNegVal(BOp1))
5585             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5586           else if (Value *NegVal = dyn_castNegVal(BOp0))
5587             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5588           else if (BO->hasOneUse()) {
5589             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5590             InsertNewInstBefore(Neg, ICI);
5591             Neg->takeName(BO);
5592             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5593           }
5594         }
5595         break;
5596       case Instruction::Xor:
5597         // For the xor case, we can xor two constants together, eliminating
5598         // the explicit xor.
5599         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5600           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5601                               ConstantExpr::getXor(RHS, BOC));
5602         
5603         // FALLTHROUGH
5604       case Instruction::Sub:
5605         // Replace (([sub|xor] A, B) != 0) with (A != B)
5606         if (RHSV == 0)
5607           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5608                               BO->getOperand(1));
5609         break;
5610         
5611       case Instruction::Or:
5612         // If bits are being or'd in that are not present in the constant we
5613         // are comparing against, then the comparison could never succeed!
5614         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5615           Constant *NotCI = ConstantExpr::getNot(RHS);
5616           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5617             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5618                                                              isICMP_NE));
5619         }
5620         break;
5621         
5622       case Instruction::And:
5623         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5624           // If bits are being compared against that are and'd out, then the
5625           // comparison can never succeed!
5626           if ((RHSV & ~BOC->getValue()) != 0)
5627             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5628                                                              isICMP_NE));
5629           
5630           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5631           if (RHS == BOC && RHSV.isPowerOf2())
5632             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5633                                 ICmpInst::ICMP_NE, LHSI,
5634                                 Constant::getNullValue(RHS->getType()));
5635           
5636           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5637           if (isSignBit(BOC)) {
5638             Value *X = BO->getOperand(0);
5639             Constant *Zero = Constant::getNullValue(X->getType());
5640             ICmpInst::Predicate pred = isICMP_NE ? 
5641               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5642             return new ICmpInst(pred, X, Zero);
5643           }
5644           
5645           // ((X & ~7) == 0) --> X < 8
5646           if (RHSV == 0 && isHighOnes(BOC)) {
5647             Value *X = BO->getOperand(0);
5648             Constant *NegX = ConstantExpr::getNeg(BOC);
5649             ICmpInst::Predicate pred = isICMP_NE ? 
5650               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5651             return new ICmpInst(pred, X, NegX);
5652           }
5653         }
5654       default: break;
5655       }
5656     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5657       // Handle icmp {eq|ne} <intrinsic>, intcst.
5658       if (II->getIntrinsicID() == Intrinsic::bswap) {
5659         AddToWorkList(II);
5660         ICI.setOperand(0, II->getOperand(1));
5661         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5662         return &ICI;
5663       }
5664     }
5665   } else {  // Not a ICMP_EQ/ICMP_NE
5666             // If the LHS is a cast from an integral value of the same size, 
5667             // then since we know the RHS is a constant, try to simlify.
5668     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5669       Value *CastOp = Cast->getOperand(0);
5670       const Type *SrcTy = CastOp->getType();
5671       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5672       if (SrcTy->isInteger() && 
5673           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5674         // If this is an unsigned comparison, try to make the comparison use
5675         // smaller constant values.
5676         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5677           // X u< 128 => X s> -1
5678           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5679                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5680         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5681                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5682           // X u> 127 => X s< 0
5683           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5684                               Constant::getNullValue(SrcTy));
5685         }
5686       }
5687     }
5688   }
5689   return 0;
5690 }
5691
5692 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5693 /// We only handle extending casts so far.
5694 ///
5695 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5696   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5697   Value *LHSCIOp        = LHSCI->getOperand(0);
5698   const Type *SrcTy     = LHSCIOp->getType();
5699   const Type *DestTy    = LHSCI->getType();
5700   Value *RHSCIOp;
5701
5702   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5703   // integer type is the same size as the pointer type.
5704   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5705       getTargetData().getPointerSizeInBits() == 
5706          cast<IntegerType>(DestTy)->getBitWidth()) {
5707     Value *RHSOp = 0;
5708     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5709       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5710     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5711       RHSOp = RHSC->getOperand(0);
5712       // If the pointer types don't match, insert a bitcast.
5713       if (LHSCIOp->getType() != RHSOp->getType())
5714         RHSOp = InsertCastBefore(Instruction::BitCast, RHSOp,
5715                                  LHSCIOp->getType(), ICI);
5716     }
5717
5718     if (RHSOp)
5719       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5720   }
5721   
5722   // The code below only handles extension cast instructions, so far.
5723   // Enforce this.
5724   if (LHSCI->getOpcode() != Instruction::ZExt &&
5725       LHSCI->getOpcode() != Instruction::SExt)
5726     return 0;
5727
5728   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5729   bool isSignedCmp = ICI.isSignedPredicate();
5730
5731   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5732     // Not an extension from the same type?
5733     RHSCIOp = CI->getOperand(0);
5734     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5735       return 0;
5736     
5737     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5738     // and the other is a zext), then we can't handle this.
5739     if (CI->getOpcode() != LHSCI->getOpcode())
5740       return 0;
5741
5742     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5743     // then we can't handle this.
5744     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5745       return 0;
5746     
5747     // Okay, just insert a compare of the reduced operands now!
5748     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5749   }
5750
5751   // If we aren't dealing with a constant on the RHS, exit early
5752   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5753   if (!CI)
5754     return 0;
5755
5756   // Compute the constant that would happen if we truncated to SrcTy then
5757   // reextended to DestTy.
5758   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5759   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5760
5761   // If the re-extended constant didn't change...
5762   if (Res2 == CI) {
5763     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5764     // For example, we might have:
5765     //    %A = sext short %X to uint
5766     //    %B = icmp ugt uint %A, 1330
5767     // It is incorrect to transform this into 
5768     //    %B = icmp ugt short %X, 1330 
5769     // because %A may have negative value. 
5770     //
5771     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5772     // OR operation is EQ/NE.
5773     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5774       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5775     else
5776       return 0;
5777   }
5778
5779   // The re-extended constant changed so the constant cannot be represented 
5780   // in the shorter type. Consequently, we cannot emit a simple comparison.
5781
5782   // First, handle some easy cases. We know the result cannot be equal at this
5783   // point so handle the ICI.isEquality() cases
5784   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5785     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5786   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5787     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5788
5789   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5790   // should have been folded away previously and not enter in here.
5791   Value *Result;
5792   if (isSignedCmp) {
5793     // We're performing a signed comparison.
5794     if (cast<ConstantInt>(CI)->getValue().isNegative())
5795       Result = ConstantInt::getFalse();          // X < (small) --> false
5796     else
5797       Result = ConstantInt::getTrue();           // X < (large) --> true
5798   } else {
5799     // We're performing an unsigned comparison.
5800     if (isSignedExt) {
5801       // We're performing an unsigned comp with a sign extended value.
5802       // This is true if the input is >= 0. [aka >s -1]
5803       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5804       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5805                                    NegOne, ICI.getName()), ICI);
5806     } else {
5807       // Unsigned extend & unsigned compare -> always true.
5808       Result = ConstantInt::getTrue();
5809     }
5810   }
5811
5812   // Finally, return the value computed.
5813   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5814       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5815     return ReplaceInstUsesWith(ICI, Result);
5816   } else {
5817     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5818             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5819            "ICmp should be folded!");
5820     if (Constant *CI = dyn_cast<Constant>(Result))
5821       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5822     else
5823       return BinaryOperator::createNot(Result);
5824   }
5825 }
5826
5827 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5828   return commonShiftTransforms(I);
5829 }
5830
5831 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5832   return commonShiftTransforms(I);
5833 }
5834
5835 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5836   return commonShiftTransforms(I);
5837 }
5838
5839 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5840   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5841   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5842
5843   // shl X, 0 == X and shr X, 0 == X
5844   // shl 0, X == 0 and shr 0, X == 0
5845   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5846       Op0 == Constant::getNullValue(Op0->getType()))
5847     return ReplaceInstUsesWith(I, Op0);
5848   
5849   if (isa<UndefValue>(Op0)) {            
5850     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5851       return ReplaceInstUsesWith(I, Op0);
5852     else                                    // undef << X -> 0, undef >>u X -> 0
5853       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5854   }
5855   if (isa<UndefValue>(Op1)) {
5856     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5857       return ReplaceInstUsesWith(I, Op0);          
5858     else                                     // X << undef, X >>u undef -> 0
5859       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5860   }
5861
5862   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5863   if (I.getOpcode() == Instruction::AShr)
5864     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5865       if (CSI->isAllOnesValue())
5866         return ReplaceInstUsesWith(I, CSI);
5867
5868   // Try to fold constant and into select arguments.
5869   if (isa<Constant>(Op0))
5870     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5871       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5872         return R;
5873
5874   // See if we can turn a signed shr into an unsigned shr.
5875   if (I.isArithmeticShift()) {
5876     if (MaskedValueIsZero(Op0, 
5877           APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
5878       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5879     }
5880   }
5881
5882   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5883     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5884       return Res;
5885   return 0;
5886 }
5887
5888 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5889                                                BinaryOperator &I) {
5890   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5891
5892   // See if we can simplify any instructions used by the instruction whose sole 
5893   // purpose is to compute bits we don't care about.
5894   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5895   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5896   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5897                            KnownZero, KnownOne))
5898     return &I;
5899   
5900   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5901   // of a signed value.
5902   //
5903   if (Op1->uge(TypeBits)) {
5904     if (I.getOpcode() != Instruction::AShr)
5905       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5906     else {
5907       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5908       return &I;
5909     }
5910   }
5911   
5912   // ((X*C1) << C2) == (X * (C1 << C2))
5913   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5914     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5915       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5916         return BinaryOperator::createMul(BO->getOperand(0),
5917                                          ConstantExpr::getShl(BOOp, Op1));
5918   
5919   // Try to fold constant and into select arguments.
5920   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5921     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5922       return R;
5923   if (isa<PHINode>(Op0))
5924     if (Instruction *NV = FoldOpIntoPhi(I))
5925       return NV;
5926   
5927   if (Op0->hasOneUse()) {
5928     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5929       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5930       Value *V1, *V2;
5931       ConstantInt *CC;
5932       switch (Op0BO->getOpcode()) {
5933         default: break;
5934         case Instruction::Add:
5935         case Instruction::And:
5936         case Instruction::Or:
5937         case Instruction::Xor: {
5938           // These operators commute.
5939           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5940           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5941               match(Op0BO->getOperand(1),
5942                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5943             Instruction *YS = BinaryOperator::createShl(
5944                                             Op0BO->getOperand(0), Op1,
5945                                             Op0BO->getName());
5946             InsertNewInstBefore(YS, I); // (Y << C)
5947             Instruction *X = 
5948               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5949                                      Op0BO->getOperand(1)->getName());
5950             InsertNewInstBefore(X, I);  // (X + (Y << C))
5951             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5952             return BinaryOperator::createAnd(X, ConstantInt::get(
5953                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5954           }
5955           
5956           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5957           Value *Op0BOOp1 = Op0BO->getOperand(1);
5958           if (isLeftShift && Op0BOOp1->hasOneUse() &&
5959               match(Op0BOOp1, 
5960                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5961               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5962               V2 == Op1) {
5963             Instruction *YS = BinaryOperator::createShl(
5964                                                      Op0BO->getOperand(0), Op1,
5965                                                      Op0BO->getName());
5966             InsertNewInstBefore(YS, I); // (Y << C)
5967             Instruction *XM =
5968               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5969                                         V1->getName()+".mask");
5970             InsertNewInstBefore(XM, I); // X & (CC << C)
5971             
5972             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5973           }
5974         }
5975           
5976         // FALL THROUGH.
5977         case Instruction::Sub: {
5978           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5979           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5980               match(Op0BO->getOperand(0),
5981                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5982             Instruction *YS = BinaryOperator::createShl(
5983                                                      Op0BO->getOperand(1), Op1,
5984                                                      Op0BO->getName());
5985             InsertNewInstBefore(YS, I); // (Y << C)
5986             Instruction *X =
5987               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5988                                      Op0BO->getOperand(0)->getName());
5989             InsertNewInstBefore(X, I);  // (X + (Y << C))
5990             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5991             return BinaryOperator::createAnd(X, ConstantInt::get(
5992                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5993           }
5994           
5995           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5996           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5997               match(Op0BO->getOperand(0),
5998                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5999                           m_ConstantInt(CC))) && V2 == Op1 &&
6000               cast<BinaryOperator>(Op0BO->getOperand(0))
6001                   ->getOperand(0)->hasOneUse()) {
6002             Instruction *YS = BinaryOperator::createShl(
6003                                                      Op0BO->getOperand(1), Op1,
6004                                                      Op0BO->getName());
6005             InsertNewInstBefore(YS, I); // (Y << C)
6006             Instruction *XM =
6007               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6008                                         V1->getName()+".mask");
6009             InsertNewInstBefore(XM, I); // X & (CC << C)
6010             
6011             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6012           }
6013           
6014           break;
6015         }
6016       }
6017       
6018       
6019       // If the operand is an bitwise operator with a constant RHS, and the
6020       // shift is the only use, we can pull it out of the shift.
6021       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6022         bool isValid = true;     // Valid only for And, Or, Xor
6023         bool highBitSet = false; // Transform if high bit of constant set?
6024         
6025         switch (Op0BO->getOpcode()) {
6026           default: isValid = false; break;   // Do not perform transform!
6027           case Instruction::Add:
6028             isValid = isLeftShift;
6029             break;
6030           case Instruction::Or:
6031           case Instruction::Xor:
6032             highBitSet = false;
6033             break;
6034           case Instruction::And:
6035             highBitSet = true;
6036             break;
6037         }
6038         
6039         // If this is a signed shift right, and the high bit is modified
6040         // by the logical operation, do not perform the transformation.
6041         // The highBitSet boolean indicates the value of the high bit of
6042         // the constant which would cause it to be modified for this
6043         // operation.
6044         //
6045         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
6046           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6047         }
6048         
6049         if (isValid) {
6050           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6051           
6052           Instruction *NewShift =
6053             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6054           InsertNewInstBefore(NewShift, I);
6055           NewShift->takeName(Op0BO);
6056           
6057           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6058                                         NewRHS);
6059         }
6060       }
6061     }
6062   }
6063   
6064   // Find out if this is a shift of a shift by a constant.
6065   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6066   if (ShiftOp && !ShiftOp->isShift())
6067     ShiftOp = 0;
6068   
6069   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6070     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6071     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6072     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6073     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6074     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6075     Value *X = ShiftOp->getOperand(0);
6076     
6077     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6078     if (AmtSum > TypeBits)
6079       AmtSum = TypeBits;
6080     
6081     const IntegerType *Ty = cast<IntegerType>(I.getType());
6082     
6083     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6084     if (I.getOpcode() == ShiftOp->getOpcode()) {
6085       return BinaryOperator::create(I.getOpcode(), X,
6086                                     ConstantInt::get(Ty, AmtSum));
6087     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6088                I.getOpcode() == Instruction::AShr) {
6089       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6090       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6091     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6092                I.getOpcode() == Instruction::LShr) {
6093       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6094       Instruction *Shift =
6095         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6096       InsertNewInstBefore(Shift, I);
6097
6098       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6099       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6100     }
6101     
6102     // Okay, if we get here, one shift must be left, and the other shift must be
6103     // right.  See if the amounts are equal.
6104     if (ShiftAmt1 == ShiftAmt2) {
6105       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6106       if (I.getOpcode() == Instruction::Shl) {
6107         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6108         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6109       }
6110       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6111       if (I.getOpcode() == Instruction::LShr) {
6112         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6113         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6114       }
6115       // We can simplify ((X << C) >>s C) into a trunc + sext.
6116       // NOTE: we could do this for any C, but that would make 'unusual' integer
6117       // types.  For now, just stick to ones well-supported by the code
6118       // generators.
6119       const Type *SExtType = 0;
6120       switch (Ty->getBitWidth() - ShiftAmt1) {
6121       case 1  :
6122       case 8  :
6123       case 16 :
6124       case 32 :
6125       case 64 :
6126       case 128:
6127         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6128         break;
6129       default: break;
6130       }
6131       if (SExtType) {
6132         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6133         InsertNewInstBefore(NewTrunc, I);
6134         return new SExtInst(NewTrunc, Ty);
6135       }
6136       // Otherwise, we can't handle it yet.
6137     } else if (ShiftAmt1 < ShiftAmt2) {
6138       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6139       
6140       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6141       if (I.getOpcode() == Instruction::Shl) {
6142         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6143                ShiftOp->getOpcode() == Instruction::AShr);
6144         Instruction *Shift =
6145           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6146         InsertNewInstBefore(Shift, I);
6147         
6148         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6149         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6150       }
6151       
6152       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6153       if (I.getOpcode() == Instruction::LShr) {
6154         assert(ShiftOp->getOpcode() == Instruction::Shl);
6155         Instruction *Shift =
6156           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6157         InsertNewInstBefore(Shift, I);
6158         
6159         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6160         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6161       }
6162       
6163       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6164     } else {
6165       assert(ShiftAmt2 < ShiftAmt1);
6166       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6167
6168       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6169       if (I.getOpcode() == Instruction::Shl) {
6170         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6171                ShiftOp->getOpcode() == Instruction::AShr);
6172         Instruction *Shift =
6173           BinaryOperator::create(ShiftOp->getOpcode(), X,
6174                                  ConstantInt::get(Ty, ShiftDiff));
6175         InsertNewInstBefore(Shift, I);
6176         
6177         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6178         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6179       }
6180       
6181       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6182       if (I.getOpcode() == Instruction::LShr) {
6183         assert(ShiftOp->getOpcode() == Instruction::Shl);
6184         Instruction *Shift =
6185           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6186         InsertNewInstBefore(Shift, I);
6187         
6188         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6189         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6190       }
6191       
6192       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6193     }
6194   }
6195   return 0;
6196 }
6197
6198
6199 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6200 /// expression.  If so, decompose it, returning some value X, such that Val is
6201 /// X*Scale+Offset.
6202 ///
6203 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6204                                         int &Offset) {
6205   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6206   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6207     Offset = CI->getZExtValue();
6208     Scale  = 1;
6209     return ConstantInt::get(Type::Int32Ty, 0);
6210   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6211     if (I->getNumOperands() == 2) {
6212       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6213         if (I->getOpcode() == Instruction::Shl) {
6214           // This is a value scaled by '1 << the shift amt'.
6215           Scale = 1U << CUI->getZExtValue();
6216           Offset = 0;
6217           return I->getOperand(0);
6218         } else if (I->getOpcode() == Instruction::Mul) {
6219           // This value is scaled by 'CUI'.
6220           Scale = CUI->getZExtValue();
6221           Offset = 0;
6222           return I->getOperand(0);
6223         } else if (I->getOpcode() == Instruction::Add) {
6224           // We have X+C.  Check to see if we really have (X*C2)+C1, 
6225           // where C1 is divisible by C2.
6226           unsigned SubScale;
6227           Value *SubVal = 
6228             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6229           Offset += CUI->getZExtValue();
6230           if (SubScale > 1 && (Offset % SubScale == 0)) {
6231             Scale = SubScale;
6232             return SubVal;
6233           }
6234         }
6235       }
6236     }
6237   }
6238
6239   // Otherwise, we can't look past this.
6240   Scale = 1;
6241   Offset = 0;
6242   return Val;
6243 }
6244
6245
6246 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6247 /// try to eliminate the cast by moving the type information into the alloc.
6248 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6249                                                    AllocationInst &AI) {
6250   const PointerType *PTy = cast<PointerType>(CI.getType());
6251   
6252   // Remove any uses of AI that are dead.
6253   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6254   
6255   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6256     Instruction *User = cast<Instruction>(*UI++);
6257     if (isInstructionTriviallyDead(User)) {
6258       while (UI != E && *UI == User)
6259         ++UI; // If this instruction uses AI more than once, don't break UI.
6260       
6261       ++NumDeadInst;
6262       DOUT << "IC: DCE: " << *User;
6263       EraseInstFromFunction(*User);
6264     }
6265   }
6266   
6267   // Get the type really allocated and the type casted to.
6268   const Type *AllocElTy = AI.getAllocatedType();
6269   const Type *CastElTy = PTy->getElementType();
6270   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6271
6272   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6273   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6274   if (CastElTyAlign < AllocElTyAlign) return 0;
6275
6276   // If the allocation has multiple uses, only promote it if we are strictly
6277   // increasing the alignment of the resultant allocation.  If we keep it the
6278   // same, we open the door to infinite loops of various kinds.
6279   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6280
6281   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6282   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6283   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6284
6285   // See if we can satisfy the modulus by pulling a scale out of the array
6286   // size argument.
6287   unsigned ArraySizeScale;
6288   int ArrayOffset;
6289   Value *NumElements = // See if the array size is a decomposable linear expr.
6290     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6291  
6292   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6293   // do the xform.
6294   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6295       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6296
6297   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6298   Value *Amt = 0;
6299   if (Scale == 1) {
6300     Amt = NumElements;
6301   } else {
6302     // If the allocation size is constant, form a constant mul expression
6303     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6304     if (isa<ConstantInt>(NumElements))
6305       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6306     // otherwise multiply the amount and the number of elements
6307     else if (Scale != 1) {
6308       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6309       Amt = InsertNewInstBefore(Tmp, AI);
6310     }
6311   }
6312   
6313   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6314     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6315     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6316     Amt = InsertNewInstBefore(Tmp, AI);
6317   }
6318   
6319   AllocationInst *New;
6320   if (isa<MallocInst>(AI))
6321     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6322   else
6323     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6324   InsertNewInstBefore(New, AI);
6325   New->takeName(&AI);
6326   
6327   // If the allocation has multiple uses, insert a cast and change all things
6328   // that used it to use the new cast.  This will also hack on CI, but it will
6329   // die soon.
6330   if (!AI.hasOneUse()) {
6331     AddUsesToWorkList(AI);
6332     // New is the allocation instruction, pointer typed. AI is the original
6333     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6334     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6335     InsertNewInstBefore(NewCast, AI);
6336     AI.replaceAllUsesWith(NewCast);
6337   }
6338   return ReplaceInstUsesWith(CI, New);
6339 }
6340
6341 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6342 /// and return it as type Ty without inserting any new casts and without
6343 /// changing the computed value.  This is used by code that tries to decide
6344 /// whether promoting or shrinking integer operations to wider or smaller types
6345 /// will allow us to eliminate a truncate or extend.
6346 ///
6347 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6348 /// extension operation if Ty is larger.
6349 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6350                                        int &NumCastsRemoved) {
6351   // We can always evaluate constants in another type.
6352   if (isa<ConstantInt>(V))
6353     return true;
6354   
6355   Instruction *I = dyn_cast<Instruction>(V);
6356   if (!I) return false;
6357   
6358   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6359   
6360   switch (I->getOpcode()) {
6361   case Instruction::Add:
6362   case Instruction::Sub:
6363   case Instruction::And:
6364   case Instruction::Or:
6365   case Instruction::Xor:
6366     if (!I->hasOneUse()) return false;
6367     // These operators can all arbitrarily be extended or truncated.
6368     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6369            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6370
6371   case Instruction::Shl:
6372     if (!I->hasOneUse()) return false;
6373     // If we are truncating the result of this SHL, and if it's a shift of a
6374     // constant amount, we can always perform a SHL in a smaller type.
6375     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6376       uint32_t BitWidth = Ty->getBitWidth();
6377       if (BitWidth < OrigTy->getBitWidth() && 
6378           CI->getLimitedValue(BitWidth) < BitWidth)
6379         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6380     }
6381     break;
6382   case Instruction::LShr:
6383     if (!I->hasOneUse()) return false;
6384     // If this is a truncate of a logical shr, we can truncate it to a smaller
6385     // lshr iff we know that the bits we would otherwise be shifting in are
6386     // already zeros.
6387     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6388       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6389       uint32_t BitWidth = Ty->getBitWidth();
6390       if (BitWidth < OrigBitWidth &&
6391           MaskedValueIsZero(I->getOperand(0),
6392             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6393           CI->getLimitedValue(BitWidth) < BitWidth) {
6394         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6395       }
6396     }
6397     break;
6398   case Instruction::Trunc:
6399   case Instruction::ZExt:
6400   case Instruction::SExt:
6401     // If this is a cast from the destination type, we can trivially eliminate
6402     // it, and this will remove a cast overall.
6403     if (I->getOperand(0)->getType() == Ty) {
6404       // If the first operand is itself a cast, and is eliminable, do not count
6405       // this as an eliminable cast.  We would prefer to eliminate those two
6406       // casts first.
6407       if (isa<CastInst>(I->getOperand(0)))
6408         return true;
6409       
6410       ++NumCastsRemoved;
6411       return true;
6412     }
6413     break;
6414   default:
6415     // TODO: Can handle more cases here.
6416     break;
6417   }
6418   
6419   return false;
6420 }
6421
6422 /// EvaluateInDifferentType - Given an expression that 
6423 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6424 /// evaluate the expression.
6425 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6426                                              bool isSigned) {
6427   if (Constant *C = dyn_cast<Constant>(V))
6428     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6429
6430   // Otherwise, it must be an instruction.
6431   Instruction *I = cast<Instruction>(V);
6432   Instruction *Res = 0;
6433   switch (I->getOpcode()) {
6434   case Instruction::Add:
6435   case Instruction::Sub:
6436   case Instruction::And:
6437   case Instruction::Or:
6438   case Instruction::Xor:
6439   case Instruction::AShr:
6440   case Instruction::LShr:
6441   case Instruction::Shl: {
6442     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6443     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6444     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6445                                  LHS, RHS, I->getName());
6446     break;
6447   }    
6448   case Instruction::Trunc:
6449   case Instruction::ZExt:
6450   case Instruction::SExt:
6451   case Instruction::BitCast:
6452     // If the source type of the cast is the type we're trying for then we can
6453     // just return the source. There's no need to insert it because its not new.
6454     if (I->getOperand(0)->getType() == Ty)
6455       return I->getOperand(0);
6456     
6457     // Some other kind of cast, which shouldn't happen, so just ..
6458     // FALL THROUGH
6459   default: 
6460     // TODO: Can handle more cases here.
6461     assert(0 && "Unreachable!");
6462     break;
6463   }
6464   
6465   return InsertNewInstBefore(Res, *I);
6466 }
6467
6468 /// @brief Implement the transforms common to all CastInst visitors.
6469 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6470   Value *Src = CI.getOperand(0);
6471
6472   // Casting undef to anything results in undef so might as just replace it and
6473   // get rid of the cast.
6474   if (isa<UndefValue>(Src))   // cast undef -> undef
6475     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6476
6477   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6478   // eliminate it now.
6479   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6480     if (Instruction::CastOps opc = 
6481         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6482       // The first cast (CSrc) is eliminable so we need to fix up or replace
6483       // the second cast (CI). CSrc will then have a good chance of being dead.
6484       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6485     }
6486   }
6487
6488   // If we are casting a select then fold the cast into the select
6489   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6490     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6491       return NV;
6492
6493   // If we are casting a PHI then fold the cast into the PHI
6494   if (isa<PHINode>(Src))
6495     if (Instruction *NV = FoldOpIntoPhi(CI))
6496       return NV;
6497   
6498   return 0;
6499 }
6500
6501 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6502 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6503   Value *Src = CI.getOperand(0);
6504   
6505   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6506     // If casting the result of a getelementptr instruction with no offset, turn
6507     // this into a cast of the original pointer!
6508     if (GEP->hasAllZeroIndices()) {
6509       // Changing the cast operand is usually not a good idea but it is safe
6510       // here because the pointer operand is being replaced with another 
6511       // pointer operand so the opcode doesn't need to change.
6512       AddToWorkList(GEP);
6513       CI.setOperand(0, GEP->getOperand(0));
6514       return &CI;
6515     }
6516     
6517     // If the GEP has a single use, and the base pointer is a bitcast, and the
6518     // GEP computes a constant offset, see if we can convert these three
6519     // instructions into fewer.  This typically happens with unions and other
6520     // non-type-safe code.
6521     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6522       if (GEP->hasAllConstantIndices()) {
6523         // We are guaranteed to get a constant from EmitGEPOffset.
6524         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6525         int64_t Offset = OffsetV->getSExtValue();
6526         
6527         // Get the base pointer input of the bitcast, and the type it points to.
6528         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6529         const Type *GEPIdxTy =
6530           cast<PointerType>(OrigBase->getType())->getElementType();
6531         if (GEPIdxTy->isSized()) {
6532           SmallVector<Value*, 8> NewIndices;
6533           
6534           // Start with the index over the outer type.  Note that the type size
6535           // might be zero (even if the offset isn't zero) if the indexed type
6536           // is something like [0 x {int, int}]
6537           const Type *IntPtrTy = TD->getIntPtrType();
6538           int64_t FirstIdx = 0;
6539           if (int64_t TySize = TD->getTypeSize(GEPIdxTy)) {
6540             FirstIdx = Offset/TySize;
6541             Offset %= TySize;
6542           
6543             // Handle silly modulus not returning values values [0..TySize).
6544             if (Offset < 0) {
6545               --FirstIdx;
6546               Offset += TySize;
6547               assert(Offset >= 0);
6548             }
6549             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6550           }
6551           
6552           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6553
6554           // Index into the types.  If we fail, set OrigBase to null.
6555           while (Offset) {
6556             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6557               const StructLayout *SL = TD->getStructLayout(STy);
6558               if (Offset < (int64_t)SL->getSizeInBytes()) {
6559                 unsigned Elt = SL->getElementContainingOffset(Offset);
6560                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6561               
6562                 Offset -= SL->getElementOffset(Elt);
6563                 GEPIdxTy = STy->getElementType(Elt);
6564               } else {
6565                 // Otherwise, we can't index into this, bail out.
6566                 Offset = 0;
6567                 OrigBase = 0;
6568               }
6569             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6570               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6571               if (uint64_t EltSize = TD->getTypeSize(STy->getElementType())) {
6572                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6573                 Offset %= EltSize;
6574               } else {
6575                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6576               }
6577               GEPIdxTy = STy->getElementType();
6578             } else {
6579               // Otherwise, we can't index into this, bail out.
6580               Offset = 0;
6581               OrigBase = 0;
6582             }
6583           }
6584           if (OrigBase) {
6585             // If we were able to index down into an element, create the GEP
6586             // and bitcast the result.  This eliminates one bitcast, potentially
6587             // two.
6588             Instruction *NGEP = new GetElementPtrInst(OrigBase, &NewIndices[0],
6589                                                       NewIndices.size(), "");
6590             InsertNewInstBefore(NGEP, CI);
6591             NGEP->takeName(GEP);
6592             
6593             if (isa<BitCastInst>(CI))
6594               return new BitCastInst(NGEP, CI.getType());
6595             assert(isa<PtrToIntInst>(CI));
6596             return new PtrToIntInst(NGEP, CI.getType());
6597           }
6598         }
6599       }      
6600     }
6601   }
6602     
6603   return commonCastTransforms(CI);
6604 }
6605
6606
6607
6608 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6609 /// integer types. This function implements the common transforms for all those
6610 /// cases.
6611 /// @brief Implement the transforms common to CastInst with integer operands
6612 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6613   if (Instruction *Result = commonCastTransforms(CI))
6614     return Result;
6615
6616   Value *Src = CI.getOperand(0);
6617   const Type *SrcTy = Src->getType();
6618   const Type *DestTy = CI.getType();
6619   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6620   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6621
6622   // See if we can simplify any instructions used by the LHS whose sole 
6623   // purpose is to compute bits we don't care about.
6624   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6625   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6626                            KnownZero, KnownOne))
6627     return &CI;
6628
6629   // If the source isn't an instruction or has more than one use then we
6630   // can't do anything more. 
6631   Instruction *SrcI = dyn_cast<Instruction>(Src);
6632   if (!SrcI || !Src->hasOneUse())
6633     return 0;
6634
6635   // Attempt to propagate the cast into the instruction for int->int casts.
6636   int NumCastsRemoved = 0;
6637   if (!isa<BitCastInst>(CI) &&
6638       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6639                                  NumCastsRemoved)) {
6640     // If this cast is a truncate, evaluting in a different type always
6641     // eliminates the cast, so it is always a win.  If this is a noop-cast
6642     // this just removes a noop cast which isn't pointful, but simplifies
6643     // the code.  If this is a zero-extension, we need to do an AND to
6644     // maintain the clear top-part of the computation, so we require that
6645     // the input have eliminated at least one cast.  If this is a sign
6646     // extension, we insert two new casts (to do the extension) so we
6647     // require that two casts have been eliminated.
6648     bool DoXForm;
6649     switch (CI.getOpcode()) {
6650     default:
6651       // All the others use floating point so we shouldn't actually 
6652       // get here because of the check above.
6653       assert(0 && "Unknown cast type");
6654     case Instruction::Trunc:
6655       DoXForm = true;
6656       break;
6657     case Instruction::ZExt:
6658       DoXForm = NumCastsRemoved >= 1;
6659       break;
6660     case Instruction::SExt:
6661       DoXForm = NumCastsRemoved >= 2;
6662       break;
6663     case Instruction::BitCast:
6664       DoXForm = false;
6665       break;
6666     }
6667     
6668     if (DoXForm) {
6669       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6670                                            CI.getOpcode() == Instruction::SExt);
6671       assert(Res->getType() == DestTy);
6672       switch (CI.getOpcode()) {
6673       default: assert(0 && "Unknown cast type!");
6674       case Instruction::Trunc:
6675       case Instruction::BitCast:
6676         // Just replace this cast with the result.
6677         return ReplaceInstUsesWith(CI, Res);
6678       case Instruction::ZExt: {
6679         // We need to emit an AND to clear the high bits.
6680         assert(SrcBitSize < DestBitSize && "Not a zext?");
6681         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6682                                                             SrcBitSize));
6683         return BinaryOperator::createAnd(Res, C);
6684       }
6685       case Instruction::SExt:
6686         // We need to emit a cast to truncate, then a cast to sext.
6687         return CastInst::create(Instruction::SExt,
6688             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6689                              CI), DestTy);
6690       }
6691     }
6692   }
6693   
6694   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6695   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6696
6697   switch (SrcI->getOpcode()) {
6698   case Instruction::Add:
6699   case Instruction::Mul:
6700   case Instruction::And:
6701   case Instruction::Or:
6702   case Instruction::Xor:
6703     // If we are discarding information, rewrite.
6704     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6705       // Don't insert two casts if they cannot be eliminated.  We allow 
6706       // two casts to be inserted if the sizes are the same.  This could 
6707       // only be converting signedness, which is a noop.
6708       if (DestBitSize == SrcBitSize || 
6709           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6710           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6711         Instruction::CastOps opcode = CI.getOpcode();
6712         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6713         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6714         return BinaryOperator::create(
6715             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6716       }
6717     }
6718
6719     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6720     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6721         SrcI->getOpcode() == Instruction::Xor &&
6722         Op1 == ConstantInt::getTrue() &&
6723         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6724       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6725       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6726     }
6727     break;
6728   case Instruction::SDiv:
6729   case Instruction::UDiv:
6730   case Instruction::SRem:
6731   case Instruction::URem:
6732     // If we are just changing the sign, rewrite.
6733     if (DestBitSize == SrcBitSize) {
6734       // Don't insert two casts if they cannot be eliminated.  We allow 
6735       // two casts to be inserted if the sizes are the same.  This could 
6736       // only be converting signedness, which is a noop.
6737       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6738           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6739         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6740                                               Op0, DestTy, SrcI);
6741         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6742                                               Op1, DestTy, SrcI);
6743         return BinaryOperator::create(
6744           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6745       }
6746     }
6747     break;
6748
6749   case Instruction::Shl:
6750     // Allow changing the sign of the source operand.  Do not allow 
6751     // changing the size of the shift, UNLESS the shift amount is a 
6752     // constant.  We must not change variable sized shifts to a smaller 
6753     // size, because it is undefined to shift more bits out than exist 
6754     // in the value.
6755     if (DestBitSize == SrcBitSize ||
6756         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6757       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6758           Instruction::BitCast : Instruction::Trunc);
6759       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6760       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6761       return BinaryOperator::createShl(Op0c, Op1c);
6762     }
6763     break;
6764   case Instruction::AShr:
6765     // If this is a signed shr, and if all bits shifted in are about to be
6766     // truncated off, turn it into an unsigned shr to allow greater
6767     // simplifications.
6768     if (DestBitSize < SrcBitSize &&
6769         isa<ConstantInt>(Op1)) {
6770       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6771       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6772         // Insert the new logical shift right.
6773         return BinaryOperator::createLShr(Op0, Op1);
6774       }
6775     }
6776     break;
6777   }
6778   return 0;
6779 }
6780
6781 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6782   if (Instruction *Result = commonIntCastTransforms(CI))
6783     return Result;
6784   
6785   Value *Src = CI.getOperand(0);
6786   const Type *Ty = CI.getType();
6787   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6788   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6789   
6790   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6791     switch (SrcI->getOpcode()) {
6792     default: break;
6793     case Instruction::LShr:
6794       // We can shrink lshr to something smaller if we know the bits shifted in
6795       // are already zeros.
6796       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6797         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6798         
6799         // Get a mask for the bits shifting in.
6800         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6801         Value* SrcIOp0 = SrcI->getOperand(0);
6802         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6803           if (ShAmt >= DestBitWidth)        // All zeros.
6804             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6805
6806           // Okay, we can shrink this.  Truncate the input, then return a new
6807           // shift.
6808           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6809           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6810                                        Ty, CI);
6811           return BinaryOperator::createLShr(V1, V2);
6812         }
6813       } else {     // This is a variable shr.
6814         
6815         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6816         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6817         // loop-invariant and CSE'd.
6818         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6819           Value *One = ConstantInt::get(SrcI->getType(), 1);
6820
6821           Value *V = InsertNewInstBefore(
6822               BinaryOperator::createShl(One, SrcI->getOperand(1),
6823                                      "tmp"), CI);
6824           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6825                                                             SrcI->getOperand(0),
6826                                                             "tmp"), CI);
6827           Value *Zero = Constant::getNullValue(V->getType());
6828           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6829         }
6830       }
6831       break;
6832     }
6833   }
6834   
6835   return 0;
6836 }
6837
6838 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6839   // If one of the common conversion will work ..
6840   if (Instruction *Result = commonIntCastTransforms(CI))
6841     return Result;
6842
6843   Value *Src = CI.getOperand(0);
6844
6845   // If this is a cast of a cast
6846   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6847     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6848     // types and if the sizes are just right we can convert this into a logical
6849     // 'and' which will be much cheaper than the pair of casts.
6850     if (isa<TruncInst>(CSrc)) {
6851       // Get the sizes of the types involved
6852       Value *A = CSrc->getOperand(0);
6853       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6854       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6855       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6856       // If we're actually extending zero bits and the trunc is a no-op
6857       if (MidSize < DstSize && SrcSize == DstSize) {
6858         // Replace both of the casts with an And of the type mask.
6859         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
6860         Constant *AndConst = ConstantInt::get(AndValue);
6861         Instruction *And = 
6862           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6863         // Unfortunately, if the type changed, we need to cast it back.
6864         if (And->getType() != CI.getType()) {
6865           And->setName(CSrc->getName()+".mask");
6866           InsertNewInstBefore(And, CI);
6867           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6868         }
6869         return And;
6870       }
6871     }
6872   }
6873
6874   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6875     // If we are just checking for a icmp eq of a single bit and zext'ing it
6876     // to an integer, then shift the bit to the appropriate place and then
6877     // cast to integer to avoid the comparison.
6878     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6879       const APInt &Op1CV = Op1C->getValue();
6880       
6881       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
6882       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
6883       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6884           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6885         Value *In = ICI->getOperand(0);
6886         Value *Sh = ConstantInt::get(In->getType(),
6887                                     In->getType()->getPrimitiveSizeInBits()-1);
6888         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
6889                                                         In->getName()+".lobit"),
6890                                  CI);
6891         if (In->getType() != CI.getType())
6892           In = CastInst::createIntegerCast(In, CI.getType(),
6893                                            false/*ZExt*/, "tmp", &CI);
6894
6895         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6896           Constant *One = ConstantInt::get(In->getType(), 1);
6897           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
6898                                                           In->getName()+".not"),
6899                                    CI);
6900         }
6901
6902         return ReplaceInstUsesWith(CI, In);
6903       }
6904       
6905       
6906       
6907       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
6908       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6909       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
6910       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
6911       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
6912       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
6913       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
6914       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6915       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
6916           // This only works for EQ and NE
6917           ICI->isEquality()) {
6918         // If Op1C some other power of two, convert:
6919         uint32_t BitWidth = Op1C->getType()->getBitWidth();
6920         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6921         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6922         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6923         
6924         APInt KnownZeroMask(~KnownZero);
6925         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6926           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6927           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6928             // (X&4) == 2 --> false
6929             // (X&4) != 2 --> true
6930             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6931             Res = ConstantExpr::getZExt(Res, CI.getType());
6932             return ReplaceInstUsesWith(CI, Res);
6933           }
6934           
6935           uint32_t ShiftAmt = KnownZeroMask.logBase2();
6936           Value *In = ICI->getOperand(0);
6937           if (ShiftAmt) {
6938             // Perform a logical shr by shiftamt.
6939             // Insert the shift to put the result in the low bit.
6940             In = InsertNewInstBefore(
6941                    BinaryOperator::createLShr(In,
6942                                      ConstantInt::get(In->getType(), ShiftAmt),
6943                                               In->getName()+".lobit"), CI);
6944           }
6945           
6946           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6947             Constant *One = ConstantInt::get(In->getType(), 1);
6948             In = BinaryOperator::createXor(In, One, "tmp");
6949             InsertNewInstBefore(cast<Instruction>(In), CI);
6950           }
6951           
6952           if (CI.getType() == In->getType())
6953             return ReplaceInstUsesWith(CI, In);
6954           else
6955             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6956         }
6957       }
6958     }
6959   }    
6960   return 0;
6961 }
6962
6963 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
6964   if (Instruction *I = commonIntCastTransforms(CI))
6965     return I;
6966   
6967   Value *Src = CI.getOperand(0);
6968   
6969   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
6970   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
6971   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6972     // If we are just checking for a icmp eq of a single bit and zext'ing it
6973     // to an integer, then shift the bit to the appropriate place and then
6974     // cast to integer to avoid the comparison.
6975     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6976       const APInt &Op1CV = Op1C->getValue();
6977       
6978       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
6979       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
6980       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6981           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6982         Value *In = ICI->getOperand(0);
6983         Value *Sh = ConstantInt::get(In->getType(),
6984                                      In->getType()->getPrimitiveSizeInBits()-1);
6985         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
6986                                                         In->getName()+".lobit"),
6987                                  CI);
6988         if (In->getType() != CI.getType())
6989           In = CastInst::createIntegerCast(In, CI.getType(),
6990                                            true/*SExt*/, "tmp", &CI);
6991         
6992         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6993           In = InsertNewInstBefore(BinaryOperator::createNot(In,
6994                                      In->getName()+".not"), CI);
6995         
6996         return ReplaceInstUsesWith(CI, In);
6997       }
6998     }
6999   }
7000       
7001   return 0;
7002 }
7003
7004 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7005   return commonCastTransforms(CI);
7006 }
7007
7008 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7009   return commonCastTransforms(CI);
7010 }
7011
7012 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7013   return commonCastTransforms(CI);
7014 }
7015
7016 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7017   return commonCastTransforms(CI);
7018 }
7019
7020 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7021   return commonCastTransforms(CI);
7022 }
7023
7024 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7025   return commonCastTransforms(CI);
7026 }
7027
7028 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7029   return commonPointerCastTransforms(CI);
7030 }
7031
7032 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7033   return commonCastTransforms(CI);
7034 }
7035
7036 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7037   // If the operands are integer typed then apply the integer transforms,
7038   // otherwise just apply the common ones.
7039   Value *Src = CI.getOperand(0);
7040   const Type *SrcTy = Src->getType();
7041   const Type *DestTy = CI.getType();
7042
7043   if (SrcTy->isInteger() && DestTy->isInteger()) {
7044     if (Instruction *Result = commonIntCastTransforms(CI))
7045       return Result;
7046   } else if (isa<PointerType>(SrcTy)) {
7047     if (Instruction *I = commonPointerCastTransforms(CI))
7048       return I;
7049   } else {
7050     if (Instruction *Result = commonCastTransforms(CI))
7051       return Result;
7052   }
7053
7054
7055   // Get rid of casts from one type to the same type. These are useless and can
7056   // be replaced by the operand.
7057   if (DestTy == Src->getType())
7058     return ReplaceInstUsesWith(CI, Src);
7059
7060   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7061     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7062     const Type *DstElTy = DstPTy->getElementType();
7063     const Type *SrcElTy = SrcPTy->getElementType();
7064     
7065     // If we are casting a malloc or alloca to a pointer to a type of the same
7066     // size, rewrite the allocation instruction to allocate the "right" type.
7067     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7068       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7069         return V;
7070     
7071     // If the source and destination are pointers, and this cast is equivalent
7072     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7073     // This can enhance SROA and other transforms that want type-safe pointers.
7074     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7075     unsigned NumZeros = 0;
7076     while (SrcElTy != DstElTy && 
7077            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7078            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7079       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7080       ++NumZeros;
7081     }
7082
7083     // If we found a path from the src to dest, create the getelementptr now.
7084     if (SrcElTy == DstElTy) {
7085       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7086       return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
7087     }
7088   }
7089
7090   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7091     if (SVI->hasOneUse()) {
7092       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7093       // a bitconvert to a vector with the same # elts.
7094       if (isa<VectorType>(DestTy) && 
7095           cast<VectorType>(DestTy)->getNumElements() == 
7096                 SVI->getType()->getNumElements()) {
7097         CastInst *Tmp;
7098         // If either of the operands is a cast from CI.getType(), then
7099         // evaluating the shuffle in the casted destination's type will allow
7100         // us to eliminate at least one cast.
7101         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7102              Tmp->getOperand(0)->getType() == DestTy) ||
7103             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7104              Tmp->getOperand(0)->getType() == DestTy)) {
7105           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7106                                                SVI->getOperand(0), DestTy, &CI);
7107           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7108                                                SVI->getOperand(1), DestTy, &CI);
7109           // Return a new shuffle vector.  Use the same element ID's, as we
7110           // know the vector types match #elts.
7111           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7112         }
7113       }
7114     }
7115   }
7116   return 0;
7117 }
7118
7119 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7120 ///   %C = or %A, %B
7121 ///   %D = select %cond, %C, %A
7122 /// into:
7123 ///   %C = select %cond, %B, 0
7124 ///   %D = or %A, %C
7125 ///
7126 /// Assuming that the specified instruction is an operand to the select, return
7127 /// a bitmask indicating which operands of this instruction are foldable if they
7128 /// equal the other incoming value of the select.
7129 ///
7130 static unsigned GetSelectFoldableOperands(Instruction *I) {
7131   switch (I->getOpcode()) {
7132   case Instruction::Add:
7133   case Instruction::Mul:
7134   case Instruction::And:
7135   case Instruction::Or:
7136   case Instruction::Xor:
7137     return 3;              // Can fold through either operand.
7138   case Instruction::Sub:   // Can only fold on the amount subtracted.
7139   case Instruction::Shl:   // Can only fold on the shift amount.
7140   case Instruction::LShr:
7141   case Instruction::AShr:
7142     return 1;
7143   default:
7144     return 0;              // Cannot fold
7145   }
7146 }
7147
7148 /// GetSelectFoldableConstant - For the same transformation as the previous
7149 /// function, return the identity constant that goes into the select.
7150 static Constant *GetSelectFoldableConstant(Instruction *I) {
7151   switch (I->getOpcode()) {
7152   default: assert(0 && "This cannot happen!"); abort();
7153   case Instruction::Add:
7154   case Instruction::Sub:
7155   case Instruction::Or:
7156   case Instruction::Xor:
7157   case Instruction::Shl:
7158   case Instruction::LShr:
7159   case Instruction::AShr:
7160     return Constant::getNullValue(I->getType());
7161   case Instruction::And:
7162     return Constant::getAllOnesValue(I->getType());
7163   case Instruction::Mul:
7164     return ConstantInt::get(I->getType(), 1);
7165   }
7166 }
7167
7168 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7169 /// have the same opcode and only one use each.  Try to simplify this.
7170 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7171                                           Instruction *FI) {
7172   if (TI->getNumOperands() == 1) {
7173     // If this is a non-volatile load or a cast from the same type,
7174     // merge.
7175     if (TI->isCast()) {
7176       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7177         return 0;
7178     } else {
7179       return 0;  // unknown unary op.
7180     }
7181
7182     // Fold this by inserting a select from the input values.
7183     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7184                                        FI->getOperand(0), SI.getName()+".v");
7185     InsertNewInstBefore(NewSI, SI);
7186     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7187                             TI->getType());
7188   }
7189
7190   // Only handle binary operators here.
7191   if (!isa<BinaryOperator>(TI))
7192     return 0;
7193
7194   // Figure out if the operations have any operands in common.
7195   Value *MatchOp, *OtherOpT, *OtherOpF;
7196   bool MatchIsOpZero;
7197   if (TI->getOperand(0) == FI->getOperand(0)) {
7198     MatchOp  = TI->getOperand(0);
7199     OtherOpT = TI->getOperand(1);
7200     OtherOpF = FI->getOperand(1);
7201     MatchIsOpZero = true;
7202   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7203     MatchOp  = TI->getOperand(1);
7204     OtherOpT = TI->getOperand(0);
7205     OtherOpF = FI->getOperand(0);
7206     MatchIsOpZero = false;
7207   } else if (!TI->isCommutative()) {
7208     return 0;
7209   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7210     MatchOp  = TI->getOperand(0);
7211     OtherOpT = TI->getOperand(1);
7212     OtherOpF = FI->getOperand(0);
7213     MatchIsOpZero = true;
7214   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7215     MatchOp  = TI->getOperand(1);
7216     OtherOpT = TI->getOperand(0);
7217     OtherOpF = FI->getOperand(1);
7218     MatchIsOpZero = true;
7219   } else {
7220     return 0;
7221   }
7222
7223   // If we reach here, they do have operations in common.
7224   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7225                                      OtherOpF, SI.getName()+".v");
7226   InsertNewInstBefore(NewSI, SI);
7227
7228   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7229     if (MatchIsOpZero)
7230       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7231     else
7232       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7233   }
7234   assert(0 && "Shouldn't get here");
7235   return 0;
7236 }
7237
7238 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7239   Value *CondVal = SI.getCondition();
7240   Value *TrueVal = SI.getTrueValue();
7241   Value *FalseVal = SI.getFalseValue();
7242
7243   // select true, X, Y  -> X
7244   // select false, X, Y -> Y
7245   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7246     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7247
7248   // select C, X, X -> X
7249   if (TrueVal == FalseVal)
7250     return ReplaceInstUsesWith(SI, TrueVal);
7251
7252   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7253     return ReplaceInstUsesWith(SI, FalseVal);
7254   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7255     return ReplaceInstUsesWith(SI, TrueVal);
7256   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7257     if (isa<Constant>(TrueVal))
7258       return ReplaceInstUsesWith(SI, TrueVal);
7259     else
7260       return ReplaceInstUsesWith(SI, FalseVal);
7261   }
7262
7263   if (SI.getType() == Type::Int1Ty) {
7264     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7265       if (C->getZExtValue()) {
7266         // Change: A = select B, true, C --> A = or B, C
7267         return BinaryOperator::createOr(CondVal, FalseVal);
7268       } else {
7269         // Change: A = select B, false, C --> A = and !B, C
7270         Value *NotCond =
7271           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7272                                              "not."+CondVal->getName()), SI);
7273         return BinaryOperator::createAnd(NotCond, FalseVal);
7274       }
7275     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7276       if (C->getZExtValue() == false) {
7277         // Change: A = select B, C, false --> A = and B, C
7278         return BinaryOperator::createAnd(CondVal, TrueVal);
7279       } else {
7280         // Change: A = select B, C, true --> A = or !B, C
7281         Value *NotCond =
7282           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7283                                              "not."+CondVal->getName()), SI);
7284         return BinaryOperator::createOr(NotCond, TrueVal);
7285       }
7286     }
7287   }
7288
7289   // Selecting between two integer constants?
7290   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7291     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7292       // select C, 1, 0 -> zext C to int
7293       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7294         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7295       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7296         // select C, 0, 1 -> zext !C to int
7297         Value *NotCond =
7298           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7299                                                "not."+CondVal->getName()), SI);
7300         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7301       }
7302       
7303       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7304
7305       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7306
7307         // (x <s 0) ? -1 : 0 -> ashr x, 31
7308         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7309           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7310             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7311               // The comparison constant and the result are not neccessarily the
7312               // same width. Make an all-ones value by inserting a AShr.
7313               Value *X = IC->getOperand(0);
7314               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7315               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7316               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7317                                                         ShAmt, "ones");
7318               InsertNewInstBefore(SRA, SI);
7319               
7320               // Finally, convert to the type of the select RHS.  We figure out
7321               // if this requires a SExt, Trunc or BitCast based on the sizes.
7322               Instruction::CastOps opc = Instruction::BitCast;
7323               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7324               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7325               if (SRASize < SISize)
7326                 opc = Instruction::SExt;
7327               else if (SRASize > SISize)
7328                 opc = Instruction::Trunc;
7329               return CastInst::create(opc, SRA, SI.getType());
7330             }
7331           }
7332
7333
7334         // If one of the constants is zero (we know they can't both be) and we
7335         // have an icmp instruction with zero, and we have an 'and' with the
7336         // non-constant value, eliminate this whole mess.  This corresponds to
7337         // cases like this: ((X & 27) ? 27 : 0)
7338         if (TrueValC->isZero() || FalseValC->isZero())
7339           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7340               cast<Constant>(IC->getOperand(1))->isNullValue())
7341             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7342               if (ICA->getOpcode() == Instruction::And &&
7343                   isa<ConstantInt>(ICA->getOperand(1)) &&
7344                   (ICA->getOperand(1) == TrueValC ||
7345                    ICA->getOperand(1) == FalseValC) &&
7346                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7347                 // Okay, now we know that everything is set up, we just don't
7348                 // know whether we have a icmp_ne or icmp_eq and whether the 
7349                 // true or false val is the zero.
7350                 bool ShouldNotVal = !TrueValC->isZero();
7351                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7352                 Value *V = ICA;
7353                 if (ShouldNotVal)
7354                   V = InsertNewInstBefore(BinaryOperator::create(
7355                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7356                 return ReplaceInstUsesWith(SI, V);
7357               }
7358       }
7359     }
7360
7361   // See if we are selecting two values based on a comparison of the two values.
7362   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7363     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7364       // Transform (X == Y) ? X : Y  -> Y
7365       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7366         return ReplaceInstUsesWith(SI, FalseVal);
7367       // Transform (X != Y) ? X : Y  -> X
7368       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7369         return ReplaceInstUsesWith(SI, TrueVal);
7370       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7371
7372     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7373       // Transform (X == Y) ? Y : X  -> X
7374       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7375         return ReplaceInstUsesWith(SI, FalseVal);
7376       // Transform (X != Y) ? Y : X  -> Y
7377       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7378         return ReplaceInstUsesWith(SI, TrueVal);
7379       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7380     }
7381   }
7382
7383   // See if we are selecting two values based on a comparison of the two values.
7384   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7385     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7386       // Transform (X == Y) ? X : Y  -> Y
7387       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7388         return ReplaceInstUsesWith(SI, FalseVal);
7389       // Transform (X != Y) ? X : Y  -> X
7390       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7391         return ReplaceInstUsesWith(SI, TrueVal);
7392       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7393
7394     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7395       // Transform (X == Y) ? Y : X  -> X
7396       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7397         return ReplaceInstUsesWith(SI, FalseVal);
7398       // Transform (X != Y) ? Y : X  -> Y
7399       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7400         return ReplaceInstUsesWith(SI, TrueVal);
7401       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7402     }
7403   }
7404
7405   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7406     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7407       if (TI->hasOneUse() && FI->hasOneUse()) {
7408         Instruction *AddOp = 0, *SubOp = 0;
7409
7410         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7411         if (TI->getOpcode() == FI->getOpcode())
7412           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7413             return IV;
7414
7415         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7416         // even legal for FP.
7417         if (TI->getOpcode() == Instruction::Sub &&
7418             FI->getOpcode() == Instruction::Add) {
7419           AddOp = FI; SubOp = TI;
7420         } else if (FI->getOpcode() == Instruction::Sub &&
7421                    TI->getOpcode() == Instruction::Add) {
7422           AddOp = TI; SubOp = FI;
7423         }
7424
7425         if (AddOp) {
7426           Value *OtherAddOp = 0;
7427           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7428             OtherAddOp = AddOp->getOperand(1);
7429           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7430             OtherAddOp = AddOp->getOperand(0);
7431           }
7432
7433           if (OtherAddOp) {
7434             // So at this point we know we have (Y -> OtherAddOp):
7435             //        select C, (add X, Y), (sub X, Z)
7436             Value *NegVal;  // Compute -Z
7437             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7438               NegVal = ConstantExpr::getNeg(C);
7439             } else {
7440               NegVal = InsertNewInstBefore(
7441                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7442             }
7443
7444             Value *NewTrueOp = OtherAddOp;
7445             Value *NewFalseOp = NegVal;
7446             if (AddOp != TI)
7447               std::swap(NewTrueOp, NewFalseOp);
7448             Instruction *NewSel =
7449               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7450
7451             NewSel = InsertNewInstBefore(NewSel, SI);
7452             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7453           }
7454         }
7455       }
7456
7457   // See if we can fold the select into one of our operands.
7458   if (SI.getType()->isInteger()) {
7459     // See the comment above GetSelectFoldableOperands for a description of the
7460     // transformation we are doing here.
7461     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7462       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7463           !isa<Constant>(FalseVal))
7464         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7465           unsigned OpToFold = 0;
7466           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7467             OpToFold = 1;
7468           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7469             OpToFold = 2;
7470           }
7471
7472           if (OpToFold) {
7473             Constant *C = GetSelectFoldableConstant(TVI);
7474             Instruction *NewSel =
7475               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7476             InsertNewInstBefore(NewSel, SI);
7477             NewSel->takeName(TVI);
7478             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7479               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7480             else {
7481               assert(0 && "Unknown instruction!!");
7482             }
7483           }
7484         }
7485
7486     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7487       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7488           !isa<Constant>(TrueVal))
7489         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7490           unsigned OpToFold = 0;
7491           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7492             OpToFold = 1;
7493           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7494             OpToFold = 2;
7495           }
7496
7497           if (OpToFold) {
7498             Constant *C = GetSelectFoldableConstant(FVI);
7499             Instruction *NewSel =
7500               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7501             InsertNewInstBefore(NewSel, SI);
7502             NewSel->takeName(FVI);
7503             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7504               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7505             else
7506               assert(0 && "Unknown instruction!!");
7507           }
7508         }
7509   }
7510
7511   if (BinaryOperator::isNot(CondVal)) {
7512     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7513     SI.setOperand(1, FalseVal);
7514     SI.setOperand(2, TrueVal);
7515     return &SI;
7516   }
7517
7518   return 0;
7519 }
7520
7521 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7522 /// determine, return it, otherwise return 0.
7523 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7524   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7525     unsigned Align = GV->getAlignment();
7526     if (Align == 0 && TD) 
7527       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7528     return Align;
7529   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7530     unsigned Align = AI->getAlignment();
7531     if (Align == 0 && TD) {
7532       if (isa<AllocaInst>(AI))
7533         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7534       else if (isa<MallocInst>(AI)) {
7535         // Malloc returns maximally aligned memory.
7536         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7537         Align =
7538           std::max(Align,
7539                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7540         Align =
7541           std::max(Align,
7542                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7543       }
7544     }
7545     return Align;
7546   } else if (isa<BitCastInst>(V) ||
7547              (isa<ConstantExpr>(V) && 
7548               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7549     User *CI = cast<User>(V);
7550     if (isa<PointerType>(CI->getOperand(0)->getType()))
7551       return GetKnownAlignment(CI->getOperand(0), TD);
7552     return 0;
7553   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7554     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7555     if (BaseAlignment == 0) return 0;
7556     
7557     // If all indexes are zero, it is just the alignment of the base pointer.
7558     bool AllZeroOperands = true;
7559     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7560       if (!isa<Constant>(GEPI->getOperand(i)) ||
7561           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7562         AllZeroOperands = false;
7563         break;
7564       }
7565     if (AllZeroOperands)
7566       return BaseAlignment;
7567     
7568     // Otherwise, if the base alignment is >= the alignment we expect for the
7569     // base pointer type, then we know that the resultant pointer is aligned at
7570     // least as much as its type requires.
7571     if (!TD) return 0;
7572
7573     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7574     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7575     if (TD->getABITypeAlignment(PtrTy->getElementType())
7576         <= BaseAlignment) {
7577       const Type *GEPTy = GEPI->getType();
7578       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7579       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7580     }
7581     return 0;
7582   }
7583   return 0;
7584 }
7585
7586
7587 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7588 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7589 /// the heavy lifting.
7590 ///
7591 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7592   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7593   if (!II) return visitCallSite(&CI);
7594   
7595   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7596   // visitCallSite.
7597   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7598     bool Changed = false;
7599
7600     // memmove/cpy/set of zero bytes is a noop.
7601     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7602       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7603
7604       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7605         if (CI->getZExtValue() == 1) {
7606           // Replace the instruction with just byte operations.  We would
7607           // transform other cases to loads/stores, but we don't know if
7608           // alignment is sufficient.
7609         }
7610     }
7611
7612     // If we have a memmove and the source operation is a constant global,
7613     // then the source and dest pointers can't alias, so we can change this
7614     // into a call to memcpy.
7615     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7616       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7617         if (GVSrc->isConstant()) {
7618           Module *M = CI.getParent()->getParent()->getParent();
7619           const char *Name;
7620           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7621               Type::Int32Ty)
7622             Name = "llvm.memcpy.i32";
7623           else
7624             Name = "llvm.memcpy.i64";
7625           Constant *MemCpy = M->getOrInsertFunction(Name,
7626                                      CI.getCalledFunction()->getFunctionType());
7627           CI.setOperand(0, MemCpy);
7628           Changed = true;
7629         }
7630     }
7631
7632     // If we can determine a pointer alignment that is bigger than currently
7633     // set, update the alignment.
7634     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7635       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7636       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7637       unsigned Align = std::min(Alignment1, Alignment2);
7638       if (MI->getAlignment()->getZExtValue() < Align) {
7639         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7640         Changed = true;
7641       }
7642     } else if (isa<MemSetInst>(MI)) {
7643       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7644       if (MI->getAlignment()->getZExtValue() < Alignment) {
7645         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7646         Changed = true;
7647       }
7648     }
7649           
7650     if (Changed) return II;
7651   } else {
7652     switch (II->getIntrinsicID()) {
7653     default: break;
7654     case Intrinsic::ppc_altivec_lvx:
7655     case Intrinsic::ppc_altivec_lvxl:
7656     case Intrinsic::x86_sse_loadu_ps:
7657     case Intrinsic::x86_sse2_loadu_pd:
7658     case Intrinsic::x86_sse2_loadu_dq:
7659       // Turn PPC lvx     -> load if the pointer is known aligned.
7660       // Turn X86 loadups -> load if the pointer is known aligned.
7661       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7662         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7663                                       PointerType::get(II->getType()), CI);
7664         return new LoadInst(Ptr);
7665       }
7666       break;
7667     case Intrinsic::ppc_altivec_stvx:
7668     case Intrinsic::ppc_altivec_stvxl:
7669       // Turn stvx -> store if the pointer is known aligned.
7670       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7671         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7672         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7673                                       OpPtrTy, CI);
7674         return new StoreInst(II->getOperand(1), Ptr);
7675       }
7676       break;
7677     case Intrinsic::x86_sse_storeu_ps:
7678     case Intrinsic::x86_sse2_storeu_pd:
7679     case Intrinsic::x86_sse2_storeu_dq:
7680     case Intrinsic::x86_sse2_storel_dq:
7681       // Turn X86 storeu -> store if the pointer is known aligned.
7682       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7683         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7684         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7685                                       OpPtrTy, CI);
7686         return new StoreInst(II->getOperand(2), Ptr);
7687       }
7688       break;
7689       
7690     case Intrinsic::x86_sse_cvttss2si: {
7691       // These intrinsics only demands the 0th element of its input vector.  If
7692       // we can simplify the input based on that, do so now.
7693       uint64_t UndefElts;
7694       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7695                                                 UndefElts)) {
7696         II->setOperand(1, V);
7697         return II;
7698       }
7699       break;
7700     }
7701       
7702     case Intrinsic::ppc_altivec_vperm:
7703       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7704       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7705         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7706         
7707         // Check that all of the elements are integer constants or undefs.
7708         bool AllEltsOk = true;
7709         for (unsigned i = 0; i != 16; ++i) {
7710           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7711               !isa<UndefValue>(Mask->getOperand(i))) {
7712             AllEltsOk = false;
7713             break;
7714           }
7715         }
7716         
7717         if (AllEltsOk) {
7718           // Cast the input vectors to byte vectors.
7719           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7720                                         II->getOperand(1), Mask->getType(), CI);
7721           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7722                                         II->getOperand(2), Mask->getType(), CI);
7723           Value *Result = UndefValue::get(Op0->getType());
7724           
7725           // Only extract each element once.
7726           Value *ExtractedElts[32];
7727           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7728           
7729           for (unsigned i = 0; i != 16; ++i) {
7730             if (isa<UndefValue>(Mask->getOperand(i)))
7731               continue;
7732             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7733             Idx &= 31;  // Match the hardware behavior.
7734             
7735             if (ExtractedElts[Idx] == 0) {
7736               Instruction *Elt = 
7737                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7738               InsertNewInstBefore(Elt, CI);
7739               ExtractedElts[Idx] = Elt;
7740             }
7741           
7742             // Insert this value into the result vector.
7743             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7744             InsertNewInstBefore(cast<Instruction>(Result), CI);
7745           }
7746           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7747         }
7748       }
7749       break;
7750
7751     case Intrinsic::stackrestore: {
7752       // If the save is right next to the restore, remove the restore.  This can
7753       // happen when variable allocas are DCE'd.
7754       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7755         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7756           BasicBlock::iterator BI = SS;
7757           if (&*++BI == II)
7758             return EraseInstFromFunction(CI);
7759         }
7760       }
7761       
7762       // If the stack restore is in a return/unwind block and if there are no
7763       // allocas or calls between the restore and the return, nuke the restore.
7764       TerminatorInst *TI = II->getParent()->getTerminator();
7765       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7766         BasicBlock::iterator BI = II;
7767         bool CannotRemove = false;
7768         for (++BI; &*BI != TI; ++BI) {
7769           if (isa<AllocaInst>(BI) ||
7770               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7771             CannotRemove = true;
7772             break;
7773           }
7774         }
7775         if (!CannotRemove)
7776           return EraseInstFromFunction(CI);
7777       }
7778       break;
7779     }
7780     }
7781   }
7782
7783   return visitCallSite(II);
7784 }
7785
7786 // InvokeInst simplification
7787 //
7788 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7789   return visitCallSite(&II);
7790 }
7791
7792 // visitCallSite - Improvements for call and invoke instructions.
7793 //
7794 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7795   bool Changed = false;
7796
7797   // If the callee is a constexpr cast of a function, attempt to move the cast
7798   // to the arguments of the call/invoke.
7799   if (transformConstExprCastCall(CS)) return 0;
7800
7801   Value *Callee = CS.getCalledValue();
7802
7803   if (Function *CalleeF = dyn_cast<Function>(Callee))
7804     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7805       Instruction *OldCall = CS.getInstruction();
7806       // If the call and callee calling conventions don't match, this call must
7807       // be unreachable, as the call is undefined.
7808       new StoreInst(ConstantInt::getTrue(),
7809                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7810       if (!OldCall->use_empty())
7811         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7812       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7813         return EraseInstFromFunction(*OldCall);
7814       return 0;
7815     }
7816
7817   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7818     // This instruction is not reachable, just remove it.  We insert a store to
7819     // undef so that we know that this code is not reachable, despite the fact
7820     // that we can't modify the CFG here.
7821     new StoreInst(ConstantInt::getTrue(),
7822                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7823                   CS.getInstruction());
7824
7825     if (!CS.getInstruction()->use_empty())
7826       CS.getInstruction()->
7827         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7828
7829     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7830       // Don't break the CFG, insert a dummy cond branch.
7831       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7832                      ConstantInt::getTrue(), II);
7833     }
7834     return EraseInstFromFunction(*CS.getInstruction());
7835   }
7836
7837   const PointerType *PTy = cast<PointerType>(Callee->getType());
7838   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7839   if (FTy->isVarArg()) {
7840     // See if we can optimize any arguments passed through the varargs area of
7841     // the call.
7842     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7843            E = CS.arg_end(); I != E; ++I)
7844       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7845         // If this cast does not effect the value passed through the varargs
7846         // area, we can eliminate the use of the cast.
7847         Value *Op = CI->getOperand(0);
7848         if (CI->isLosslessCast()) {
7849           *I = Op;
7850           Changed = true;
7851         }
7852       }
7853   }
7854
7855   return Changed ? CS.getInstruction() : 0;
7856 }
7857
7858 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7859 // attempt to move the cast to the arguments of the call/invoke.
7860 //
7861 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7862   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7863   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7864   if (CE->getOpcode() != Instruction::BitCast || 
7865       !isa<Function>(CE->getOperand(0)))
7866     return false;
7867   Function *Callee = cast<Function>(CE->getOperand(0));
7868   Instruction *Caller = CS.getInstruction();
7869
7870   // Okay, this is a cast from a function to a different type.  Unless doing so
7871   // would cause a type conversion of one of our arguments, change this call to
7872   // be a direct call with arguments casted to the appropriate types.
7873   //
7874   const FunctionType *FT = Callee->getFunctionType();
7875   const Type *OldRetTy = Caller->getType();
7876
7877   const FunctionType *ActualFT =
7878     cast<FunctionType>(cast<PointerType>(CE->getType())->getElementType());
7879   
7880   // If the parameter attributes don't match up, don't do the xform.  We don't
7881   // want to lose an sret attribute or something.
7882   if (FT->getParamAttrs() != ActualFT->getParamAttrs())
7883     return false;
7884   
7885   // Check to see if we are changing the return type...
7886   if (OldRetTy != FT->getReturnType()) {
7887     if (Callee->isDeclaration() && !Caller->use_empty() && 
7888         // Conversion is ok if changing from pointer to int of same size.
7889         !(isa<PointerType>(FT->getReturnType()) &&
7890           TD->getIntPtrType() == OldRetTy))
7891       return false;   // Cannot transform this return value.
7892
7893     // If the callsite is an invoke instruction, and the return value is used by
7894     // a PHI node in a successor, we cannot change the return type of the call
7895     // because there is no place to put the cast instruction (without breaking
7896     // the critical edge).  Bail out in this case.
7897     if (!Caller->use_empty())
7898       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7899         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7900              UI != E; ++UI)
7901           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7902             if (PN->getParent() == II->getNormalDest() ||
7903                 PN->getParent() == II->getUnwindDest())
7904               return false;
7905   }
7906
7907   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7908   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7909
7910   CallSite::arg_iterator AI = CS.arg_begin();
7911   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7912     const Type *ParamTy = FT->getParamType(i);
7913     const Type *ActTy = (*AI)->getType();
7914     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7915     //Some conversions are safe even if we do not have a body.
7916     //Either we can cast directly, or we can upconvert the argument
7917     bool isConvertible = ActTy == ParamTy ||
7918       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7919       (ParamTy->isInteger() && ActTy->isInteger() &&
7920        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7921       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7922        && c->getValue().isStrictlyPositive());
7923     if (Callee->isDeclaration() && !isConvertible) return false;
7924
7925     // Most other conversions can be done if we have a body, even if these
7926     // lose information, e.g. int->short.
7927     // Some conversions cannot be done at all, e.g. float to pointer.
7928     // Logic here parallels CastInst::getCastOpcode (the design there
7929     // requires legality checks like this be done before calling it).
7930     if (ParamTy->isInteger()) {
7931       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7932         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7933           return false;
7934       }
7935       if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7936           !isa<PointerType>(ActTy))
7937         return false;
7938     } else if (ParamTy->isFloatingPoint()) {
7939       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7940         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7941           return false;
7942       }
7943       if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7944         return false;
7945     } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7946       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7947         if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7948           return false;
7949       }
7950       if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())      
7951         return false;
7952     } else if (isa<PointerType>(ParamTy)) {
7953       if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7954         return false;
7955     } else {
7956       return false;
7957     }
7958   }
7959
7960   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7961       Callee->isDeclaration())
7962     return false;   // Do not delete arguments unless we have a function body...
7963
7964   // Okay, we decided that this is a safe thing to do: go ahead and start
7965   // inserting cast instructions as necessary...
7966   std::vector<Value*> Args;
7967   Args.reserve(NumActualArgs);
7968
7969   AI = CS.arg_begin();
7970   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7971     const Type *ParamTy = FT->getParamType(i);
7972     if ((*AI)->getType() == ParamTy) {
7973       Args.push_back(*AI);
7974     } else {
7975       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7976           false, ParamTy, false);
7977       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7978       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7979     }
7980   }
7981
7982   // If the function takes more arguments than the call was taking, add them
7983   // now...
7984   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7985     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7986
7987   // If we are removing arguments to the function, emit an obnoxious warning...
7988   if (FT->getNumParams() < NumActualArgs)
7989     if (!FT->isVarArg()) {
7990       cerr << "WARNING: While resolving call to function '"
7991            << Callee->getName() << "' arguments were dropped!\n";
7992     } else {
7993       // Add all of the arguments in their promoted form to the arg list...
7994       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7995         const Type *PTy = getPromotedType((*AI)->getType());
7996         if (PTy != (*AI)->getType()) {
7997           // Must promote to pass through va_arg area!
7998           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7999                                                                 PTy, false);
8000           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8001           InsertNewInstBefore(Cast, *Caller);
8002           Args.push_back(Cast);
8003         } else {
8004           Args.push_back(*AI);
8005         }
8006       }
8007     }
8008
8009   if (FT->getReturnType() == Type::VoidTy)
8010     Caller->setName("");   // Void type should not have a name.
8011
8012   Instruction *NC;
8013   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8014     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8015                         &Args[0], Args.size(), Caller->getName(), Caller);
8016     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
8017   } else {
8018     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
8019     if (cast<CallInst>(Caller)->isTailCall())
8020       cast<CallInst>(NC)->setTailCall();
8021    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8022   }
8023
8024   // Insert a cast of the return type as necessary.
8025   Value *NV = NC;
8026   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8027     if (NV->getType() != Type::VoidTy) {
8028       const Type *CallerTy = Caller->getType();
8029       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8030                                                             CallerTy, false);
8031       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
8032
8033       // If this is an invoke instruction, we should insert it after the first
8034       // non-phi, instruction in the normal successor block.
8035       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8036         BasicBlock::iterator I = II->getNormalDest()->begin();
8037         while (isa<PHINode>(I)) ++I;
8038         InsertNewInstBefore(NC, *I);
8039       } else {
8040         // Otherwise, it's a call, just insert cast right after the call instr
8041         InsertNewInstBefore(NC, *Caller);
8042       }
8043       AddUsersToWorkList(*Caller);
8044     } else {
8045       NV = UndefValue::get(Caller->getType());
8046     }
8047   }
8048
8049   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8050     Caller->replaceAllUsesWith(NV);
8051   Caller->eraseFromParent();
8052   RemoveFromWorkList(Caller);
8053   return true;
8054 }
8055
8056 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8057 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8058 /// and a single binop.
8059 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8060   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8061   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8062          isa<CmpInst>(FirstInst));
8063   unsigned Opc = FirstInst->getOpcode();
8064   Value *LHSVal = FirstInst->getOperand(0);
8065   Value *RHSVal = FirstInst->getOperand(1);
8066     
8067   const Type *LHSType = LHSVal->getType();
8068   const Type *RHSType = RHSVal->getType();
8069   
8070   // Scan to see if all operands are the same opcode, all have one use, and all
8071   // kill their operands (i.e. the operands have one use).
8072   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8073     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8074     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8075         // Verify type of the LHS matches so we don't fold cmp's of different
8076         // types or GEP's with different index types.
8077         I->getOperand(0)->getType() != LHSType ||
8078         I->getOperand(1)->getType() != RHSType)
8079       return 0;
8080
8081     // If they are CmpInst instructions, check their predicates
8082     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8083       if (cast<CmpInst>(I)->getPredicate() !=
8084           cast<CmpInst>(FirstInst)->getPredicate())
8085         return 0;
8086     
8087     // Keep track of which operand needs a phi node.
8088     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8089     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8090   }
8091   
8092   // Otherwise, this is safe to transform, determine if it is profitable.
8093
8094   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8095   // Indexes are often folded into load/store instructions, so we don't want to
8096   // hide them behind a phi.
8097   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8098     return 0;
8099   
8100   Value *InLHS = FirstInst->getOperand(0);
8101   Value *InRHS = FirstInst->getOperand(1);
8102   PHINode *NewLHS = 0, *NewRHS = 0;
8103   if (LHSVal == 0) {
8104     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8105     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8106     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8107     InsertNewInstBefore(NewLHS, PN);
8108     LHSVal = NewLHS;
8109   }
8110   
8111   if (RHSVal == 0) {
8112     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8113     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8114     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8115     InsertNewInstBefore(NewRHS, PN);
8116     RHSVal = NewRHS;
8117   }
8118   
8119   // Add all operands to the new PHIs.
8120   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8121     if (NewLHS) {
8122       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8123       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8124     }
8125     if (NewRHS) {
8126       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8127       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8128     }
8129   }
8130     
8131   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8132     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8133   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8134     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8135                            RHSVal);
8136   else {
8137     assert(isa<GetElementPtrInst>(FirstInst));
8138     return new GetElementPtrInst(LHSVal, RHSVal);
8139   }
8140 }
8141
8142 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8143 /// of the block that defines it.  This means that it must be obvious the value
8144 /// of the load is not changed from the point of the load to the end of the
8145 /// block it is in.
8146 ///
8147 /// Finally, it is safe, but not profitable, to sink a load targetting a
8148 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8149 /// to a register.
8150 static bool isSafeToSinkLoad(LoadInst *L) {
8151   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8152   
8153   for (++BBI; BBI != E; ++BBI)
8154     if (BBI->mayWriteToMemory())
8155       return false;
8156   
8157   // Check for non-address taken alloca.  If not address-taken already, it isn't
8158   // profitable to do this xform.
8159   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8160     bool isAddressTaken = false;
8161     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8162          UI != E; ++UI) {
8163       if (isa<LoadInst>(UI)) continue;
8164       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8165         // If storing TO the alloca, then the address isn't taken.
8166         if (SI->getOperand(1) == AI) continue;
8167       }
8168       isAddressTaken = true;
8169       break;
8170     }
8171     
8172     if (!isAddressTaken)
8173       return false;
8174   }
8175   
8176   return true;
8177 }
8178
8179
8180 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8181 // operator and they all are only used by the PHI, PHI together their
8182 // inputs, and do the operation once, to the result of the PHI.
8183 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8184   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8185
8186   // Scan the instruction, looking for input operations that can be folded away.
8187   // If all input operands to the phi are the same instruction (e.g. a cast from
8188   // the same type or "+42") we can pull the operation through the PHI, reducing
8189   // code size and simplifying code.
8190   Constant *ConstantOp = 0;
8191   const Type *CastSrcTy = 0;
8192   bool isVolatile = false;
8193   if (isa<CastInst>(FirstInst)) {
8194     CastSrcTy = FirstInst->getOperand(0)->getType();
8195   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8196     // Can fold binop, compare or shift here if the RHS is a constant, 
8197     // otherwise call FoldPHIArgBinOpIntoPHI.
8198     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8199     if (ConstantOp == 0)
8200       return FoldPHIArgBinOpIntoPHI(PN);
8201   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8202     isVolatile = LI->isVolatile();
8203     // We can't sink the load if the loaded value could be modified between the
8204     // load and the PHI.
8205     if (LI->getParent() != PN.getIncomingBlock(0) ||
8206         !isSafeToSinkLoad(LI))
8207       return 0;
8208   } else if (isa<GetElementPtrInst>(FirstInst)) {
8209     if (FirstInst->getNumOperands() == 2)
8210       return FoldPHIArgBinOpIntoPHI(PN);
8211     // Can't handle general GEPs yet.
8212     return 0;
8213   } else {
8214     return 0;  // Cannot fold this operation.
8215   }
8216
8217   // Check to see if all arguments are the same operation.
8218   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8219     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8220     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8221     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8222       return 0;
8223     if (CastSrcTy) {
8224       if (I->getOperand(0)->getType() != CastSrcTy)
8225         return 0;  // Cast operation must match.
8226     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8227       // We can't sink the load if the loaded value could be modified between 
8228       // the load and the PHI.
8229       if (LI->isVolatile() != isVolatile ||
8230           LI->getParent() != PN.getIncomingBlock(i) ||
8231           !isSafeToSinkLoad(LI))
8232         return 0;
8233     } else if (I->getOperand(1) != ConstantOp) {
8234       return 0;
8235     }
8236   }
8237
8238   // Okay, they are all the same operation.  Create a new PHI node of the
8239   // correct type, and PHI together all of the LHS's of the instructions.
8240   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8241                                PN.getName()+".in");
8242   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8243
8244   Value *InVal = FirstInst->getOperand(0);
8245   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8246
8247   // Add all operands to the new PHI.
8248   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8249     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8250     if (NewInVal != InVal)
8251       InVal = 0;
8252     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8253   }
8254
8255   Value *PhiVal;
8256   if (InVal) {
8257     // The new PHI unions all of the same values together.  This is really
8258     // common, so we handle it intelligently here for compile-time speed.
8259     PhiVal = InVal;
8260     delete NewPN;
8261   } else {
8262     InsertNewInstBefore(NewPN, PN);
8263     PhiVal = NewPN;
8264   }
8265
8266   // Insert and return the new operation.
8267   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8268     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8269   else if (isa<LoadInst>(FirstInst))
8270     return new LoadInst(PhiVal, "", isVolatile);
8271   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8272     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8273   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8274     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8275                            PhiVal, ConstantOp);
8276   else
8277     assert(0 && "Unknown operation");
8278   return 0;
8279 }
8280
8281 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8282 /// that is dead.
8283 static bool DeadPHICycle(PHINode *PN,
8284                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8285   if (PN->use_empty()) return true;
8286   if (!PN->hasOneUse()) return false;
8287
8288   // Remember this node, and if we find the cycle, return.
8289   if (!PotentiallyDeadPHIs.insert(PN))
8290     return true;
8291
8292   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8293     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8294
8295   return false;
8296 }
8297
8298 // PHINode simplification
8299 //
8300 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8301   // If LCSSA is around, don't mess with Phi nodes
8302   if (MustPreserveLCSSA) return 0;
8303   
8304   if (Value *V = PN.hasConstantValue())
8305     return ReplaceInstUsesWith(PN, V);
8306
8307   // If all PHI operands are the same operation, pull them through the PHI,
8308   // reducing code size.
8309   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8310       PN.getIncomingValue(0)->hasOneUse())
8311     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8312       return Result;
8313
8314   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8315   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8316   // PHI)... break the cycle.
8317   if (PN.hasOneUse()) {
8318     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8319     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8320       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8321       PotentiallyDeadPHIs.insert(&PN);
8322       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8323         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8324     }
8325    
8326     // If this phi has a single use, and if that use just computes a value for
8327     // the next iteration of a loop, delete the phi.  This occurs with unused
8328     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8329     // common case here is good because the only other things that catch this
8330     // are induction variable analysis (sometimes) and ADCE, which is only run
8331     // late.
8332     if (PHIUser->hasOneUse() &&
8333         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8334         PHIUser->use_back() == &PN) {
8335       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8336     }
8337   }
8338
8339   return 0;
8340 }
8341
8342 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8343                                    Instruction *InsertPoint,
8344                                    InstCombiner *IC) {
8345   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8346   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8347   // We must cast correctly to the pointer type. Ensure that we
8348   // sign extend the integer value if it is smaller as this is
8349   // used for address computation.
8350   Instruction::CastOps opcode = 
8351      (VTySize < PtrSize ? Instruction::SExt :
8352       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8353   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8354 }
8355
8356
8357 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8358   Value *PtrOp = GEP.getOperand(0);
8359   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
8360   // If so, eliminate the noop.
8361   if (GEP.getNumOperands() == 1)
8362     return ReplaceInstUsesWith(GEP, PtrOp);
8363
8364   if (isa<UndefValue>(GEP.getOperand(0)))
8365     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8366
8367   bool HasZeroPointerIndex = false;
8368   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8369     HasZeroPointerIndex = C->isNullValue();
8370
8371   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8372     return ReplaceInstUsesWith(GEP, PtrOp);
8373
8374   // Eliminate unneeded casts for indices.
8375   bool MadeChange = false;
8376   
8377   gep_type_iterator GTI = gep_type_begin(GEP);
8378   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8379     if (isa<SequentialType>(*GTI)) {
8380       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8381         if (CI->getOpcode() == Instruction::ZExt ||
8382             CI->getOpcode() == Instruction::SExt) {
8383           const Type *SrcTy = CI->getOperand(0)->getType();
8384           // We can eliminate a cast from i32 to i64 iff the target 
8385           // is a 32-bit pointer target.
8386           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8387             MadeChange = true;
8388             GEP.setOperand(i, CI->getOperand(0));
8389           }
8390         }
8391       }
8392       // If we are using a wider index than needed for this platform, shrink it
8393       // to what we need.  If the incoming value needs a cast instruction,
8394       // insert it.  This explicit cast can make subsequent optimizations more
8395       // obvious.
8396       Value *Op = GEP.getOperand(i);
8397       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8398         if (Constant *C = dyn_cast<Constant>(Op)) {
8399           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8400           MadeChange = true;
8401         } else {
8402           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8403                                 GEP);
8404           GEP.setOperand(i, Op);
8405           MadeChange = true;
8406         }
8407     }
8408   }
8409   if (MadeChange) return &GEP;
8410
8411   // If this GEP instruction doesn't move the pointer, and if the input operand
8412   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8413   // real input to the dest type.
8414   if (GEP.hasAllZeroIndices() && isa<BitCastInst>(GEP.getOperand(0)))
8415     return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8416                            GEP.getType());
8417     
8418   // Combine Indices - If the source pointer to this getelementptr instruction
8419   // is a getelementptr instruction, combine the indices of the two
8420   // getelementptr instructions into a single instruction.
8421   //
8422   SmallVector<Value*, 8> SrcGEPOperands;
8423   if (User *Src = dyn_castGetElementPtr(PtrOp))
8424     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8425
8426   if (!SrcGEPOperands.empty()) {
8427     // Note that if our source is a gep chain itself that we wait for that
8428     // chain to be resolved before we perform this transformation.  This
8429     // avoids us creating a TON of code in some cases.
8430     //
8431     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8432         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8433       return 0;   // Wait until our source is folded to completion.
8434
8435     SmallVector<Value*, 8> Indices;
8436
8437     // Find out whether the last index in the source GEP is a sequential idx.
8438     bool EndsWithSequential = false;
8439     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8440            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8441       EndsWithSequential = !isa<StructType>(*I);
8442
8443     // Can we combine the two pointer arithmetics offsets?
8444     if (EndsWithSequential) {
8445       // Replace: gep (gep %P, long B), long A, ...
8446       // With:    T = long A+B; gep %P, T, ...
8447       //
8448       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8449       if (SO1 == Constant::getNullValue(SO1->getType())) {
8450         Sum = GO1;
8451       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8452         Sum = SO1;
8453       } else {
8454         // If they aren't the same type, convert both to an integer of the
8455         // target's pointer size.
8456         if (SO1->getType() != GO1->getType()) {
8457           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8458             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8459           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8460             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8461           } else {
8462             unsigned PS = TD->getPointerSize();
8463             if (TD->getTypeSize(SO1->getType()) == PS) {
8464               // Convert GO1 to SO1's type.
8465               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8466
8467             } else if (TD->getTypeSize(GO1->getType()) == PS) {
8468               // Convert SO1 to GO1's type.
8469               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8470             } else {
8471               const Type *PT = TD->getIntPtrType();
8472               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8473               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8474             }
8475           }
8476         }
8477         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8478           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8479         else {
8480           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8481           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8482         }
8483       }
8484
8485       // Recycle the GEP we already have if possible.
8486       if (SrcGEPOperands.size() == 2) {
8487         GEP.setOperand(0, SrcGEPOperands[0]);
8488         GEP.setOperand(1, Sum);
8489         return &GEP;
8490       } else {
8491         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8492                        SrcGEPOperands.end()-1);
8493         Indices.push_back(Sum);
8494         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8495       }
8496     } else if (isa<Constant>(*GEP.idx_begin()) &&
8497                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8498                SrcGEPOperands.size() != 1) {
8499       // Otherwise we can do the fold if the first index of the GEP is a zero
8500       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8501                      SrcGEPOperands.end());
8502       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8503     }
8504
8505     if (!Indices.empty())
8506       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8507                                    Indices.size(), GEP.getName());
8508
8509   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8510     // GEP of global variable.  If all of the indices for this GEP are
8511     // constants, we can promote this to a constexpr instead of an instruction.
8512
8513     // Scan for nonconstants...
8514     SmallVector<Constant*, 8> Indices;
8515     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8516     for (; I != E && isa<Constant>(*I); ++I)
8517       Indices.push_back(cast<Constant>(*I));
8518
8519     if (I == E) {  // If they are all constants...
8520       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8521                                                     &Indices[0],Indices.size());
8522
8523       // Replace all uses of the GEP with the new constexpr...
8524       return ReplaceInstUsesWith(GEP, CE);
8525     }
8526   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8527     if (!isa<PointerType>(X->getType())) {
8528       // Not interesting.  Source pointer must be a cast from pointer.
8529     } else if (HasZeroPointerIndex) {
8530       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8531       // into     : GEP [10 x ubyte]* X, long 0, ...
8532       //
8533       // This occurs when the program declares an array extern like "int X[];"
8534       //
8535       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8536       const PointerType *XTy = cast<PointerType>(X->getType());
8537       if (const ArrayType *XATy =
8538           dyn_cast<ArrayType>(XTy->getElementType()))
8539         if (const ArrayType *CATy =
8540             dyn_cast<ArrayType>(CPTy->getElementType()))
8541           if (CATy->getElementType() == XATy->getElementType()) {
8542             // At this point, we know that the cast source type is a pointer
8543             // to an array of the same type as the destination pointer
8544             // array.  Because the array type is never stepped over (there
8545             // is a leading zero) we can fold the cast into this GEP.
8546             GEP.setOperand(0, X);
8547             return &GEP;
8548           }
8549     } else if (GEP.getNumOperands() == 2) {
8550       // Transform things like:
8551       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8552       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8553       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8554       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8555       if (isa<ArrayType>(SrcElTy) &&
8556           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8557           TD->getTypeSize(ResElTy)) {
8558         Value *V = InsertNewInstBefore(
8559                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8560                                      GEP.getOperand(1), GEP.getName()), GEP);
8561         // V and GEP are both pointer types --> BitCast
8562         return new BitCastInst(V, GEP.getType());
8563       }
8564       
8565       // Transform things like:
8566       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8567       //   (where tmp = 8*tmp2) into:
8568       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8569       
8570       if (isa<ArrayType>(SrcElTy) &&
8571           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8572         uint64_t ArrayEltSize =
8573             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8574         
8575         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
8576         // allow either a mul, shift, or constant here.
8577         Value *NewIdx = 0;
8578         ConstantInt *Scale = 0;
8579         if (ArrayEltSize == 1) {
8580           NewIdx = GEP.getOperand(1);
8581           Scale = ConstantInt::get(NewIdx->getType(), 1);
8582         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8583           NewIdx = ConstantInt::get(CI->getType(), 1);
8584           Scale = CI;
8585         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8586           if (Inst->getOpcode() == Instruction::Shl &&
8587               isa<ConstantInt>(Inst->getOperand(1))) {
8588             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8589             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8590             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
8591             NewIdx = Inst->getOperand(0);
8592           } else if (Inst->getOpcode() == Instruction::Mul &&
8593                      isa<ConstantInt>(Inst->getOperand(1))) {
8594             Scale = cast<ConstantInt>(Inst->getOperand(1));
8595             NewIdx = Inst->getOperand(0);
8596           }
8597         }
8598
8599         // If the index will be to exactly the right offset with the scale taken
8600         // out, perform the transformation.
8601         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8602           if (isa<ConstantInt>(Scale))
8603             Scale = ConstantInt::get(Scale->getType(),
8604                                       Scale->getZExtValue() / ArrayEltSize);
8605           if (Scale->getZExtValue() != 1) {
8606             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8607                                                        true /*SExt*/);
8608             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8609             NewIdx = InsertNewInstBefore(Sc, GEP);
8610           }
8611
8612           // Insert the new GEP instruction.
8613           Instruction *NewGEP =
8614             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8615                                   NewIdx, GEP.getName());
8616           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8617           // The NewGEP must be pointer typed, so must the old one -> BitCast
8618           return new BitCastInst(NewGEP, GEP.getType());
8619         }
8620       }
8621     }
8622   }
8623
8624   return 0;
8625 }
8626
8627 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8628   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8629   if (AI.isArrayAllocation())    // Check C != 1
8630     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8631       const Type *NewTy = 
8632         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8633       AllocationInst *New = 0;
8634
8635       // Create and insert the replacement instruction...
8636       if (isa<MallocInst>(AI))
8637         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8638       else {
8639         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8640         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8641       }
8642
8643       InsertNewInstBefore(New, AI);
8644
8645       // Scan to the end of the allocation instructions, to skip over a block of
8646       // allocas if possible...
8647       //
8648       BasicBlock::iterator It = New;
8649       while (isa<AllocationInst>(*It)) ++It;
8650
8651       // Now that I is pointing to the first non-allocation-inst in the block,
8652       // insert our getelementptr instruction...
8653       //
8654       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8655       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8656                                        New->getName()+".sub", It);
8657
8658       // Now make everything use the getelementptr instead of the original
8659       // allocation.
8660       return ReplaceInstUsesWith(AI, V);
8661     } else if (isa<UndefValue>(AI.getArraySize())) {
8662       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8663     }
8664
8665   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8666   // Note that we only do this for alloca's, because malloc should allocate and
8667   // return a unique pointer, even for a zero byte allocation.
8668   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8669       TD->getTypeSize(AI.getAllocatedType()) == 0)
8670     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8671
8672   return 0;
8673 }
8674
8675 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8676   Value *Op = FI.getOperand(0);
8677
8678   // free undef -> unreachable.
8679   if (isa<UndefValue>(Op)) {
8680     // Insert a new store to null because we cannot modify the CFG here.
8681     new StoreInst(ConstantInt::getTrue(),
8682                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8683     return EraseInstFromFunction(FI);
8684   }
8685   
8686   // If we have 'free null' delete the instruction.  This can happen in stl code
8687   // when lots of inlining happens.
8688   if (isa<ConstantPointerNull>(Op))
8689     return EraseInstFromFunction(FI);
8690   
8691   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8692   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8693     FI.setOperand(0, CI->getOperand(0));
8694     return &FI;
8695   }
8696   
8697   // Change free (gep X, 0,0,0,0) into free(X)
8698   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8699     if (GEPI->hasAllZeroIndices()) {
8700       AddToWorkList(GEPI);
8701       FI.setOperand(0, GEPI->getOperand(0));
8702       return &FI;
8703     }
8704   }
8705   
8706   // Change free(malloc) into nothing, if the malloc has a single use.
8707   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8708     if (MI->hasOneUse()) {
8709       EraseInstFromFunction(FI);
8710       return EraseInstFromFunction(*MI);
8711     }
8712
8713   return 0;
8714 }
8715
8716
8717 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8718 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8719   User *CI = cast<User>(LI.getOperand(0));
8720   Value *CastOp = CI->getOperand(0);
8721
8722   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8723   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8724     const Type *SrcPTy = SrcTy->getElementType();
8725
8726     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8727          isa<VectorType>(DestPTy)) {
8728       // If the source is an array, the code below will not succeed.  Check to
8729       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8730       // constants.
8731       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8732         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8733           if (ASrcTy->getNumElements() != 0) {
8734             Value *Idxs[2];
8735             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8736             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8737             SrcTy = cast<PointerType>(CastOp->getType());
8738             SrcPTy = SrcTy->getElementType();
8739           }
8740
8741       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8742             isa<VectorType>(SrcPTy)) &&
8743           // Do not allow turning this into a load of an integer, which is then
8744           // casted to a pointer, this pessimizes pointer analysis a lot.
8745           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8746           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8747                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8748
8749         // Okay, we are casting from one integer or pointer type to another of
8750         // the same size.  Instead of casting the pointer before the load, cast
8751         // the result of the loaded value.
8752         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8753                                                              CI->getName(),
8754                                                          LI.isVolatile()),LI);
8755         // Now cast the result of the load.
8756         return new BitCastInst(NewLoad, LI.getType());
8757       }
8758     }
8759   }
8760   return 0;
8761 }
8762
8763 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8764 /// from this value cannot trap.  If it is not obviously safe to load from the
8765 /// specified pointer, we do a quick local scan of the basic block containing
8766 /// ScanFrom, to determine if the address is already accessed.
8767 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8768   // If it is an alloca or global variable, it is always safe to load from.
8769   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8770
8771   // Otherwise, be a little bit agressive by scanning the local block where we
8772   // want to check to see if the pointer is already being loaded or stored
8773   // from/to.  If so, the previous load or store would have already trapped,
8774   // so there is no harm doing an extra load (also, CSE will later eliminate
8775   // the load entirely).
8776   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8777
8778   while (BBI != E) {
8779     --BBI;
8780
8781     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8782       if (LI->getOperand(0) == V) return true;
8783     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8784       if (SI->getOperand(1) == V) return true;
8785
8786   }
8787   return false;
8788 }
8789
8790 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8791   Value *Op = LI.getOperand(0);
8792
8793   // Attempt to improve the alignment.
8794   unsigned KnownAlign = GetKnownAlignment(Op, TD);
8795   if (KnownAlign > LI.getAlignment())
8796     LI.setAlignment(KnownAlign);
8797
8798   // load (cast X) --> cast (load X) iff safe
8799   if (isa<CastInst>(Op))
8800     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8801       return Res;
8802
8803   // None of the following transforms are legal for volatile loads.
8804   if (LI.isVolatile()) return 0;
8805   
8806   if (&LI.getParent()->front() != &LI) {
8807     BasicBlock::iterator BBI = &LI; --BBI;
8808     // If the instruction immediately before this is a store to the same
8809     // address, do a simple form of store->load forwarding.
8810     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8811       if (SI->getOperand(1) == LI.getOperand(0))
8812         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8813     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8814       if (LIB->getOperand(0) == LI.getOperand(0))
8815         return ReplaceInstUsesWith(LI, LIB);
8816   }
8817
8818   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8819     if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
8820       // Insert a new store to null instruction before the load to indicate
8821       // that this code is not reachable.  We do this instead of inserting
8822       // an unreachable instruction directly because we cannot modify the
8823       // CFG.
8824       new StoreInst(UndefValue::get(LI.getType()),
8825                     Constant::getNullValue(Op->getType()), &LI);
8826       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8827     }
8828
8829   if (Constant *C = dyn_cast<Constant>(Op)) {
8830     // load null/undef -> undef
8831     if ((C->isNullValue() || isa<UndefValue>(C))) {
8832       // Insert a new store to null instruction before the load to indicate that
8833       // this code is not reachable.  We do this instead of inserting an
8834       // unreachable instruction directly because we cannot modify the CFG.
8835       new StoreInst(UndefValue::get(LI.getType()),
8836                     Constant::getNullValue(Op->getType()), &LI);
8837       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8838     }
8839
8840     // Instcombine load (constant global) into the value loaded.
8841     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8842       if (GV->isConstant() && !GV->isDeclaration())
8843         return ReplaceInstUsesWith(LI, GV->getInitializer());
8844
8845     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8846     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8847       if (CE->getOpcode() == Instruction::GetElementPtr) {
8848         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8849           if (GV->isConstant() && !GV->isDeclaration())
8850             if (Constant *V = 
8851                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8852               return ReplaceInstUsesWith(LI, V);
8853         if (CE->getOperand(0)->isNullValue()) {
8854           // Insert a new store to null instruction before the load to indicate
8855           // that this code is not reachable.  We do this instead of inserting
8856           // an unreachable instruction directly because we cannot modify the
8857           // CFG.
8858           new StoreInst(UndefValue::get(LI.getType()),
8859                         Constant::getNullValue(Op->getType()), &LI);
8860           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8861         }
8862
8863       } else if (CE->isCast()) {
8864         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8865           return Res;
8866       }
8867   }
8868
8869   if (Op->hasOneUse()) {
8870     // Change select and PHI nodes to select values instead of addresses: this
8871     // helps alias analysis out a lot, allows many others simplifications, and
8872     // exposes redundancy in the code.
8873     //
8874     // Note that we cannot do the transformation unless we know that the
8875     // introduced loads cannot trap!  Something like this is valid as long as
8876     // the condition is always false: load (select bool %C, int* null, int* %G),
8877     // but it would not be valid if we transformed it to load from null
8878     // unconditionally.
8879     //
8880     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8881       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8882       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8883           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8884         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8885                                      SI->getOperand(1)->getName()+".val"), LI);
8886         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8887                                      SI->getOperand(2)->getName()+".val"), LI);
8888         return new SelectInst(SI->getCondition(), V1, V2);
8889       }
8890
8891       // load (select (cond, null, P)) -> load P
8892       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8893         if (C->isNullValue()) {
8894           LI.setOperand(0, SI->getOperand(2));
8895           return &LI;
8896         }
8897
8898       // load (select (cond, P, null)) -> load P
8899       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8900         if (C->isNullValue()) {
8901           LI.setOperand(0, SI->getOperand(1));
8902           return &LI;
8903         }
8904     }
8905   }
8906   return 0;
8907 }
8908
8909 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8910 /// when possible.
8911 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8912   User *CI = cast<User>(SI.getOperand(1));
8913   Value *CastOp = CI->getOperand(0);
8914
8915   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8916   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8917     const Type *SrcPTy = SrcTy->getElementType();
8918
8919     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8920       // If the source is an array, the code below will not succeed.  Check to
8921       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8922       // constants.
8923       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8924         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8925           if (ASrcTy->getNumElements() != 0) {
8926             Value* Idxs[2];
8927             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8928             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8929             SrcTy = cast<PointerType>(CastOp->getType());
8930             SrcPTy = SrcTy->getElementType();
8931           }
8932
8933       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8934           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8935                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8936
8937         // Okay, we are casting from one integer or pointer type to another of
8938         // the same size.  Instead of casting the pointer before 
8939         // the store, cast the value to be stored.
8940         Value *NewCast;
8941         Value *SIOp0 = SI.getOperand(0);
8942         Instruction::CastOps opcode = Instruction::BitCast;
8943         const Type* CastSrcTy = SIOp0->getType();
8944         const Type* CastDstTy = SrcPTy;
8945         if (isa<PointerType>(CastDstTy)) {
8946           if (CastSrcTy->isInteger())
8947             opcode = Instruction::IntToPtr;
8948         } else if (isa<IntegerType>(CastDstTy)) {
8949           if (isa<PointerType>(SIOp0->getType()))
8950             opcode = Instruction::PtrToInt;
8951         }
8952         if (Constant *C = dyn_cast<Constant>(SIOp0))
8953           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8954         else
8955           NewCast = IC.InsertNewInstBefore(
8956             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8957             SI);
8958         return new StoreInst(NewCast, CastOp);
8959       }
8960     }
8961   }
8962   return 0;
8963 }
8964
8965 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8966   Value *Val = SI.getOperand(0);
8967   Value *Ptr = SI.getOperand(1);
8968
8969   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8970     EraseInstFromFunction(SI);
8971     ++NumCombined;
8972     return 0;
8973   }
8974   
8975   // If the RHS is an alloca with a single use, zapify the store, making the
8976   // alloca dead.
8977   if (Ptr->hasOneUse()) {
8978     if (isa<AllocaInst>(Ptr)) {
8979       EraseInstFromFunction(SI);
8980       ++NumCombined;
8981       return 0;
8982     }
8983     
8984     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8985       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8986           GEP->getOperand(0)->hasOneUse()) {
8987         EraseInstFromFunction(SI);
8988         ++NumCombined;
8989         return 0;
8990       }
8991   }
8992
8993   // Attempt to improve the alignment.
8994   unsigned KnownAlign = GetKnownAlignment(Ptr, TD);
8995   if (KnownAlign > SI.getAlignment())
8996     SI.setAlignment(KnownAlign);
8997
8998   // Do really simple DSE, to catch cases where there are several consequtive
8999   // stores to the same location, separated by a few arithmetic operations. This
9000   // situation often occurs with bitfield accesses.
9001   BasicBlock::iterator BBI = &SI;
9002   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9003        --ScanInsts) {
9004     --BBI;
9005     
9006     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9007       // Prev store isn't volatile, and stores to the same location?
9008       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9009         ++NumDeadStore;
9010         ++BBI;
9011         EraseInstFromFunction(*PrevSI);
9012         continue;
9013       }
9014       break;
9015     }
9016     
9017     // If this is a load, we have to stop.  However, if the loaded value is from
9018     // the pointer we're loading and is producing the pointer we're storing,
9019     // then *this* store is dead (X = load P; store X -> P).
9020     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9021       if (LI == Val && LI->getOperand(0) == Ptr) {
9022         EraseInstFromFunction(SI);
9023         ++NumCombined;
9024         return 0;
9025       }
9026       // Otherwise, this is a load from some other location.  Stores before it
9027       // may not be dead.
9028       break;
9029     }
9030     
9031     // Don't skip over loads or things that can modify memory.
9032     if (BBI->mayWriteToMemory())
9033       break;
9034   }
9035   
9036   
9037   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9038
9039   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9040   if (isa<ConstantPointerNull>(Ptr)) {
9041     if (!isa<UndefValue>(Val)) {
9042       SI.setOperand(0, UndefValue::get(Val->getType()));
9043       if (Instruction *U = dyn_cast<Instruction>(Val))
9044         AddToWorkList(U);  // Dropped a use.
9045       ++NumCombined;
9046     }
9047     return 0;  // Do not modify these!
9048   }
9049
9050   // store undef, Ptr -> noop
9051   if (isa<UndefValue>(Val)) {
9052     EraseInstFromFunction(SI);
9053     ++NumCombined;
9054     return 0;
9055   }
9056
9057   // If the pointer destination is a cast, see if we can fold the cast into the
9058   // source instead.
9059   if (isa<CastInst>(Ptr))
9060     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9061       return Res;
9062   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9063     if (CE->isCast())
9064       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9065         return Res;
9066
9067   
9068   // If this store is the last instruction in the basic block, and if the block
9069   // ends with an unconditional branch, try to move it to the successor block.
9070   BBI = &SI; ++BBI;
9071   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9072     if (BI->isUnconditional())
9073       if (SimplifyStoreAtEndOfBlock(SI))
9074         return 0;  // xform done!
9075   
9076   return 0;
9077 }
9078
9079 /// SimplifyStoreAtEndOfBlock - Turn things like:
9080 ///   if () { *P = v1; } else { *P = v2 }
9081 /// into a phi node with a store in the successor.
9082 ///
9083 /// Simplify things like:
9084 ///   *P = v1; if () { *P = v2; }
9085 /// into a phi node with a store in the successor.
9086 ///
9087 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9088   BasicBlock *StoreBB = SI.getParent();
9089   
9090   // Check to see if the successor block has exactly two incoming edges.  If
9091   // so, see if the other predecessor contains a store to the same location.
9092   // if so, insert a PHI node (if needed) and move the stores down.
9093   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9094   
9095   // Determine whether Dest has exactly two predecessors and, if so, compute
9096   // the other predecessor.
9097   pred_iterator PI = pred_begin(DestBB);
9098   BasicBlock *OtherBB = 0;
9099   if (*PI != StoreBB)
9100     OtherBB = *PI;
9101   ++PI;
9102   if (PI == pred_end(DestBB))
9103     return false;
9104   
9105   if (*PI != StoreBB) {
9106     if (OtherBB)
9107       return false;
9108     OtherBB = *PI;
9109   }
9110   if (++PI != pred_end(DestBB))
9111     return false;
9112   
9113   
9114   // Verify that the other block ends in a branch and is not otherwise empty.
9115   BasicBlock::iterator BBI = OtherBB->getTerminator();
9116   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9117   if (!OtherBr || BBI == OtherBB->begin())
9118     return false;
9119   
9120   // If the other block ends in an unconditional branch, check for the 'if then
9121   // else' case.  there is an instruction before the branch.
9122   StoreInst *OtherStore = 0;
9123   if (OtherBr->isUnconditional()) {
9124     // If this isn't a store, or isn't a store to the same location, bail out.
9125     --BBI;
9126     OtherStore = dyn_cast<StoreInst>(BBI);
9127     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9128       return false;
9129   } else {
9130     // Otherwise, the other block ended with a conditional branch. If one of the
9131     // destinations is StoreBB, then we have the if/then case.
9132     if (OtherBr->getSuccessor(0) != StoreBB && 
9133         OtherBr->getSuccessor(1) != StoreBB)
9134       return false;
9135     
9136     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9137     // if/then triangle.  See if there is a store to the same ptr as SI that
9138     // lives in OtherBB.
9139     for (;; --BBI) {
9140       // Check to see if we find the matching store.
9141       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9142         if (OtherStore->getOperand(1) != SI.getOperand(1))
9143           return false;
9144         break;
9145       }
9146       // If we find something that may be using the stored value, or if we run
9147       // out of instructions, we can't do the xform.
9148       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9149           BBI == OtherBB->begin())
9150         return false;
9151     }
9152     
9153     // In order to eliminate the store in OtherBr, we have to
9154     // make sure nothing reads the stored value in StoreBB.
9155     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9156       // FIXME: This should really be AA driven.
9157       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9158         return false;
9159     }
9160   }
9161   
9162   // Insert a PHI node now if we need it.
9163   Value *MergedVal = OtherStore->getOperand(0);
9164   if (MergedVal != SI.getOperand(0)) {
9165     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9166     PN->reserveOperandSpace(2);
9167     PN->addIncoming(SI.getOperand(0), SI.getParent());
9168     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9169     MergedVal = InsertNewInstBefore(PN, DestBB->front());
9170   }
9171   
9172   // Advance to a place where it is safe to insert the new store and
9173   // insert it.
9174   BBI = DestBB->begin();
9175   while (isa<PHINode>(BBI)) ++BBI;
9176   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9177                                     OtherStore->isVolatile()), *BBI);
9178   
9179   // Nuke the old stores.
9180   EraseInstFromFunction(SI);
9181   EraseInstFromFunction(*OtherStore);
9182   ++NumCombined;
9183   return true;
9184 }
9185
9186
9187 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9188   // Change br (not X), label True, label False to: br X, label False, True
9189   Value *X = 0;
9190   BasicBlock *TrueDest;
9191   BasicBlock *FalseDest;
9192   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9193       !isa<Constant>(X)) {
9194     // Swap Destinations and condition...
9195     BI.setCondition(X);
9196     BI.setSuccessor(0, FalseDest);
9197     BI.setSuccessor(1, TrueDest);
9198     return &BI;
9199   }
9200
9201   // Cannonicalize fcmp_one -> fcmp_oeq
9202   FCmpInst::Predicate FPred; Value *Y;
9203   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
9204                              TrueDest, FalseDest)))
9205     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9206          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9207       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9208       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9209       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9210       NewSCC->takeName(I);
9211       // Swap Destinations and condition...
9212       BI.setCondition(NewSCC);
9213       BI.setSuccessor(0, FalseDest);
9214       BI.setSuccessor(1, TrueDest);
9215       RemoveFromWorkList(I);
9216       I->eraseFromParent();
9217       AddToWorkList(NewSCC);
9218       return &BI;
9219     }
9220
9221   // Cannonicalize icmp_ne -> icmp_eq
9222   ICmpInst::Predicate IPred;
9223   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9224                       TrueDest, FalseDest)))
9225     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
9226          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9227          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9228       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9229       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9230       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9231       NewSCC->takeName(I);
9232       // Swap Destinations and condition...
9233       BI.setCondition(NewSCC);
9234       BI.setSuccessor(0, FalseDest);
9235       BI.setSuccessor(1, TrueDest);
9236       RemoveFromWorkList(I);
9237       I->eraseFromParent();;
9238       AddToWorkList(NewSCC);
9239       return &BI;
9240     }
9241
9242   return 0;
9243 }
9244
9245 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9246   Value *Cond = SI.getCondition();
9247   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9248     if (I->getOpcode() == Instruction::Add)
9249       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9250         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9251         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9252           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9253                                                 AddRHS));
9254         SI.setOperand(0, I->getOperand(0));
9255         AddToWorkList(I);
9256         return &SI;
9257       }
9258   }
9259   return 0;
9260 }
9261
9262 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9263 /// is to leave as a vector operation.
9264 static bool CheapToScalarize(Value *V, bool isConstant) {
9265   if (isa<ConstantAggregateZero>(V)) 
9266     return true;
9267   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9268     if (isConstant) return true;
9269     // If all elts are the same, we can extract.
9270     Constant *Op0 = C->getOperand(0);
9271     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9272       if (C->getOperand(i) != Op0)
9273         return false;
9274     return true;
9275   }
9276   Instruction *I = dyn_cast<Instruction>(V);
9277   if (!I) return false;
9278   
9279   // Insert element gets simplified to the inserted element or is deleted if
9280   // this is constant idx extract element and its a constant idx insertelt.
9281   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9282       isa<ConstantInt>(I->getOperand(2)))
9283     return true;
9284   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9285     return true;
9286   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9287     if (BO->hasOneUse() &&
9288         (CheapToScalarize(BO->getOperand(0), isConstant) ||
9289          CheapToScalarize(BO->getOperand(1), isConstant)))
9290       return true;
9291   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9292     if (CI->hasOneUse() &&
9293         (CheapToScalarize(CI->getOperand(0), isConstant) ||
9294          CheapToScalarize(CI->getOperand(1), isConstant)))
9295       return true;
9296   
9297   return false;
9298 }
9299
9300 /// Read and decode a shufflevector mask.
9301 ///
9302 /// It turns undef elements into values that are larger than the number of
9303 /// elements in the input.
9304 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9305   unsigned NElts = SVI->getType()->getNumElements();
9306   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9307     return std::vector<unsigned>(NElts, 0);
9308   if (isa<UndefValue>(SVI->getOperand(2)))
9309     return std::vector<unsigned>(NElts, 2*NElts);
9310
9311   std::vector<unsigned> Result;
9312   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9313   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9314     if (isa<UndefValue>(CP->getOperand(i)))
9315       Result.push_back(NElts*2);  // undef -> 8
9316     else
9317       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9318   return Result;
9319 }
9320
9321 /// FindScalarElement - Given a vector and an element number, see if the scalar
9322 /// value is already around as a register, for example if it were inserted then
9323 /// extracted from the vector.
9324 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9325   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9326   const VectorType *PTy = cast<VectorType>(V->getType());
9327   unsigned Width = PTy->getNumElements();
9328   if (EltNo >= Width)  // Out of range access.
9329     return UndefValue::get(PTy->getElementType());
9330   
9331   if (isa<UndefValue>(V))
9332     return UndefValue::get(PTy->getElementType());
9333   else if (isa<ConstantAggregateZero>(V))
9334     return Constant::getNullValue(PTy->getElementType());
9335   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9336     return CP->getOperand(EltNo);
9337   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9338     // If this is an insert to a variable element, we don't know what it is.
9339     if (!isa<ConstantInt>(III->getOperand(2))) 
9340       return 0;
9341     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9342     
9343     // If this is an insert to the element we are looking for, return the
9344     // inserted value.
9345     if (EltNo == IIElt) 
9346       return III->getOperand(1);
9347     
9348     // Otherwise, the insertelement doesn't modify the value, recurse on its
9349     // vector input.
9350     return FindScalarElement(III->getOperand(0), EltNo);
9351   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9352     unsigned InEl = getShuffleMask(SVI)[EltNo];
9353     if (InEl < Width)
9354       return FindScalarElement(SVI->getOperand(0), InEl);
9355     else if (InEl < Width*2)
9356       return FindScalarElement(SVI->getOperand(1), InEl - Width);
9357     else
9358       return UndefValue::get(PTy->getElementType());
9359   }
9360   
9361   // Otherwise, we don't know.
9362   return 0;
9363 }
9364
9365 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9366
9367   // If vector val is undef, replace extract with scalar undef.
9368   if (isa<UndefValue>(EI.getOperand(0)))
9369     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9370
9371   // If vector val is constant 0, replace extract with scalar 0.
9372   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9373     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9374   
9375   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9376     // If vector val is constant with uniform operands, replace EI
9377     // with that operand
9378     Constant *op0 = C->getOperand(0);
9379     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9380       if (C->getOperand(i) != op0) {
9381         op0 = 0; 
9382         break;
9383       }
9384     if (op0)
9385       return ReplaceInstUsesWith(EI, op0);
9386   }
9387   
9388   // If extracting a specified index from the vector, see if we can recursively
9389   // find a previously computed scalar that was inserted into the vector.
9390   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9391     unsigned IndexVal = IdxC->getZExtValue();
9392     unsigned VectorWidth = 
9393       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9394       
9395     // If this is extracting an invalid index, turn this into undef, to avoid
9396     // crashing the code below.
9397     if (IndexVal >= VectorWidth)
9398       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9399     
9400     // This instruction only demands the single element from the input vector.
9401     // If the input vector has a single use, simplify it based on this use
9402     // property.
9403     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
9404       uint64_t UndefElts;
9405       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9406                                                 1 << IndexVal,
9407                                                 UndefElts)) {
9408         EI.setOperand(0, V);
9409         return &EI;
9410       }
9411     }
9412     
9413     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9414       return ReplaceInstUsesWith(EI, Elt);
9415     
9416     // If the this extractelement is directly using a bitcast from a vector of
9417     // the same number of elements, see if we can find the source element from
9418     // it.  In this case, we will end up needing to bitcast the scalars.
9419     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9420       if (const VectorType *VT = 
9421               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9422         if (VT->getNumElements() == VectorWidth)
9423           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9424             return new BitCastInst(Elt, EI.getType());
9425     }
9426   }
9427   
9428   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9429     if (I->hasOneUse()) {
9430       // Push extractelement into predecessor operation if legal and
9431       // profitable to do so
9432       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9433         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9434         if (CheapToScalarize(BO, isConstantElt)) {
9435           ExtractElementInst *newEI0 = 
9436             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9437                                    EI.getName()+".lhs");
9438           ExtractElementInst *newEI1 =
9439             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9440                                    EI.getName()+".rhs");
9441           InsertNewInstBefore(newEI0, EI);
9442           InsertNewInstBefore(newEI1, EI);
9443           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9444         }
9445       } else if (isa<LoadInst>(I)) {
9446         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9447                                       PointerType::get(EI.getType()), EI);
9448         GetElementPtrInst *GEP = 
9449           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9450         InsertNewInstBefore(GEP, EI);
9451         return new LoadInst(GEP);
9452       }
9453     }
9454     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9455       // Extracting the inserted element?
9456       if (IE->getOperand(2) == EI.getOperand(1))
9457         return ReplaceInstUsesWith(EI, IE->getOperand(1));
9458       // If the inserted and extracted elements are constants, they must not
9459       // be the same value, extract from the pre-inserted value instead.
9460       if (isa<Constant>(IE->getOperand(2)) &&
9461           isa<Constant>(EI.getOperand(1))) {
9462         AddUsesToWorkList(EI);
9463         EI.setOperand(0, IE->getOperand(0));
9464         return &EI;
9465       }
9466     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9467       // If this is extracting an element from a shufflevector, figure out where
9468       // it came from and extract from the appropriate input element instead.
9469       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9470         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9471         Value *Src;
9472         if (SrcIdx < SVI->getType()->getNumElements())
9473           Src = SVI->getOperand(0);
9474         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9475           SrcIdx -= SVI->getType()->getNumElements();
9476           Src = SVI->getOperand(1);
9477         } else {
9478           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9479         }
9480         return new ExtractElementInst(Src, SrcIdx);
9481       }
9482     }
9483   }
9484   return 0;
9485 }
9486
9487 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9488 /// elements from either LHS or RHS, return the shuffle mask and true. 
9489 /// Otherwise, return false.
9490 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9491                                          std::vector<Constant*> &Mask) {
9492   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9493          "Invalid CollectSingleShuffleElements");
9494   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9495
9496   if (isa<UndefValue>(V)) {
9497     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9498     return true;
9499   } else if (V == LHS) {
9500     for (unsigned i = 0; i != NumElts; ++i)
9501       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9502     return true;
9503   } else if (V == RHS) {
9504     for (unsigned i = 0; i != NumElts; ++i)
9505       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9506     return true;
9507   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9508     // If this is an insert of an extract from some other vector, include it.
9509     Value *VecOp    = IEI->getOperand(0);
9510     Value *ScalarOp = IEI->getOperand(1);
9511     Value *IdxOp    = IEI->getOperand(2);
9512     
9513     if (!isa<ConstantInt>(IdxOp))
9514       return false;
9515     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9516     
9517     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
9518       // Okay, we can handle this if the vector we are insertinting into is
9519       // transitively ok.
9520       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9521         // If so, update the mask to reflect the inserted undef.
9522         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9523         return true;
9524       }      
9525     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9526       if (isa<ConstantInt>(EI->getOperand(1)) &&
9527           EI->getOperand(0)->getType() == V->getType()) {
9528         unsigned ExtractedIdx =
9529           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9530         
9531         // This must be extracting from either LHS or RHS.
9532         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9533           // Okay, we can handle this if the vector we are insertinting into is
9534           // transitively ok.
9535           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9536             // If so, update the mask to reflect the inserted value.
9537             if (EI->getOperand(0) == LHS) {
9538               Mask[InsertedIdx & (NumElts-1)] = 
9539                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9540             } else {
9541               assert(EI->getOperand(0) == RHS);
9542               Mask[InsertedIdx & (NumElts-1)] = 
9543                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9544               
9545             }
9546             return true;
9547           }
9548         }
9549       }
9550     }
9551   }
9552   // TODO: Handle shufflevector here!
9553   
9554   return false;
9555 }
9556
9557 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9558 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
9559 /// that computes V and the LHS value of the shuffle.
9560 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9561                                      Value *&RHS) {
9562   assert(isa<VectorType>(V->getType()) && 
9563          (RHS == 0 || V->getType() == RHS->getType()) &&
9564          "Invalid shuffle!");
9565   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9566
9567   if (isa<UndefValue>(V)) {
9568     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9569     return V;
9570   } else if (isa<ConstantAggregateZero>(V)) {
9571     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9572     return V;
9573   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9574     // If this is an insert of an extract from some other vector, include it.
9575     Value *VecOp    = IEI->getOperand(0);
9576     Value *ScalarOp = IEI->getOperand(1);
9577     Value *IdxOp    = IEI->getOperand(2);
9578     
9579     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9580       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9581           EI->getOperand(0)->getType() == V->getType()) {
9582         unsigned ExtractedIdx =
9583           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9584         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9585         
9586         // Either the extracted from or inserted into vector must be RHSVec,
9587         // otherwise we'd end up with a shuffle of three inputs.
9588         if (EI->getOperand(0) == RHS || RHS == 0) {
9589           RHS = EI->getOperand(0);
9590           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9591           Mask[InsertedIdx & (NumElts-1)] = 
9592             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9593           return V;
9594         }
9595         
9596         if (VecOp == RHS) {
9597           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9598           // Everything but the extracted element is replaced with the RHS.
9599           for (unsigned i = 0; i != NumElts; ++i) {
9600             if (i != InsertedIdx)
9601               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9602           }
9603           return V;
9604         }
9605         
9606         // If this insertelement is a chain that comes from exactly these two
9607         // vectors, return the vector and the effective shuffle.
9608         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9609           return EI->getOperand(0);
9610         
9611       }
9612     }
9613   }
9614   // TODO: Handle shufflevector here!
9615   
9616   // Otherwise, can't do anything fancy.  Return an identity vector.
9617   for (unsigned i = 0; i != NumElts; ++i)
9618     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9619   return V;
9620 }
9621
9622 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9623   Value *VecOp    = IE.getOperand(0);
9624   Value *ScalarOp = IE.getOperand(1);
9625   Value *IdxOp    = IE.getOperand(2);
9626   
9627   // Inserting an undef or into an undefined place, remove this.
9628   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9629     ReplaceInstUsesWith(IE, VecOp);
9630   
9631   // If the inserted element was extracted from some other vector, and if the 
9632   // indexes are constant, try to turn this into a shufflevector operation.
9633   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9634     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9635         EI->getOperand(0)->getType() == IE.getType()) {
9636       unsigned NumVectorElts = IE.getType()->getNumElements();
9637       unsigned ExtractedIdx =
9638         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9639       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9640       
9641       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9642         return ReplaceInstUsesWith(IE, VecOp);
9643       
9644       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
9645         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9646       
9647       // If we are extracting a value from a vector, then inserting it right
9648       // back into the same place, just use the input vector.
9649       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9650         return ReplaceInstUsesWith(IE, VecOp);      
9651       
9652       // We could theoretically do this for ANY input.  However, doing so could
9653       // turn chains of insertelement instructions into a chain of shufflevector
9654       // instructions, and right now we do not merge shufflevectors.  As such,
9655       // only do this in a situation where it is clear that there is benefit.
9656       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9657         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
9658         // the values of VecOp, except then one read from EIOp0.
9659         // Build a new shuffle mask.
9660         std::vector<Constant*> Mask;
9661         if (isa<UndefValue>(VecOp))
9662           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9663         else {
9664           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9665           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9666                                                        NumVectorElts));
9667         } 
9668         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9669         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9670                                      ConstantVector::get(Mask));
9671       }
9672       
9673       // If this insertelement isn't used by some other insertelement, turn it
9674       // (and any insertelements it points to), into one big shuffle.
9675       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9676         std::vector<Constant*> Mask;
9677         Value *RHS = 0;
9678         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9679         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9680         // We now have a shuffle of LHS, RHS, Mask.
9681         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9682       }
9683     }
9684   }
9685
9686   return 0;
9687 }
9688
9689
9690 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9691   Value *LHS = SVI.getOperand(0);
9692   Value *RHS = SVI.getOperand(1);
9693   std::vector<unsigned> Mask = getShuffleMask(&SVI);
9694
9695   bool MadeChange = false;
9696   
9697   // Undefined shuffle mask -> undefined value.
9698   if (isa<UndefValue>(SVI.getOperand(2)))
9699     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9700   
9701   // If we have shuffle(x, undef, mask) and any elements of mask refer to
9702   // the undef, change them to undefs.
9703   if (isa<UndefValue>(SVI.getOperand(1))) {
9704     // Scan to see if there are any references to the RHS.  If so, replace them
9705     // with undef element refs and set MadeChange to true.
9706     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9707       if (Mask[i] >= e && Mask[i] != 2*e) {
9708         Mask[i] = 2*e;
9709         MadeChange = true;
9710       }
9711     }
9712     
9713     if (MadeChange) {
9714       // Remap any references to RHS to use LHS.
9715       std::vector<Constant*> Elts;
9716       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9717         if (Mask[i] == 2*e)
9718           Elts.push_back(UndefValue::get(Type::Int32Ty));
9719         else
9720           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9721       }
9722       SVI.setOperand(2, ConstantVector::get(Elts));
9723     }
9724   }
9725   
9726   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
9727   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9728   if (LHS == RHS || isa<UndefValue>(LHS)) {
9729     if (isa<UndefValue>(LHS) && LHS == RHS) {
9730       // shuffle(undef,undef,mask) -> undef.
9731       return ReplaceInstUsesWith(SVI, LHS);
9732     }
9733     
9734     // Remap any references to RHS to use LHS.
9735     std::vector<Constant*> Elts;
9736     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9737       if (Mask[i] >= 2*e)
9738         Elts.push_back(UndefValue::get(Type::Int32Ty));
9739       else {
9740         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9741             (Mask[i] <  e && isa<UndefValue>(LHS)))
9742           Mask[i] = 2*e;     // Turn into undef.
9743         else
9744           Mask[i] &= (e-1);  // Force to LHS.
9745         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9746       }
9747     }
9748     SVI.setOperand(0, SVI.getOperand(1));
9749     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9750     SVI.setOperand(2, ConstantVector::get(Elts));
9751     LHS = SVI.getOperand(0);
9752     RHS = SVI.getOperand(1);
9753     MadeChange = true;
9754   }
9755   
9756   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9757   bool isLHSID = true, isRHSID = true;
9758     
9759   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9760     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9761     // Is this an identity shuffle of the LHS value?
9762     isLHSID &= (Mask[i] == i);
9763       
9764     // Is this an identity shuffle of the RHS value?
9765     isRHSID &= (Mask[i]-e == i);
9766   }
9767
9768   // Eliminate identity shuffles.
9769   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9770   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9771   
9772   // If the LHS is a shufflevector itself, see if we can combine it with this
9773   // one without producing an unusual shuffle.  Here we are really conservative:
9774   // we are absolutely afraid of producing a shuffle mask not in the input
9775   // program, because the code gen may not be smart enough to turn a merged
9776   // shuffle into two specific shuffles: it may produce worse code.  As such,
9777   // we only merge two shuffles if the result is one of the two input shuffle
9778   // masks.  In this case, merging the shuffles just removes one instruction,
9779   // which we know is safe.  This is good for things like turning:
9780   // (splat(splat)) -> splat.
9781   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9782     if (isa<UndefValue>(RHS)) {
9783       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9784
9785       std::vector<unsigned> NewMask;
9786       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9787         if (Mask[i] >= 2*e)
9788           NewMask.push_back(2*e);
9789         else
9790           NewMask.push_back(LHSMask[Mask[i]]);
9791       
9792       // If the result mask is equal to the src shuffle or this shuffle mask, do
9793       // the replacement.
9794       if (NewMask == LHSMask || NewMask == Mask) {
9795         std::vector<Constant*> Elts;
9796         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9797           if (NewMask[i] >= e*2) {
9798             Elts.push_back(UndefValue::get(Type::Int32Ty));
9799           } else {
9800             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9801           }
9802         }
9803         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9804                                      LHSSVI->getOperand(1),
9805                                      ConstantVector::get(Elts));
9806       }
9807     }
9808   }
9809
9810   return MadeChange ? &SVI : 0;
9811 }
9812
9813
9814
9815
9816 /// TryToSinkInstruction - Try to move the specified instruction from its
9817 /// current block into the beginning of DestBlock, which can only happen if it's
9818 /// safe to move the instruction past all of the instructions between it and the
9819 /// end of its block.
9820 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9821   assert(I->hasOneUse() && "Invariants didn't hold!");
9822
9823   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9824   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9825
9826   // Do not sink alloca instructions out of the entry block.
9827   if (isa<AllocaInst>(I) && I->getParent() ==
9828         &DestBlock->getParent()->getEntryBlock())
9829     return false;
9830
9831   // We can only sink load instructions if there is nothing between the load and
9832   // the end of block that could change the value.
9833   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9834     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9835          Scan != E; ++Scan)
9836       if (Scan->mayWriteToMemory())
9837         return false;
9838   }
9839
9840   BasicBlock::iterator InsertPos = DestBlock->begin();
9841   while (isa<PHINode>(InsertPos)) ++InsertPos;
9842
9843   I->moveBefore(InsertPos);
9844   ++NumSunkInst;
9845   return true;
9846 }
9847
9848
9849 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9850 /// all reachable code to the worklist.
9851 ///
9852 /// This has a couple of tricks to make the code faster and more powerful.  In
9853 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9854 /// them to the worklist (this significantly speeds up instcombine on code where
9855 /// many instructions are dead or constant).  Additionally, if we find a branch
9856 /// whose condition is a known constant, we only visit the reachable successors.
9857 ///
9858 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9859                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9860                                        InstCombiner &IC,
9861                                        const TargetData *TD) {
9862   std::vector<BasicBlock*> Worklist;
9863   Worklist.push_back(BB);
9864
9865   while (!Worklist.empty()) {
9866     BB = Worklist.back();
9867     Worklist.pop_back();
9868     
9869     // We have now visited this block!  If we've already been here, ignore it.
9870     if (!Visited.insert(BB)) continue;
9871     
9872     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9873       Instruction *Inst = BBI++;
9874       
9875       // DCE instruction if trivially dead.
9876       if (isInstructionTriviallyDead(Inst)) {
9877         ++NumDeadInst;
9878         DOUT << "IC: DCE: " << *Inst;
9879         Inst->eraseFromParent();
9880         continue;
9881       }
9882       
9883       // ConstantProp instruction if trivially constant.
9884       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9885         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9886         Inst->replaceAllUsesWith(C);
9887         ++NumConstProp;
9888         Inst->eraseFromParent();
9889         continue;
9890       }
9891       
9892       IC.AddToWorkList(Inst);
9893     }
9894
9895     // Recursively visit successors.  If this is a branch or switch on a
9896     // constant, only visit the reachable successor.
9897     TerminatorInst *TI = BB->getTerminator();
9898     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9899       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9900         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9901         Worklist.push_back(BI->getSuccessor(!CondVal));
9902         continue;
9903       }
9904     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9905       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9906         // See if this is an explicit destination.
9907         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9908           if (SI->getCaseValue(i) == Cond) {
9909             Worklist.push_back(SI->getSuccessor(i));
9910             continue;
9911           }
9912         
9913         // Otherwise it is the default destination.
9914         Worklist.push_back(SI->getSuccessor(0));
9915         continue;
9916       }
9917     }
9918     
9919     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9920       Worklist.push_back(TI->getSuccessor(i));
9921   }
9922 }
9923
9924 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
9925   bool Changed = false;
9926   TD = &getAnalysis<TargetData>();
9927   
9928   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9929              << F.getNameStr() << "\n");
9930
9931   {
9932     // Do a depth-first traversal of the function, populate the worklist with
9933     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9934     // track of which blocks we visit.
9935     SmallPtrSet<BasicBlock*, 64> Visited;
9936     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
9937
9938     // Do a quick scan over the function.  If we find any blocks that are
9939     // unreachable, remove any instructions inside of them.  This prevents
9940     // the instcombine code from having to deal with some bad special cases.
9941     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9942       if (!Visited.count(BB)) {
9943         Instruction *Term = BB->getTerminator();
9944         while (Term != BB->begin()) {   // Remove instrs bottom-up
9945           BasicBlock::iterator I = Term; --I;
9946
9947           DOUT << "IC: DCE: " << *I;
9948           ++NumDeadInst;
9949
9950           if (!I->use_empty())
9951             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9952           I->eraseFromParent();
9953         }
9954       }
9955   }
9956
9957   while (!Worklist.empty()) {
9958     Instruction *I = RemoveOneFromWorkList();
9959     if (I == 0) continue;  // skip null values.
9960
9961     // Check to see if we can DCE the instruction.
9962     if (isInstructionTriviallyDead(I)) {
9963       // Add operands to the worklist.
9964       if (I->getNumOperands() < 4)
9965         AddUsesToWorkList(*I);
9966       ++NumDeadInst;
9967
9968       DOUT << "IC: DCE: " << *I;
9969
9970       I->eraseFromParent();
9971       RemoveFromWorkList(I);
9972       continue;
9973     }
9974
9975     // Instruction isn't dead, see if we can constant propagate it.
9976     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9977       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9978
9979       // Add operands to the worklist.
9980       AddUsesToWorkList(*I);
9981       ReplaceInstUsesWith(*I, C);
9982
9983       ++NumConstProp;
9984       I->eraseFromParent();
9985       RemoveFromWorkList(I);
9986       continue;
9987     }
9988
9989     // See if we can trivially sink this instruction to a successor basic block.
9990     if (I->hasOneUse()) {
9991       BasicBlock *BB = I->getParent();
9992       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9993       if (UserParent != BB) {
9994         bool UserIsSuccessor = false;
9995         // See if the user is one of our successors.
9996         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9997           if (*SI == UserParent) {
9998             UserIsSuccessor = true;
9999             break;
10000           }
10001
10002         // If the user is one of our immediate successors, and if that successor
10003         // only has us as a predecessors (we'd have to split the critical edge
10004         // otherwise), we can keep going.
10005         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10006             next(pred_begin(UserParent)) == pred_end(UserParent))
10007           // Okay, the CFG is simple enough, try to sink this instruction.
10008           Changed |= TryToSinkInstruction(I, UserParent);
10009       }
10010     }
10011
10012     // Now that we have an instruction, try combining it to simplify it...
10013 #ifndef NDEBUG
10014     std::string OrigI;
10015 #endif
10016     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10017     if (Instruction *Result = visit(*I)) {
10018       ++NumCombined;
10019       // Should we replace the old instruction with a new one?
10020       if (Result != I) {
10021         DOUT << "IC: Old = " << *I
10022              << "    New = " << *Result;
10023
10024         // Everything uses the new instruction now.
10025         I->replaceAllUsesWith(Result);
10026
10027         // Push the new instruction and any users onto the worklist.
10028         AddToWorkList(Result);
10029         AddUsersToWorkList(*Result);
10030
10031         // Move the name to the new instruction first.
10032         Result->takeName(I);
10033
10034         // Insert the new instruction into the basic block...
10035         BasicBlock *InstParent = I->getParent();
10036         BasicBlock::iterator InsertPos = I;
10037
10038         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10039           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10040             ++InsertPos;
10041
10042         InstParent->getInstList().insert(InsertPos, Result);
10043
10044         // Make sure that we reprocess all operands now that we reduced their
10045         // use counts.
10046         AddUsesToWorkList(*I);
10047
10048         // Instructions can end up on the worklist more than once.  Make sure
10049         // we do not process an instruction that has been deleted.
10050         RemoveFromWorkList(I);
10051
10052         // Erase the old instruction.
10053         InstParent->getInstList().erase(I);
10054       } else {
10055 #ifndef NDEBUG
10056         DOUT << "IC: Mod = " << OrigI
10057              << "    New = " << *I;
10058 #endif
10059
10060         // If the instruction was modified, it's possible that it is now dead.
10061         // if so, remove it.
10062         if (isInstructionTriviallyDead(I)) {
10063           // Make sure we process all operands now that we are reducing their
10064           // use counts.
10065           AddUsesToWorkList(*I);
10066
10067           // Instructions may end up in the worklist more than once.  Erase all
10068           // occurrences of this instruction.
10069           RemoveFromWorkList(I);
10070           I->eraseFromParent();
10071         } else {
10072           AddToWorkList(I);
10073           AddUsersToWorkList(*I);
10074         }
10075       }
10076       Changed = true;
10077     }
10078   }
10079
10080   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10081   return Changed;
10082 }
10083
10084
10085 bool InstCombiner::runOnFunction(Function &F) {
10086   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10087   
10088   bool EverMadeChange = false;
10089
10090   // Iterate while there is work to do.
10091   unsigned Iteration = 0;
10092   while (DoOneIteration(F, Iteration++)) 
10093     EverMadeChange = true;
10094   return EverMadeChange;
10095 }
10096
10097 FunctionPass *llvm::createInstructionCombiningPass() {
10098   return new InstCombiner();
10099 }
10100