Transforming -A + -B --> -(A + B) isn't safe for FP, thanks
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/ParameterAttributes.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <sstream>
62 using namespace llvm;
63 using namespace llvm::PatternMatch;
64
65 STATISTIC(NumCombined , "Number of insts combined");
66 STATISTIC(NumConstProp, "Number of constant folds");
67 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69 STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71 namespace {
72   class VISIBILITY_HIDDEN InstCombiner
73     : public FunctionPass,
74       public InstVisitor<InstCombiner, Instruction*> {
75     // Worklist of all of the instructions that need to be simplified.
76     std::vector<Instruction*> Worklist;
77     DenseMap<Instruction*, unsigned> WorklistMap;
78     TargetData *TD;
79     bool MustPreserveLCSSA;
80   public:
81     static char ID; // Pass identification, replacement for typeid
82     InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84     /// AddToWorkList - Add the specified instruction to the worklist if it
85     /// isn't already in it.
86     void AddToWorkList(Instruction *I) {
87       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88         Worklist.push_back(I);
89     }
90     
91     // RemoveFromWorkList - remove I from the worklist if it exists.
92     void RemoveFromWorkList(Instruction *I) {
93       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94       if (It == WorklistMap.end()) return; // Not in worklist.
95       
96       // Don't bother moving everything down, just null out the slot.
97       Worklist[It->second] = 0;
98       
99       WorklistMap.erase(It);
100     }
101     
102     Instruction *RemoveOneFromWorkList() {
103       Instruction *I = Worklist.back();
104       Worklist.pop_back();
105       WorklistMap.erase(I);
106       return I;
107     }
108
109     
110     /// AddUsersToWorkList - When an instruction is simplified, add all users of
111     /// the instruction to the work lists because they might get more simplified
112     /// now.
113     ///
114     void AddUsersToWorkList(Value &I) {
115       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116            UI != UE; ++UI)
117         AddToWorkList(cast<Instruction>(*UI));
118     }
119
120     /// AddUsesToWorkList - When an instruction is simplified, add operands to
121     /// the work lists because they might get more simplified now.
122     ///
123     void AddUsesToWorkList(Instruction &I) {
124       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126           AddToWorkList(Op);
127     }
128     
129     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130     /// dead.  Add all of its operands to the worklist, turning them into
131     /// undef's to reduce the number of uses of those instructions.
132     ///
133     /// Return the specified operand before it is turned into an undef.
134     ///
135     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136       Value *R = I.getOperand(op);
137       
138       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140           AddToWorkList(Op);
141           // Set the operand to undef to drop the use.
142           I.setOperand(i, UndefValue::get(Op->getType()));
143         }
144       
145       return R;
146     }
147
148   public:
149     virtual bool runOnFunction(Function &F);
150     
151     bool DoOneIteration(Function &F, unsigned ItNum);
152
153     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154       AU.addRequired<TargetData>();
155       AU.addPreservedID(LCSSAID);
156       AU.setPreservesCFG();
157     }
158
159     TargetData &getTargetData() const { return *TD; }
160
161     // Visitation implementation - Implement instruction combining for different
162     // instruction types.  The semantics are as follows:
163     // Return Value:
164     //    null        - No change was made
165     //     I          - Change was made, I is still valid, I may be dead though
166     //   otherwise    - Change was made, replace I with returned instruction
167     //
168     Instruction *visitAdd(BinaryOperator &I);
169     Instruction *visitSub(BinaryOperator &I);
170     Instruction *visitMul(BinaryOperator &I);
171     Instruction *visitURem(BinaryOperator &I);
172     Instruction *visitSRem(BinaryOperator &I);
173     Instruction *visitFRem(BinaryOperator &I);
174     Instruction *commonRemTransforms(BinaryOperator &I);
175     Instruction *commonIRemTransforms(BinaryOperator &I);
176     Instruction *commonDivTransforms(BinaryOperator &I);
177     Instruction *commonIDivTransforms(BinaryOperator &I);
178     Instruction *visitUDiv(BinaryOperator &I);
179     Instruction *visitSDiv(BinaryOperator &I);
180     Instruction *visitFDiv(BinaryOperator &I);
181     Instruction *visitAnd(BinaryOperator &I);
182     Instruction *visitOr (BinaryOperator &I);
183     Instruction *visitXor(BinaryOperator &I);
184     Instruction *visitShl(BinaryOperator &I);
185     Instruction *visitAShr(BinaryOperator &I);
186     Instruction *visitLShr(BinaryOperator &I);
187     Instruction *commonShiftTransforms(BinaryOperator &I);
188     Instruction *visitFCmpInst(FCmpInst &I);
189     Instruction *visitICmpInst(ICmpInst &I);
190     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
191     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192                                                 Instruction *LHS,
193                                                 ConstantInt *RHS);
194     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195                                 ConstantInt *DivRHS);
196
197     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198                              ICmpInst::Predicate Cond, Instruction &I);
199     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
200                                      BinaryOperator &I);
201     Instruction *commonCastTransforms(CastInst &CI);
202     Instruction *commonIntCastTransforms(CastInst &CI);
203     Instruction *commonPointerCastTransforms(CastInst &CI);
204     Instruction *visitTrunc(TruncInst &CI);
205     Instruction *visitZExt(ZExtInst &CI);
206     Instruction *visitSExt(SExtInst &CI);
207     Instruction *visitFPTrunc(FPTruncInst &CI);
208     Instruction *visitFPExt(CastInst &CI);
209     Instruction *visitFPToUI(CastInst &CI);
210     Instruction *visitFPToSI(CastInst &CI);
211     Instruction *visitUIToFP(CastInst &CI);
212     Instruction *visitSIToFP(CastInst &CI);
213     Instruction *visitPtrToInt(CastInst &CI);
214     Instruction *visitIntToPtr(IntToPtrInst &CI);
215     Instruction *visitBitCast(BitCastInst &CI);
216     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217                                 Instruction *FI);
218     Instruction *visitSelectInst(SelectInst &CI);
219     Instruction *visitCallInst(CallInst &CI);
220     Instruction *visitInvokeInst(InvokeInst &II);
221     Instruction *visitPHINode(PHINode &PN);
222     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
223     Instruction *visitAllocationInst(AllocationInst &AI);
224     Instruction *visitFreeInst(FreeInst &FI);
225     Instruction *visitLoadInst(LoadInst &LI);
226     Instruction *visitStoreInst(StoreInst &SI);
227     Instruction *visitBranchInst(BranchInst &BI);
228     Instruction *visitSwitchInst(SwitchInst &SI);
229     Instruction *visitInsertElementInst(InsertElementInst &IE);
230     Instruction *visitExtractElementInst(ExtractElementInst &EI);
231     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
232
233     // visitInstruction - Specify what to return for unhandled instructions...
234     Instruction *visitInstruction(Instruction &I) { return 0; }
235
236   private:
237     Instruction *visitCallSite(CallSite CS);
238     bool transformConstExprCastCall(CallSite CS);
239     Instruction *transformCallThroughTrampoline(CallSite CS);
240
241   public:
242     // InsertNewInstBefore - insert an instruction New before instruction Old
243     // in the program.  Add the new instruction to the worklist.
244     //
245     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
246       assert(New && New->getParent() == 0 &&
247              "New instruction already inserted into a basic block!");
248       BasicBlock *BB = Old.getParent();
249       BB->getInstList().insert(&Old, New);  // Insert inst
250       AddToWorkList(New);
251       return New;
252     }
253
254     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
255     /// This also adds the cast to the worklist.  Finally, this returns the
256     /// cast.
257     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
258                             Instruction &Pos) {
259       if (V->getType() == Ty) return V;
260
261       if (Constant *CV = dyn_cast<Constant>(V))
262         return ConstantExpr::getCast(opc, CV, Ty);
263       
264       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
265       AddToWorkList(C);
266       return C;
267     }
268         
269     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
270       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
271     }
272
273
274     // ReplaceInstUsesWith - This method is to be used when an instruction is
275     // found to be dead, replacable with another preexisting expression.  Here
276     // we add all uses of I to the worklist, replace all uses of I with the new
277     // value, then return I, so that the inst combiner will know that I was
278     // modified.
279     //
280     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
281       AddUsersToWorkList(I);         // Add all modified instrs to worklist
282       if (&I != V) {
283         I.replaceAllUsesWith(V);
284         return &I;
285       } else {
286         // If we are replacing the instruction with itself, this must be in a
287         // segment of unreachable code, so just clobber the instruction.
288         I.replaceAllUsesWith(UndefValue::get(I.getType()));
289         return &I;
290       }
291     }
292
293     // UpdateValueUsesWith - This method is to be used when an value is
294     // found to be replacable with another preexisting expression or was
295     // updated.  Here we add all uses of I to the worklist, replace all uses of
296     // I with the new value (unless the instruction was just updated), then
297     // return true, so that the inst combiner will know that I was modified.
298     //
299     bool UpdateValueUsesWith(Value *Old, Value *New) {
300       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
301       if (Old != New)
302         Old->replaceAllUsesWith(New);
303       if (Instruction *I = dyn_cast<Instruction>(Old))
304         AddToWorkList(I);
305       if (Instruction *I = dyn_cast<Instruction>(New))
306         AddToWorkList(I);
307       return true;
308     }
309     
310     // EraseInstFromFunction - When dealing with an instruction that has side
311     // effects or produces a void value, we can't rely on DCE to delete the
312     // instruction.  Instead, visit methods should return the value returned by
313     // this function.
314     Instruction *EraseInstFromFunction(Instruction &I) {
315       assert(I.use_empty() && "Cannot erase instruction that is used!");
316       AddUsesToWorkList(I);
317       RemoveFromWorkList(&I);
318       I.eraseFromParent();
319       return 0;  // Don't do anything with FI
320     }
321
322   private:
323     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
324     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
325     /// casts that are known to not do anything...
326     ///
327     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
328                                    Value *V, const Type *DestTy,
329                                    Instruction *InsertBefore);
330
331     /// SimplifyCommutative - This performs a few simplifications for 
332     /// commutative operators.
333     bool SimplifyCommutative(BinaryOperator &I);
334
335     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
336     /// most-complex to least-complex order.
337     bool SimplifyCompare(CmpInst &I);
338
339     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
340     /// on the demanded bits.
341     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
342                               APInt& KnownZero, APInt& KnownOne,
343                               unsigned Depth = 0);
344
345     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
346                                       uint64_t &UndefElts, unsigned Depth = 0);
347       
348     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
349     // PHI node as operand #0, see if we can fold the instruction into the PHI
350     // (which is only possible if all operands to the PHI are constants).
351     Instruction *FoldOpIntoPhi(Instruction &I);
352
353     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
354     // operator and they all are only used by the PHI, PHI together their
355     // inputs, and do the operation once, to the result of the PHI.
356     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
357     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
358     
359     
360     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
361                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
362     
363     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
364                               bool isSub, Instruction &I);
365     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
366                                  bool isSigned, bool Inside, Instruction &IB);
367     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
368     Instruction *MatchBSwap(BinaryOperator &I);
369     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
370     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
371
372
373     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
374   };
375
376   char InstCombiner::ID = 0;
377   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
378 }
379
380 // getComplexity:  Assign a complexity or rank value to LLVM Values...
381 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
382 static unsigned getComplexity(Value *V) {
383   if (isa<Instruction>(V)) {
384     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
385       return 3;
386     return 4;
387   }
388   if (isa<Argument>(V)) return 3;
389   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
390 }
391
392 // isOnlyUse - Return true if this instruction will be deleted if we stop using
393 // it.
394 static bool isOnlyUse(Value *V) {
395   return V->hasOneUse() || isa<Constant>(V);
396 }
397
398 // getPromotedType - Return the specified type promoted as it would be to pass
399 // though a va_arg area...
400 static const Type *getPromotedType(const Type *Ty) {
401   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
402     if (ITy->getBitWidth() < 32)
403       return Type::Int32Ty;
404   }
405   return Ty;
406 }
407
408 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
409 /// expression bitcast,  return the operand value, otherwise return null.
410 static Value *getBitCastOperand(Value *V) {
411   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
412     return I->getOperand(0);
413   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
414     if (CE->getOpcode() == Instruction::BitCast)
415       return CE->getOperand(0);
416   return 0;
417 }
418
419 /// This function is a wrapper around CastInst::isEliminableCastPair. It
420 /// simply extracts arguments and returns what that function returns.
421 static Instruction::CastOps 
422 isEliminableCastPair(
423   const CastInst *CI, ///< The first cast instruction
424   unsigned opcode,       ///< The opcode of the second cast instruction
425   const Type *DstTy,     ///< The target type for the second cast instruction
426   TargetData *TD         ///< The target data for pointer size
427 ) {
428   
429   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
430   const Type *MidTy = CI->getType();                  // B from above
431
432   // Get the opcodes of the two Cast instructions
433   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
434   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
435
436   return Instruction::CastOps(
437       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
438                                      DstTy, TD->getIntPtrType()));
439 }
440
441 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442 /// in any code being generated.  It does not require codegen if V is simple
443 /// enough or if the cast can be folded into other casts.
444 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
445                               const Type *Ty, TargetData *TD) {
446   if (V->getType() == Ty || isa<Constant>(V)) return false;
447   
448   // If this is another cast that can be eliminated, it isn't codegen either.
449   if (const CastInst *CI = dyn_cast<CastInst>(V))
450     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
451       return false;
452   return true;
453 }
454
455 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
456 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
457 /// casts that are known to not do anything...
458 ///
459 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
460                                              Value *V, const Type *DestTy,
461                                              Instruction *InsertBefore) {
462   if (V->getType() == DestTy) return V;
463   if (Constant *C = dyn_cast<Constant>(V))
464     return ConstantExpr::getCast(opcode, C, DestTy);
465   
466   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
467 }
468
469 // SimplifyCommutative - This performs a few simplifications for commutative
470 // operators:
471 //
472 //  1. Order operands such that they are listed from right (least complex) to
473 //     left (most complex).  This puts constants before unary operators before
474 //     binary operators.
475 //
476 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
478 //
479 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
480   bool Changed = false;
481   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482     Changed = !I.swapOperands();
483
484   if (!I.isAssociative()) return Changed;
485   Instruction::BinaryOps Opcode = I.getOpcode();
486   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488       if (isa<Constant>(I.getOperand(1))) {
489         Constant *Folded = ConstantExpr::get(I.getOpcode(),
490                                              cast<Constant>(I.getOperand(1)),
491                                              cast<Constant>(Op->getOperand(1)));
492         I.setOperand(0, Op->getOperand(0));
493         I.setOperand(1, Folded);
494         return true;
495       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497             isOnlyUse(Op) && isOnlyUse(Op1)) {
498           Constant *C1 = cast<Constant>(Op->getOperand(1));
499           Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
502           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
503           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504                                                     Op1->getOperand(0),
505                                                     Op1->getName(), &I);
506           AddToWorkList(New);
507           I.setOperand(0, New);
508           I.setOperand(1, Folded);
509           return true;
510         }
511     }
512   return Changed;
513 }
514
515 /// SimplifyCompare - For a CmpInst this function just orders the operands
516 /// so that theyare listed from right (least complex) to left (most complex).
517 /// This puts constants before unary operators before binary operators.
518 bool InstCombiner::SimplifyCompare(CmpInst &I) {
519   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
520     return false;
521   I.swapOperands();
522   // Compare instructions are not associative so there's nothing else we can do.
523   return true;
524 }
525
526 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
527 // if the LHS is a constant zero (which is the 'negate' form).
528 //
529 static inline Value *dyn_castNegVal(Value *V) {
530   if (BinaryOperator::isNeg(V))
531     return BinaryOperator::getNegArgument(V);
532
533   // Constants can be considered to be negated values if they can be folded.
534   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535     return ConstantExpr::getNeg(C);
536   return 0;
537 }
538
539 static inline Value *dyn_castNotVal(Value *V) {
540   if (BinaryOperator::isNot(V))
541     return BinaryOperator::getNotArgument(V);
542
543   // Constants can be considered to be not'ed values...
544   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
545     return ConstantInt::get(~C->getValue());
546   return 0;
547 }
548
549 // dyn_castFoldableMul - If this value is a multiply that can be folded into
550 // other computations (because it has a constant operand), return the
551 // non-constant operand of the multiply, and set CST to point to the multiplier.
552 // Otherwise, return null.
553 //
554 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
555   if (V->hasOneUse() && V->getType()->isInteger())
556     if (Instruction *I = dyn_cast<Instruction>(V)) {
557       if (I->getOpcode() == Instruction::Mul)
558         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
559           return I->getOperand(0);
560       if (I->getOpcode() == Instruction::Shl)
561         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
562           // The multiplier is really 1 << CST.
563           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
564           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
565           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
566           return I->getOperand(0);
567         }
568     }
569   return 0;
570 }
571
572 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
573 /// expression, return it.
574 static User *dyn_castGetElementPtr(Value *V) {
575   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
576   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
577     if (CE->getOpcode() == Instruction::GetElementPtr)
578       return cast<User>(V);
579   return false;
580 }
581
582 /// AddOne - Add one to a ConstantInt
583 static ConstantInt *AddOne(ConstantInt *C) {
584   APInt Val(C->getValue());
585   return ConstantInt::get(++Val);
586 }
587 /// SubOne - Subtract one from a ConstantInt
588 static ConstantInt *SubOne(ConstantInt *C) {
589   APInt Val(C->getValue());
590   return ConstantInt::get(--Val);
591 }
592 /// Add - Add two ConstantInts together
593 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
594   return ConstantInt::get(C1->getValue() + C2->getValue());
595 }
596 /// And - Bitwise AND two ConstantInts together
597 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
598   return ConstantInt::get(C1->getValue() & C2->getValue());
599 }
600 /// Subtract - Subtract one ConstantInt from another
601 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
602   return ConstantInt::get(C1->getValue() - C2->getValue());
603 }
604 /// Multiply - Multiply two ConstantInts together
605 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
606   return ConstantInt::get(C1->getValue() * C2->getValue());
607 }
608
609 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
610 /// known to be either zero or one and return them in the KnownZero/KnownOne
611 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
612 /// processing.
613 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
614 /// we cannot optimize based on the assumption that it is zero without changing
615 /// it to be an explicit zero.  If we don't change it to zero, other code could
616 /// optimized based on the contradictory assumption that it is non-zero.
617 /// Because instcombine aggressively folds operations with undef args anyway,
618 /// this won't lose us code quality.
619 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
620                               APInt& KnownOne, unsigned Depth = 0) {
621   assert(V && "No Value?");
622   assert(Depth <= 6 && "Limit Search Depth");
623   uint32_t BitWidth = Mask.getBitWidth();
624   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
625          KnownZero.getBitWidth() == BitWidth && 
626          KnownOne.getBitWidth() == BitWidth &&
627          "V, Mask, KnownOne and KnownZero should have same BitWidth");
628   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
629     // We know all of the bits for a constant!
630     KnownOne = CI->getValue() & Mask;
631     KnownZero = ~KnownOne & Mask;
632     return;
633   }
634
635   if (Depth == 6 || Mask == 0)
636     return;  // Limit search depth.
637
638   Instruction *I = dyn_cast<Instruction>(V);
639   if (!I) return;
640
641   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
642   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
643   
644   switch (I->getOpcode()) {
645   case Instruction::And: {
646     // If either the LHS or the RHS are Zero, the result is zero.
647     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
648     APInt Mask2(Mask & ~KnownZero);
649     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
650     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
651     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
652     
653     // Output known-1 bits are only known if set in both the LHS & RHS.
654     KnownOne &= KnownOne2;
655     // Output known-0 are known to be clear if zero in either the LHS | RHS.
656     KnownZero |= KnownZero2;
657     return;
658   }
659   case Instruction::Or: {
660     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
661     APInt Mask2(Mask & ~KnownOne);
662     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
663     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
664     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
665     
666     // Output known-0 bits are only known if clear in both the LHS & RHS.
667     KnownZero &= KnownZero2;
668     // Output known-1 are known to be set if set in either the LHS | RHS.
669     KnownOne |= KnownOne2;
670     return;
671   }
672   case Instruction::Xor: {
673     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
674     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
675     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
676     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
677     
678     // Output known-0 bits are known if clear or set in both the LHS & RHS.
679     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
680     // Output known-1 are known to be set if set in only one of the LHS, RHS.
681     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
682     KnownZero = KnownZeroOut;
683     return;
684   }
685   case Instruction::Select:
686     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
687     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
688     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
689     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
690
691     // Only known if known in both the LHS and RHS.
692     KnownOne &= KnownOne2;
693     KnownZero &= KnownZero2;
694     return;
695   case Instruction::FPTrunc:
696   case Instruction::FPExt:
697   case Instruction::FPToUI:
698   case Instruction::FPToSI:
699   case Instruction::SIToFP:
700   case Instruction::PtrToInt:
701   case Instruction::UIToFP:
702   case Instruction::IntToPtr:
703     return; // Can't work with floating point or pointers
704   case Instruction::Trunc: {
705     // All these have integer operands
706     uint32_t SrcBitWidth = 
707       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
708     APInt MaskIn(Mask);
709     MaskIn.zext(SrcBitWidth);
710     KnownZero.zext(SrcBitWidth);
711     KnownOne.zext(SrcBitWidth);
712     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
713     KnownZero.trunc(BitWidth);
714     KnownOne.trunc(BitWidth);
715     return;
716   }
717   case Instruction::BitCast: {
718     const Type *SrcTy = I->getOperand(0)->getType();
719     if (SrcTy->isInteger()) {
720       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
721       return;
722     }
723     break;
724   }
725   case Instruction::ZExt:  {
726     // Compute the bits in the result that are not present in the input.
727     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
728     uint32_t SrcBitWidth = SrcTy->getBitWidth();
729       
730     APInt MaskIn(Mask);
731     MaskIn.trunc(SrcBitWidth);
732     KnownZero.trunc(SrcBitWidth);
733     KnownOne.trunc(SrcBitWidth);
734     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
735     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
736     // The top bits are known to be zero.
737     KnownZero.zext(BitWidth);
738     KnownOne.zext(BitWidth);
739     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
740     return;
741   }
742   case Instruction::SExt: {
743     // Compute the bits in the result that are not present in the input.
744     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
745     uint32_t SrcBitWidth = SrcTy->getBitWidth();
746       
747     APInt MaskIn(Mask); 
748     MaskIn.trunc(SrcBitWidth);
749     KnownZero.trunc(SrcBitWidth);
750     KnownOne.trunc(SrcBitWidth);
751     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
752     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
753     KnownZero.zext(BitWidth);
754     KnownOne.zext(BitWidth);
755
756     // If the sign bit of the input is known set or clear, then we know the
757     // top bits of the result.
758     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
759       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
760     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
761       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
762     return;
763   }
764   case Instruction::Shl:
765     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
766     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
767       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
768       APInt Mask2(Mask.lshr(ShiftAmt));
769       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
770       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
771       KnownZero <<= ShiftAmt;
772       KnownOne  <<= ShiftAmt;
773       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
774       return;
775     }
776     break;
777   case Instruction::LShr:
778     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
779     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
780       // Compute the new bits that are at the top now.
781       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
782       
783       // Unsigned shift right.
784       APInt Mask2(Mask.shl(ShiftAmt));
785       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
786       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
787       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
788       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
789       // high bits known zero.
790       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
791       return;
792     }
793     break;
794   case Instruction::AShr:
795     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
796     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
797       // Compute the new bits that are at the top now.
798       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
799       
800       // Signed shift right.
801       APInt Mask2(Mask.shl(ShiftAmt));
802       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
803       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
804       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
805       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
806         
807       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
808       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
809         KnownZero |= HighBits;
810       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
811         KnownOne |= HighBits;
812       return;
813     }
814     break;
815   }
816 }
817
818 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
819 /// this predicate to simplify operations downstream.  Mask is known to be zero
820 /// for bits that V cannot have.
821 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
822   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
823   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
824   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
825   return (KnownZero & Mask) == Mask;
826 }
827
828 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
829 /// specified instruction is a constant integer.  If so, check to see if there
830 /// are any bits set in the constant that are not demanded.  If so, shrink the
831 /// constant and return true.
832 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
833                                    APInt Demanded) {
834   assert(I && "No instruction?");
835   assert(OpNo < I->getNumOperands() && "Operand index too large");
836
837   // If the operand is not a constant integer, nothing to do.
838   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
839   if (!OpC) return false;
840
841   // If there are no bits set that aren't demanded, nothing to do.
842   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
843   if ((~Demanded & OpC->getValue()) == 0)
844     return false;
845
846   // This instruction is producing bits that are not demanded. Shrink the RHS.
847   Demanded &= OpC->getValue();
848   I->setOperand(OpNo, ConstantInt::get(Demanded));
849   return true;
850 }
851
852 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
853 // set of known zero and one bits, compute the maximum and minimum values that
854 // could have the specified known zero and known one bits, returning them in
855 // min/max.
856 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
857                                                    const APInt& KnownZero,
858                                                    const APInt& KnownOne,
859                                                    APInt& Min, APInt& Max) {
860   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
861   assert(KnownZero.getBitWidth() == BitWidth && 
862          KnownOne.getBitWidth() == BitWidth &&
863          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
864          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
865   APInt UnknownBits = ~(KnownZero|KnownOne);
866
867   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
868   // bit if it is unknown.
869   Min = KnownOne;
870   Max = KnownOne|UnknownBits;
871   
872   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
873     Min.set(BitWidth-1);
874     Max.clear(BitWidth-1);
875   }
876 }
877
878 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
879 // a set of known zero and one bits, compute the maximum and minimum values that
880 // could have the specified known zero and known one bits, returning them in
881 // min/max.
882 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
883                                                      const APInt &KnownZero,
884                                                      const APInt &KnownOne,
885                                                      APInt &Min, APInt &Max) {
886   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
887   assert(KnownZero.getBitWidth() == BitWidth && 
888          KnownOne.getBitWidth() == BitWidth &&
889          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
890          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
891   APInt UnknownBits = ~(KnownZero|KnownOne);
892   
893   // The minimum value is when the unknown bits are all zeros.
894   Min = KnownOne;
895   // The maximum value is when the unknown bits are all ones.
896   Max = KnownOne|UnknownBits;
897 }
898
899 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
900 /// value based on the demanded bits. When this function is called, it is known
901 /// that only the bits set in DemandedMask of the result of V are ever used
902 /// downstream. Consequently, depending on the mask and V, it may be possible
903 /// to replace V with a constant or one of its operands. In such cases, this
904 /// function does the replacement and returns true. In all other cases, it
905 /// returns false after analyzing the expression and setting KnownOne and known
906 /// to be one in the expression. KnownZero contains all the bits that are known
907 /// to be zero in the expression. These are provided to potentially allow the
908 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
909 /// the expression. KnownOne and KnownZero always follow the invariant that 
910 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
911 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
912 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
913 /// and KnownOne must all be the same.
914 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
915                                         APInt& KnownZero, APInt& KnownOne,
916                                         unsigned Depth) {
917   assert(V != 0 && "Null pointer of Value???");
918   assert(Depth <= 6 && "Limit Search Depth");
919   uint32_t BitWidth = DemandedMask.getBitWidth();
920   const IntegerType *VTy = cast<IntegerType>(V->getType());
921   assert(VTy->getBitWidth() == BitWidth && 
922          KnownZero.getBitWidth() == BitWidth && 
923          KnownOne.getBitWidth() == BitWidth &&
924          "Value *V, DemandedMask, KnownZero and KnownOne \
925           must have same BitWidth");
926   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
927     // We know all of the bits for a constant!
928     KnownOne = CI->getValue() & DemandedMask;
929     KnownZero = ~KnownOne & DemandedMask;
930     return false;
931   }
932   
933   KnownZero.clear(); 
934   KnownOne.clear();
935   if (!V->hasOneUse()) {    // Other users may use these bits.
936     if (Depth != 0) {       // Not at the root.
937       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
938       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
939       return false;
940     }
941     // If this is the root being simplified, allow it to have multiple uses,
942     // just set the DemandedMask to all bits.
943     DemandedMask = APInt::getAllOnesValue(BitWidth);
944   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
945     if (V != UndefValue::get(VTy))
946       return UpdateValueUsesWith(V, UndefValue::get(VTy));
947     return false;
948   } else if (Depth == 6) {        // Limit search depth.
949     return false;
950   }
951   
952   Instruction *I = dyn_cast<Instruction>(V);
953   if (!I) return false;        // Only analyze instructions.
954
955   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
956   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
957   switch (I->getOpcode()) {
958   default: break;
959   case Instruction::And:
960     // If either the LHS or the RHS are Zero, the result is zero.
961     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962                              RHSKnownZero, RHSKnownOne, Depth+1))
963       return true;
964     assert((RHSKnownZero & RHSKnownOne) == 0 && 
965            "Bits known to be one AND zero?"); 
966
967     // If something is known zero on the RHS, the bits aren't demanded on the
968     // LHS.
969     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
970                              LHSKnownZero, LHSKnownOne, Depth+1))
971       return true;
972     assert((LHSKnownZero & LHSKnownOne) == 0 && 
973            "Bits known to be one AND zero?"); 
974
975     // If all of the demanded bits are known 1 on one side, return the other.
976     // These bits cannot contribute to the result of the 'and'.
977     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
978         (DemandedMask & ~LHSKnownZero))
979       return UpdateValueUsesWith(I, I->getOperand(0));
980     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
981         (DemandedMask & ~RHSKnownZero))
982       return UpdateValueUsesWith(I, I->getOperand(1));
983     
984     // If all of the demanded bits in the inputs are known zeros, return zero.
985     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
986       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
987       
988     // If the RHS is a constant, see if we can simplify it.
989     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
990       return UpdateValueUsesWith(I, I);
991       
992     // Output known-1 bits are only known if set in both the LHS & RHS.
993     RHSKnownOne &= LHSKnownOne;
994     // Output known-0 are known to be clear if zero in either the LHS | RHS.
995     RHSKnownZero |= LHSKnownZero;
996     break;
997   case Instruction::Or:
998     // If either the LHS or the RHS are One, the result is One.
999     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1000                              RHSKnownZero, RHSKnownOne, Depth+1))
1001       return true;
1002     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1003            "Bits known to be one AND zero?"); 
1004     // If something is known one on the RHS, the bits aren't demanded on the
1005     // LHS.
1006     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1007                              LHSKnownZero, LHSKnownOne, Depth+1))
1008       return true;
1009     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1010            "Bits known to be one AND zero?"); 
1011     
1012     // If all of the demanded bits are known zero on one side, return the other.
1013     // These bits cannot contribute to the result of the 'or'.
1014     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1015         (DemandedMask & ~LHSKnownOne))
1016       return UpdateValueUsesWith(I, I->getOperand(0));
1017     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1018         (DemandedMask & ~RHSKnownOne))
1019       return UpdateValueUsesWith(I, I->getOperand(1));
1020
1021     // If all of the potentially set bits on one side are known to be set on
1022     // the other side, just use the 'other' side.
1023     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1024         (DemandedMask & (~RHSKnownZero)))
1025       return UpdateValueUsesWith(I, I->getOperand(0));
1026     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1027         (DemandedMask & (~LHSKnownZero)))
1028       return UpdateValueUsesWith(I, I->getOperand(1));
1029         
1030     // If the RHS is a constant, see if we can simplify it.
1031     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1032       return UpdateValueUsesWith(I, I);
1033           
1034     // Output known-0 bits are only known if clear in both the LHS & RHS.
1035     RHSKnownZero &= LHSKnownZero;
1036     // Output known-1 are known to be set if set in either the LHS | RHS.
1037     RHSKnownOne |= LHSKnownOne;
1038     break;
1039   case Instruction::Xor: {
1040     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1041                              RHSKnownZero, RHSKnownOne, Depth+1))
1042       return true;
1043     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1044            "Bits known to be one AND zero?"); 
1045     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1046                              LHSKnownZero, LHSKnownOne, Depth+1))
1047       return true;
1048     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1049            "Bits known to be one AND zero?"); 
1050     
1051     // If all of the demanded bits are known zero on one side, return the other.
1052     // These bits cannot contribute to the result of the 'xor'.
1053     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1054       return UpdateValueUsesWith(I, I->getOperand(0));
1055     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1056       return UpdateValueUsesWith(I, I->getOperand(1));
1057     
1058     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1059     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1060                          (RHSKnownOne & LHSKnownOne);
1061     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1062     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1063                         (RHSKnownOne & LHSKnownZero);
1064     
1065     // If all of the demanded bits are known to be zero on one side or the
1066     // other, turn this into an *inclusive* or.
1067     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1068     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1069       Instruction *Or =
1070         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1071                                  I->getName());
1072       InsertNewInstBefore(Or, *I);
1073       return UpdateValueUsesWith(I, Or);
1074     }
1075     
1076     // If all of the demanded bits on one side are known, and all of the set
1077     // bits on that side are also known to be set on the other side, turn this
1078     // into an AND, as we know the bits will be cleared.
1079     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1080     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1081       // all known
1082       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1083         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1084         Instruction *And = 
1085           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1086         InsertNewInstBefore(And, *I);
1087         return UpdateValueUsesWith(I, And);
1088       }
1089     }
1090     
1091     // If the RHS is a constant, see if we can simplify it.
1092     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1093     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1094       return UpdateValueUsesWith(I, I);
1095     
1096     RHSKnownZero = KnownZeroOut;
1097     RHSKnownOne  = KnownOneOut;
1098     break;
1099   }
1100   case Instruction::Select:
1101     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1102                              RHSKnownZero, RHSKnownOne, Depth+1))
1103       return true;
1104     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1105                              LHSKnownZero, LHSKnownOne, Depth+1))
1106       return true;
1107     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1108            "Bits known to be one AND zero?"); 
1109     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1110            "Bits known to be one AND zero?"); 
1111     
1112     // If the operands are constants, see if we can simplify them.
1113     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1114       return UpdateValueUsesWith(I, I);
1115     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1116       return UpdateValueUsesWith(I, I);
1117     
1118     // Only known if known in both the LHS and RHS.
1119     RHSKnownOne &= LHSKnownOne;
1120     RHSKnownZero &= LHSKnownZero;
1121     break;
1122   case Instruction::Trunc: {
1123     uint32_t truncBf = 
1124       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1125     DemandedMask.zext(truncBf);
1126     RHSKnownZero.zext(truncBf);
1127     RHSKnownOne.zext(truncBf);
1128     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1129                              RHSKnownZero, RHSKnownOne, Depth+1))
1130       return true;
1131     DemandedMask.trunc(BitWidth);
1132     RHSKnownZero.trunc(BitWidth);
1133     RHSKnownOne.trunc(BitWidth);
1134     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1135            "Bits known to be one AND zero?"); 
1136     break;
1137   }
1138   case Instruction::BitCast:
1139     if (!I->getOperand(0)->getType()->isInteger())
1140       return false;
1141       
1142     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1143                              RHSKnownZero, RHSKnownOne, Depth+1))
1144       return true;
1145     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1146            "Bits known to be one AND zero?"); 
1147     break;
1148   case Instruction::ZExt: {
1149     // Compute the bits in the result that are not present in the input.
1150     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1151     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1152     
1153     DemandedMask.trunc(SrcBitWidth);
1154     RHSKnownZero.trunc(SrcBitWidth);
1155     RHSKnownOne.trunc(SrcBitWidth);
1156     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1157                              RHSKnownZero, RHSKnownOne, Depth+1))
1158       return true;
1159     DemandedMask.zext(BitWidth);
1160     RHSKnownZero.zext(BitWidth);
1161     RHSKnownOne.zext(BitWidth);
1162     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1163            "Bits known to be one AND zero?"); 
1164     // The top bits are known to be zero.
1165     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1166     break;
1167   }
1168   case Instruction::SExt: {
1169     // Compute the bits in the result that are not present in the input.
1170     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1171     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1172     
1173     APInt InputDemandedBits = DemandedMask & 
1174                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1175
1176     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1177     // If any of the sign extended bits are demanded, we know that the sign
1178     // bit is demanded.
1179     if ((NewBits & DemandedMask) != 0)
1180       InputDemandedBits.set(SrcBitWidth-1);
1181       
1182     InputDemandedBits.trunc(SrcBitWidth);
1183     RHSKnownZero.trunc(SrcBitWidth);
1184     RHSKnownOne.trunc(SrcBitWidth);
1185     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1186                              RHSKnownZero, RHSKnownOne, Depth+1))
1187       return true;
1188     InputDemandedBits.zext(BitWidth);
1189     RHSKnownZero.zext(BitWidth);
1190     RHSKnownOne.zext(BitWidth);
1191     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1192            "Bits known to be one AND zero?"); 
1193       
1194     // If the sign bit of the input is known set or clear, then we know the
1195     // top bits of the result.
1196
1197     // If the input sign bit is known zero, or if the NewBits are not demanded
1198     // convert this into a zero extension.
1199     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1200     {
1201       // Convert to ZExt cast
1202       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1203       return UpdateValueUsesWith(I, NewCast);
1204     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1205       RHSKnownOne |= NewBits;
1206     }
1207     break;
1208   }
1209   case Instruction::Add: {
1210     // Figure out what the input bits are.  If the top bits of the and result
1211     // are not demanded, then the add doesn't demand them from its input
1212     // either.
1213     uint32_t NLZ = DemandedMask.countLeadingZeros();
1214       
1215     // If there is a constant on the RHS, there are a variety of xformations
1216     // we can do.
1217     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218       // If null, this should be simplified elsewhere.  Some of the xforms here
1219       // won't work if the RHS is zero.
1220       if (RHS->isZero())
1221         break;
1222       
1223       // If the top bit of the output is demanded, demand everything from the
1224       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1225       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1226
1227       // Find information about known zero/one bits in the input.
1228       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1229                                LHSKnownZero, LHSKnownOne, Depth+1))
1230         return true;
1231
1232       // If the RHS of the add has bits set that can't affect the input, reduce
1233       // the constant.
1234       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1235         return UpdateValueUsesWith(I, I);
1236       
1237       // Avoid excess work.
1238       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1239         break;
1240       
1241       // Turn it into OR if input bits are zero.
1242       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1243         Instruction *Or =
1244           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1245                                    I->getName());
1246         InsertNewInstBefore(Or, *I);
1247         return UpdateValueUsesWith(I, Or);
1248       }
1249       
1250       // We can say something about the output known-zero and known-one bits,
1251       // depending on potential carries from the input constant and the
1252       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1253       // bits set and the RHS constant is 0x01001, then we know we have a known
1254       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1255       
1256       // To compute this, we first compute the potential carry bits.  These are
1257       // the bits which may be modified.  I'm not aware of a better way to do
1258       // this scan.
1259       const APInt& RHSVal = RHS->getValue();
1260       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1261       
1262       // Now that we know which bits have carries, compute the known-1/0 sets.
1263       
1264       // Bits are known one if they are known zero in one operand and one in the
1265       // other, and there is no input carry.
1266       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1267                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1268       
1269       // Bits are known zero if they are known zero in both operands and there
1270       // is no input carry.
1271       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1272     } else {
1273       // If the high-bits of this ADD are not demanded, then it does not demand
1274       // the high bits of its LHS or RHS.
1275       if (DemandedMask[BitWidth-1] == 0) {
1276         // Right fill the mask of bits for this ADD to demand the most
1277         // significant bit and all those below it.
1278         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1279         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1280                                  LHSKnownZero, LHSKnownOne, Depth+1))
1281           return true;
1282         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1283                                  LHSKnownZero, LHSKnownOne, Depth+1))
1284           return true;
1285       }
1286     }
1287     break;
1288   }
1289   case Instruction::Sub:
1290     // If the high-bits of this SUB are not demanded, then it does not demand
1291     // the high bits of its LHS or RHS.
1292     if (DemandedMask[BitWidth-1] == 0) {
1293       // Right fill the mask of bits for this SUB to demand the most
1294       // significant bit and all those below it.
1295       uint32_t NLZ = DemandedMask.countLeadingZeros();
1296       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1297       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1298                                LHSKnownZero, LHSKnownOne, Depth+1))
1299         return true;
1300       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1301                                LHSKnownZero, LHSKnownOne, Depth+1))
1302         return true;
1303     }
1304     break;
1305   case Instruction::Shl:
1306     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1307       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1308       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1309       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1310                                RHSKnownZero, RHSKnownOne, Depth+1))
1311         return true;
1312       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1313              "Bits known to be one AND zero?"); 
1314       RHSKnownZero <<= ShiftAmt;
1315       RHSKnownOne  <<= ShiftAmt;
1316       // low bits known zero.
1317       if (ShiftAmt)
1318         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1319     }
1320     break;
1321   case Instruction::LShr:
1322     // For a logical shift right
1323     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1324       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1325       
1326       // Unsigned shift right.
1327       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1328       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1329                                RHSKnownZero, RHSKnownOne, Depth+1))
1330         return true;
1331       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1332              "Bits known to be one AND zero?"); 
1333       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1334       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1335       if (ShiftAmt) {
1336         // Compute the new bits that are at the top now.
1337         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1338         RHSKnownZero |= HighBits;  // high bits known zero.
1339       }
1340     }
1341     break;
1342   case Instruction::AShr:
1343     // If this is an arithmetic shift right and only the low-bit is set, we can
1344     // always convert this into a logical shr, even if the shift amount is
1345     // variable.  The low bit of the shift cannot be an input sign bit unless
1346     // the shift amount is >= the size of the datatype, which is undefined.
1347     if (DemandedMask == 1) {
1348       // Perform the logical shift right.
1349       Value *NewVal = BinaryOperator::createLShr(
1350                         I->getOperand(0), I->getOperand(1), I->getName());
1351       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1352       return UpdateValueUsesWith(I, NewVal);
1353     }    
1354
1355     // If the sign bit is the only bit demanded by this ashr, then there is no
1356     // need to do it, the shift doesn't change the high bit.
1357     if (DemandedMask.isSignBit())
1358       return UpdateValueUsesWith(I, I->getOperand(0));
1359     
1360     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1361       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1362       
1363       // Signed shift right.
1364       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1365       // If any of the "high bits" are demanded, we should set the sign bit as
1366       // demanded.
1367       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1368         DemandedMaskIn.set(BitWidth-1);
1369       if (SimplifyDemandedBits(I->getOperand(0),
1370                                DemandedMaskIn,
1371                                RHSKnownZero, RHSKnownOne, Depth+1))
1372         return true;
1373       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1374              "Bits known to be one AND zero?"); 
1375       // Compute the new bits that are at the top now.
1376       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1377       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1378       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1379         
1380       // Handle the sign bits.
1381       APInt SignBit(APInt::getSignBit(BitWidth));
1382       // Adjust to where it is now in the mask.
1383       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1384         
1385       // If the input sign bit is known to be zero, or if none of the top bits
1386       // are demanded, turn this into an unsigned shift right.
1387       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1388           (HighBits & ~DemandedMask) == HighBits) {
1389         // Perform the logical shift right.
1390         Value *NewVal = BinaryOperator::createLShr(
1391                           I->getOperand(0), SA, I->getName());
1392         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1393         return UpdateValueUsesWith(I, NewVal);
1394       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1395         RHSKnownOne |= HighBits;
1396       }
1397     }
1398     break;
1399   }
1400   
1401   // If the client is only demanding bits that we know, return the known
1402   // constant.
1403   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1404     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1405   return false;
1406 }
1407
1408
1409 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1410 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1411 /// actually used by the caller.  This method analyzes which elements of the
1412 /// operand are undef and returns that information in UndefElts.
1413 ///
1414 /// If the information about demanded elements can be used to simplify the
1415 /// operation, the operation is simplified, then the resultant value is
1416 /// returned.  This returns null if no change was made.
1417 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1418                                                 uint64_t &UndefElts,
1419                                                 unsigned Depth) {
1420   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1421   assert(VWidth <= 64 && "Vector too wide to analyze!");
1422   uint64_t EltMask = ~0ULL >> (64-VWidth);
1423   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1424          "Invalid DemandedElts!");
1425
1426   if (isa<UndefValue>(V)) {
1427     // If the entire vector is undefined, just return this info.
1428     UndefElts = EltMask;
1429     return 0;
1430   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1431     UndefElts = EltMask;
1432     return UndefValue::get(V->getType());
1433   }
1434   
1435   UndefElts = 0;
1436   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1437     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1438     Constant *Undef = UndefValue::get(EltTy);
1439
1440     std::vector<Constant*> Elts;
1441     for (unsigned i = 0; i != VWidth; ++i)
1442       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1443         Elts.push_back(Undef);
1444         UndefElts |= (1ULL << i);
1445       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1446         Elts.push_back(Undef);
1447         UndefElts |= (1ULL << i);
1448       } else {                               // Otherwise, defined.
1449         Elts.push_back(CP->getOperand(i));
1450       }
1451         
1452     // If we changed the constant, return it.
1453     Constant *NewCP = ConstantVector::get(Elts);
1454     return NewCP != CP ? NewCP : 0;
1455   } else if (isa<ConstantAggregateZero>(V)) {
1456     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1457     // set to undef.
1458     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1459     Constant *Zero = Constant::getNullValue(EltTy);
1460     Constant *Undef = UndefValue::get(EltTy);
1461     std::vector<Constant*> Elts;
1462     for (unsigned i = 0; i != VWidth; ++i)
1463       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1464     UndefElts = DemandedElts ^ EltMask;
1465     return ConstantVector::get(Elts);
1466   }
1467   
1468   if (!V->hasOneUse()) {    // Other users may use these bits.
1469     if (Depth != 0) {       // Not at the root.
1470       // TODO: Just compute the UndefElts information recursively.
1471       return false;
1472     }
1473     return false;
1474   } else if (Depth == 10) {        // Limit search depth.
1475     return false;
1476   }
1477   
1478   Instruction *I = dyn_cast<Instruction>(V);
1479   if (!I) return false;        // Only analyze instructions.
1480   
1481   bool MadeChange = false;
1482   uint64_t UndefElts2;
1483   Value *TmpV;
1484   switch (I->getOpcode()) {
1485   default: break;
1486     
1487   case Instruction::InsertElement: {
1488     // If this is a variable index, we don't know which element it overwrites.
1489     // demand exactly the same input as we produce.
1490     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1491     if (Idx == 0) {
1492       // Note that we can't propagate undef elt info, because we don't know
1493       // which elt is getting updated.
1494       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1495                                         UndefElts2, Depth+1);
1496       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1497       break;
1498     }
1499     
1500     // If this is inserting an element that isn't demanded, remove this
1501     // insertelement.
1502     unsigned IdxNo = Idx->getZExtValue();
1503     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1504       return AddSoonDeadInstToWorklist(*I, 0);
1505     
1506     // Otherwise, the element inserted overwrites whatever was there, so the
1507     // input demanded set is simpler than the output set.
1508     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1509                                       DemandedElts & ~(1ULL << IdxNo),
1510                                       UndefElts, Depth+1);
1511     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1512
1513     // The inserted element is defined.
1514     UndefElts |= 1ULL << IdxNo;
1515     break;
1516   }
1517   case Instruction::BitCast: {
1518     // Vector->vector casts only.
1519     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1520     if (!VTy) break;
1521     unsigned InVWidth = VTy->getNumElements();
1522     uint64_t InputDemandedElts = 0;
1523     unsigned Ratio;
1524
1525     if (VWidth == InVWidth) {
1526       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1527       // elements as are demanded of us.
1528       Ratio = 1;
1529       InputDemandedElts = DemandedElts;
1530     } else if (VWidth > InVWidth) {
1531       // Untested so far.
1532       break;
1533       
1534       // If there are more elements in the result than there are in the source,
1535       // then an input element is live if any of the corresponding output
1536       // elements are live.
1537       Ratio = VWidth/InVWidth;
1538       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1539         if (DemandedElts & (1ULL << OutIdx))
1540           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1541       }
1542     } else {
1543       // Untested so far.
1544       break;
1545       
1546       // If there are more elements in the source than there are in the result,
1547       // then an input element is live if the corresponding output element is
1548       // live.
1549       Ratio = InVWidth/VWidth;
1550       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1551         if (DemandedElts & (1ULL << InIdx/Ratio))
1552           InputDemandedElts |= 1ULL << InIdx;
1553     }
1554     
1555     // div/rem demand all inputs, because they don't want divide by zero.
1556     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1557                                       UndefElts2, Depth+1);
1558     if (TmpV) {
1559       I->setOperand(0, TmpV);
1560       MadeChange = true;
1561     }
1562     
1563     UndefElts = UndefElts2;
1564     if (VWidth > InVWidth) {
1565       assert(0 && "Unimp");
1566       // If there are more elements in the result than there are in the source,
1567       // then an output element is undef if the corresponding input element is
1568       // undef.
1569       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1570         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1571           UndefElts |= 1ULL << OutIdx;
1572     } else if (VWidth < InVWidth) {
1573       assert(0 && "Unimp");
1574       // If there are more elements in the source than there are in the result,
1575       // then a result element is undef if all of the corresponding input
1576       // elements are undef.
1577       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1578       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1579         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1580           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1581     }
1582     break;
1583   }
1584   case Instruction::And:
1585   case Instruction::Or:
1586   case Instruction::Xor:
1587   case Instruction::Add:
1588   case Instruction::Sub:
1589   case Instruction::Mul:
1590     // div/rem demand all inputs, because they don't want divide by zero.
1591     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1592                                       UndefElts, Depth+1);
1593     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1594     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1595                                       UndefElts2, Depth+1);
1596     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1597       
1598     // Output elements are undefined if both are undefined.  Consider things
1599     // like undef&0.  The result is known zero, not undef.
1600     UndefElts &= UndefElts2;
1601     break;
1602     
1603   case Instruction::Call: {
1604     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1605     if (!II) break;
1606     switch (II->getIntrinsicID()) {
1607     default: break;
1608       
1609     // Binary vector operations that work column-wise.  A dest element is a
1610     // function of the corresponding input elements from the two inputs.
1611     case Intrinsic::x86_sse_sub_ss:
1612     case Intrinsic::x86_sse_mul_ss:
1613     case Intrinsic::x86_sse_min_ss:
1614     case Intrinsic::x86_sse_max_ss:
1615     case Intrinsic::x86_sse2_sub_sd:
1616     case Intrinsic::x86_sse2_mul_sd:
1617     case Intrinsic::x86_sse2_min_sd:
1618     case Intrinsic::x86_sse2_max_sd:
1619       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1620                                         UndefElts, Depth+1);
1621       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1622       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1623                                         UndefElts2, Depth+1);
1624       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1625
1626       // If only the low elt is demanded and this is a scalarizable intrinsic,
1627       // scalarize it now.
1628       if (DemandedElts == 1) {
1629         switch (II->getIntrinsicID()) {
1630         default: break;
1631         case Intrinsic::x86_sse_sub_ss:
1632         case Intrinsic::x86_sse_mul_ss:
1633         case Intrinsic::x86_sse2_sub_sd:
1634         case Intrinsic::x86_sse2_mul_sd:
1635           // TODO: Lower MIN/MAX/ABS/etc
1636           Value *LHS = II->getOperand(1);
1637           Value *RHS = II->getOperand(2);
1638           // Extract the element as scalars.
1639           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1640           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1641           
1642           switch (II->getIntrinsicID()) {
1643           default: assert(0 && "Case stmts out of sync!");
1644           case Intrinsic::x86_sse_sub_ss:
1645           case Intrinsic::x86_sse2_sub_sd:
1646             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1647                                                         II->getName()), *II);
1648             break;
1649           case Intrinsic::x86_sse_mul_ss:
1650           case Intrinsic::x86_sse2_mul_sd:
1651             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1652                                                          II->getName()), *II);
1653             break;
1654           }
1655           
1656           Instruction *New =
1657             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1658                                   II->getName());
1659           InsertNewInstBefore(New, *II);
1660           AddSoonDeadInstToWorklist(*II, 0);
1661           return New;
1662         }            
1663       }
1664         
1665       // Output elements are undefined if both are undefined.  Consider things
1666       // like undef&0.  The result is known zero, not undef.
1667       UndefElts &= UndefElts2;
1668       break;
1669     }
1670     break;
1671   }
1672   }
1673   return MadeChange ? I : 0;
1674 }
1675
1676 /// @returns true if the specified compare predicate is
1677 /// true when both operands are equal...
1678 /// @brief Determine if the icmp Predicate is true when both operands are equal
1679 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1680   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1681          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1682          pred == ICmpInst::ICMP_SLE;
1683 }
1684
1685 /// @returns true if the specified compare instruction is
1686 /// true when both operands are equal...
1687 /// @brief Determine if the ICmpInst returns true when both operands are equal
1688 static bool isTrueWhenEqual(ICmpInst &ICI) {
1689   return isTrueWhenEqual(ICI.getPredicate());
1690 }
1691
1692 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1693 /// function is designed to check a chain of associative operators for a
1694 /// potential to apply a certain optimization.  Since the optimization may be
1695 /// applicable if the expression was reassociated, this checks the chain, then
1696 /// reassociates the expression as necessary to expose the optimization
1697 /// opportunity.  This makes use of a special Functor, which must define
1698 /// 'shouldApply' and 'apply' methods.
1699 ///
1700 template<typename Functor>
1701 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1702   unsigned Opcode = Root.getOpcode();
1703   Value *LHS = Root.getOperand(0);
1704
1705   // Quick check, see if the immediate LHS matches...
1706   if (F.shouldApply(LHS))
1707     return F.apply(Root);
1708
1709   // Otherwise, if the LHS is not of the same opcode as the root, return.
1710   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1711   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1712     // Should we apply this transform to the RHS?
1713     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1714
1715     // If not to the RHS, check to see if we should apply to the LHS...
1716     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1717       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1718       ShouldApply = true;
1719     }
1720
1721     // If the functor wants to apply the optimization to the RHS of LHSI,
1722     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1723     if (ShouldApply) {
1724       BasicBlock *BB = Root.getParent();
1725
1726       // Now all of the instructions are in the current basic block, go ahead
1727       // and perform the reassociation.
1728       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1729
1730       // First move the selected RHS to the LHS of the root...
1731       Root.setOperand(0, LHSI->getOperand(1));
1732
1733       // Make what used to be the LHS of the root be the user of the root...
1734       Value *ExtraOperand = TmpLHSI->getOperand(1);
1735       if (&Root == TmpLHSI) {
1736         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1737         return 0;
1738       }
1739       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1740       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1741       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1742       BasicBlock::iterator ARI = &Root; ++ARI;
1743       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1744       ARI = Root;
1745
1746       // Now propagate the ExtraOperand down the chain of instructions until we
1747       // get to LHSI.
1748       while (TmpLHSI != LHSI) {
1749         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1750         // Move the instruction to immediately before the chain we are
1751         // constructing to avoid breaking dominance properties.
1752         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1753         BB->getInstList().insert(ARI, NextLHSI);
1754         ARI = NextLHSI;
1755
1756         Value *NextOp = NextLHSI->getOperand(1);
1757         NextLHSI->setOperand(1, ExtraOperand);
1758         TmpLHSI = NextLHSI;
1759         ExtraOperand = NextOp;
1760       }
1761
1762       // Now that the instructions are reassociated, have the functor perform
1763       // the transformation...
1764       return F.apply(Root);
1765     }
1766
1767     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1768   }
1769   return 0;
1770 }
1771
1772
1773 // AddRHS - Implements: X + X --> X << 1
1774 struct AddRHS {
1775   Value *RHS;
1776   AddRHS(Value *rhs) : RHS(rhs) {}
1777   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1778   Instruction *apply(BinaryOperator &Add) const {
1779     return BinaryOperator::createShl(Add.getOperand(0),
1780                                   ConstantInt::get(Add.getType(), 1));
1781   }
1782 };
1783
1784 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1785 //                 iff C1&C2 == 0
1786 struct AddMaskingAnd {
1787   Constant *C2;
1788   AddMaskingAnd(Constant *c) : C2(c) {}
1789   bool shouldApply(Value *LHS) const {
1790     ConstantInt *C1;
1791     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1792            ConstantExpr::getAnd(C1, C2)->isNullValue();
1793   }
1794   Instruction *apply(BinaryOperator &Add) const {
1795     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1796   }
1797 };
1798
1799 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1800                                              InstCombiner *IC) {
1801   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1802     if (Constant *SOC = dyn_cast<Constant>(SO))
1803       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1804
1805     return IC->InsertNewInstBefore(CastInst::create(
1806           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1807   }
1808
1809   // Figure out if the constant is the left or the right argument.
1810   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1811   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1812
1813   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1814     if (ConstIsRHS)
1815       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1816     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1817   }
1818
1819   Value *Op0 = SO, *Op1 = ConstOperand;
1820   if (!ConstIsRHS)
1821     std::swap(Op0, Op1);
1822   Instruction *New;
1823   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1824     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1825   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1826     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1827                           SO->getName()+".cmp");
1828   else {
1829     assert(0 && "Unknown binary instruction type!");
1830     abort();
1831   }
1832   return IC->InsertNewInstBefore(New, I);
1833 }
1834
1835 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1836 // constant as the other operand, try to fold the binary operator into the
1837 // select arguments.  This also works for Cast instructions, which obviously do
1838 // not have a second operand.
1839 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1840                                      InstCombiner *IC) {
1841   // Don't modify shared select instructions
1842   if (!SI->hasOneUse()) return 0;
1843   Value *TV = SI->getOperand(1);
1844   Value *FV = SI->getOperand(2);
1845
1846   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1847     // Bool selects with constant operands can be folded to logical ops.
1848     if (SI->getType() == Type::Int1Ty) return 0;
1849
1850     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1851     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1852
1853     return new SelectInst(SI->getCondition(), SelectTrueVal,
1854                           SelectFalseVal);
1855   }
1856   return 0;
1857 }
1858
1859
1860 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1861 /// node as operand #0, see if we can fold the instruction into the PHI (which
1862 /// is only possible if all operands to the PHI are constants).
1863 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1864   PHINode *PN = cast<PHINode>(I.getOperand(0));
1865   unsigned NumPHIValues = PN->getNumIncomingValues();
1866   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1867
1868   // Check to see if all of the operands of the PHI are constants.  If there is
1869   // one non-constant value, remember the BB it is.  If there is more than one
1870   // or if *it* is a PHI, bail out.
1871   BasicBlock *NonConstBB = 0;
1872   for (unsigned i = 0; i != NumPHIValues; ++i)
1873     if (!isa<Constant>(PN->getIncomingValue(i))) {
1874       if (NonConstBB) return 0;  // More than one non-const value.
1875       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1876       NonConstBB = PN->getIncomingBlock(i);
1877       
1878       // If the incoming non-constant value is in I's block, we have an infinite
1879       // loop.
1880       if (NonConstBB == I.getParent())
1881         return 0;
1882     }
1883   
1884   // If there is exactly one non-constant value, we can insert a copy of the
1885   // operation in that block.  However, if this is a critical edge, we would be
1886   // inserting the computation one some other paths (e.g. inside a loop).  Only
1887   // do this if the pred block is unconditionally branching into the phi block.
1888   if (NonConstBB) {
1889     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1890     if (!BI || !BI->isUnconditional()) return 0;
1891   }
1892
1893   // Okay, we can do the transformation: create the new PHI node.
1894   PHINode *NewPN = new PHINode(I.getType(), "");
1895   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1896   InsertNewInstBefore(NewPN, *PN);
1897   NewPN->takeName(PN);
1898
1899   // Next, add all of the operands to the PHI.
1900   if (I.getNumOperands() == 2) {
1901     Constant *C = cast<Constant>(I.getOperand(1));
1902     for (unsigned i = 0; i != NumPHIValues; ++i) {
1903       Value *InV = 0;
1904       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1905         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1906           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1907         else
1908           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1909       } else {
1910         assert(PN->getIncomingBlock(i) == NonConstBB);
1911         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1912           InV = BinaryOperator::create(BO->getOpcode(),
1913                                        PN->getIncomingValue(i), C, "phitmp",
1914                                        NonConstBB->getTerminator());
1915         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1916           InV = CmpInst::create(CI->getOpcode(), 
1917                                 CI->getPredicate(),
1918                                 PN->getIncomingValue(i), C, "phitmp",
1919                                 NonConstBB->getTerminator());
1920         else
1921           assert(0 && "Unknown binop!");
1922         
1923         AddToWorkList(cast<Instruction>(InV));
1924       }
1925       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1926     }
1927   } else { 
1928     CastInst *CI = cast<CastInst>(&I);
1929     const Type *RetTy = CI->getType();
1930     for (unsigned i = 0; i != NumPHIValues; ++i) {
1931       Value *InV;
1932       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1933         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1934       } else {
1935         assert(PN->getIncomingBlock(i) == NonConstBB);
1936         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1937                                I.getType(), "phitmp", 
1938                                NonConstBB->getTerminator());
1939         AddToWorkList(cast<Instruction>(InV));
1940       }
1941       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1942     }
1943   }
1944   return ReplaceInstUsesWith(I, NewPN);
1945 }
1946
1947
1948 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
1949 /// value is never equal to -0.0.
1950 ///
1951 /// Note that this function will need to be revisited when we support nondefault
1952 /// rounding modes!
1953 ///
1954 static bool CannotBeNegativeZero(const Value *V) {
1955   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1956     return !CFP->getValueAPF().isNegZero();
1957
1958   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1959   if (const Instruction *I = dyn_cast<Instruction>(V)) {
1960     if (I->getOpcode() == Instruction::Add &&
1961         isa<ConstantFP>(I->getOperand(1)) && 
1962         cast<ConstantFP>(I->getOperand(1))->isNullValue())
1963       return true;
1964     
1965     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1966       if (II->getIntrinsicID() == Intrinsic::sqrt)
1967         return CannotBeNegativeZero(II->getOperand(1));
1968     
1969     if (const CallInst *CI = dyn_cast<CallInst>(I))
1970       if (const Function *F = CI->getCalledFunction()) {
1971         if (F->isDeclaration()) {
1972           switch (F->getNameLen()) {
1973           case 3:  // abs(x) != -0.0
1974             if (!strcmp(F->getNameStart(), "abs")) return true;
1975             break;
1976           case 4:  // abs[lf](x) != -0.0
1977             if (!strcmp(F->getNameStart(), "absf")) return true;
1978             if (!strcmp(F->getNameStart(), "absl")) return true;
1979             break;
1980           }
1981         }
1982       }
1983   }
1984   
1985   return false;
1986 }
1987
1988
1989 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1990   bool Changed = SimplifyCommutative(I);
1991   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1992
1993   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1994     // X + undef -> undef
1995     if (isa<UndefValue>(RHS))
1996       return ReplaceInstUsesWith(I, RHS);
1997
1998     // X + 0 --> X
1999     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2000       if (RHSC->isNullValue())
2001         return ReplaceInstUsesWith(I, LHS);
2002     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2003       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2004                               (I.getType())->getValueAPF()))
2005         return ReplaceInstUsesWith(I, LHS);
2006     }
2007
2008     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2009       // X + (signbit) --> X ^ signbit
2010       const APInt& Val = CI->getValue();
2011       uint32_t BitWidth = Val.getBitWidth();
2012       if (Val == APInt::getSignBit(BitWidth))
2013         return BinaryOperator::createXor(LHS, RHS);
2014       
2015       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2016       // (X & 254)+1 -> (X&254)|1
2017       if (!isa<VectorType>(I.getType())) {
2018         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2019         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2020                                  KnownZero, KnownOne))
2021           return &I;
2022       }
2023     }
2024
2025     if (isa<PHINode>(LHS))
2026       if (Instruction *NV = FoldOpIntoPhi(I))
2027         return NV;
2028     
2029     ConstantInt *XorRHS = 0;
2030     Value *XorLHS = 0;
2031     if (isa<ConstantInt>(RHSC) &&
2032         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2033       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2034       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2035       
2036       uint32_t Size = TySizeBits / 2;
2037       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2038       APInt CFF80Val(-C0080Val);
2039       do {
2040         if (TySizeBits > Size) {
2041           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2042           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2043           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2044               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2045             // This is a sign extend if the top bits are known zero.
2046             if (!MaskedValueIsZero(XorLHS, 
2047                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2048               Size = 0;  // Not a sign ext, but can't be any others either.
2049             break;
2050           }
2051         }
2052         Size >>= 1;
2053         C0080Val = APIntOps::lshr(C0080Val, Size);
2054         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2055       } while (Size >= 1);
2056       
2057       // FIXME: This shouldn't be necessary. When the backends can handle types
2058       // with funny bit widths then this whole cascade of if statements should
2059       // be removed. It is just here to get the size of the "middle" type back
2060       // up to something that the back ends can handle.
2061       const Type *MiddleType = 0;
2062       switch (Size) {
2063         default: break;
2064         case 32: MiddleType = Type::Int32Ty; break;
2065         case 16: MiddleType = Type::Int16Ty; break;
2066         case  8: MiddleType = Type::Int8Ty; break;
2067       }
2068       if (MiddleType) {
2069         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2070         InsertNewInstBefore(NewTrunc, I);
2071         return new SExtInst(NewTrunc, I.getType(), I.getName());
2072       }
2073     }
2074   }
2075
2076   // X + X --> X << 1
2077   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2078     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2079
2080     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2081       if (RHSI->getOpcode() == Instruction::Sub)
2082         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2083           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2084     }
2085     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2086       if (LHSI->getOpcode() == Instruction::Sub)
2087         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2088           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2089     }
2090   }
2091
2092   // -A + B  -->  B - A
2093   // -A + -B  -->  -(A + B)
2094   if (Value *LHSV = dyn_castNegVal(LHS)) {
2095     if (LHS->getType()->isIntOrIntVector()) {
2096       if (Value *RHSV = dyn_castNegVal(RHS)) {
2097         Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2098         InsertNewInstBefore(NewAdd, I);
2099         return BinaryOperator::createNeg(NewAdd);
2100       }
2101     }
2102     
2103     return BinaryOperator::createSub(RHS, LHSV);
2104   }
2105
2106   // A + -B  -->  A - B
2107   if (!isa<Constant>(RHS))
2108     if (Value *V = dyn_castNegVal(RHS))
2109       return BinaryOperator::createSub(LHS, V);
2110
2111
2112   ConstantInt *C2;
2113   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2114     if (X == RHS)   // X*C + X --> X * (C+1)
2115       return BinaryOperator::createMul(RHS, AddOne(C2));
2116
2117     // X*C1 + X*C2 --> X * (C1+C2)
2118     ConstantInt *C1;
2119     if (X == dyn_castFoldableMul(RHS, C1))
2120       return BinaryOperator::createMul(X, Add(C1, C2));
2121   }
2122
2123   // X + X*C --> X * (C+1)
2124   if (dyn_castFoldableMul(RHS, C2) == LHS)
2125     return BinaryOperator::createMul(LHS, AddOne(C2));
2126
2127   // X + ~X --> -1   since   ~X = -X-1
2128   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2129     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2130   
2131
2132   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2133   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2134     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2135       return R;
2136
2137   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2138   if (I.getType()->isIntOrIntVector()) {
2139     Value *W, *X, *Y, *Z;
2140     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2141         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2142       if (W != Y) {
2143         if (W == Z) {
2144           std::swap(Y, Z);
2145         } else if (Y == X) {
2146           std::swap(W, X);
2147         } else if (X == Z) {
2148           std::swap(Y, Z);
2149           std::swap(W, X);
2150         }
2151       }
2152
2153       if (W == Y) {
2154         Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2155                                                             LHS->getName()), I);
2156         return BinaryOperator::createMul(W, NewAdd);
2157       }
2158     }
2159   }
2160
2161   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2162     Value *X = 0;
2163     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2164       return BinaryOperator::createSub(SubOne(CRHS), X);
2165
2166     // (X & FF00) + xx00  -> (X+xx00) & FF00
2167     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2168       Constant *Anded = And(CRHS, C2);
2169       if (Anded == CRHS) {
2170         // See if all bits from the first bit set in the Add RHS up are included
2171         // in the mask.  First, get the rightmost bit.
2172         const APInt& AddRHSV = CRHS->getValue();
2173
2174         // Form a mask of all bits from the lowest bit added through the top.
2175         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2176
2177         // See if the and mask includes all of these bits.
2178         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2179
2180         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2181           // Okay, the xform is safe.  Insert the new add pronto.
2182           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2183                                                             LHS->getName()), I);
2184           return BinaryOperator::createAnd(NewAdd, C2);
2185         }
2186       }
2187     }
2188
2189     // Try to fold constant add into select arguments.
2190     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2191       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2192         return R;
2193   }
2194
2195   // add (cast *A to intptrtype) B -> 
2196   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2197   {
2198     CastInst *CI = dyn_cast<CastInst>(LHS);
2199     Value *Other = RHS;
2200     if (!CI) {
2201       CI = dyn_cast<CastInst>(RHS);
2202       Other = LHS;
2203     }
2204     if (CI && CI->getType()->isSized() && 
2205         (CI->getType()->getPrimitiveSizeInBits() == 
2206          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2207         && isa<PointerType>(CI->getOperand(0)->getType())) {
2208       unsigned AS =
2209         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2210       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2211                                       PointerType::get(Type::Int8Ty, AS), I);
2212       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2213       return new PtrToIntInst(I2, CI->getType());
2214     }
2215   }
2216   
2217   // add (select X 0 (sub n A)) A  -->  select X A n
2218   {
2219     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2220     Value *Other = RHS;
2221     if (!SI) {
2222       SI = dyn_cast<SelectInst>(RHS);
2223       Other = LHS;
2224     }
2225     if (SI && SI->hasOneUse()) {
2226       Value *TV = SI->getTrueValue();
2227       Value *FV = SI->getFalseValue();
2228       Value *A, *N;
2229
2230       // Can we fold the add into the argument of the select?
2231       // We check both true and false select arguments for a matching subtract.
2232       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2233           A == Other)  // Fold the add into the true select value.
2234         return new SelectInst(SI->getCondition(), N, A);
2235       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2236           A == Other)  // Fold the add into the false select value.
2237         return new SelectInst(SI->getCondition(), A, N);
2238     }
2239   }
2240   
2241   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2242   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2243     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2244       return ReplaceInstUsesWith(I, LHS);
2245
2246   return Changed ? &I : 0;
2247 }
2248
2249 // isSignBit - Return true if the value represented by the constant only has the
2250 // highest order bit set.
2251 static bool isSignBit(ConstantInt *CI) {
2252   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2253   return CI->getValue() == APInt::getSignBit(NumBits);
2254 }
2255
2256 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2257   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2258
2259   if (Op0 == Op1)         // sub X, X  -> 0
2260     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2261
2262   // If this is a 'B = x-(-A)', change to B = x+A...
2263   if (Value *V = dyn_castNegVal(Op1))
2264     return BinaryOperator::createAdd(Op0, V);
2265
2266   if (isa<UndefValue>(Op0))
2267     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2268   if (isa<UndefValue>(Op1))
2269     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2270
2271   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2272     // Replace (-1 - A) with (~A)...
2273     if (C->isAllOnesValue())
2274       return BinaryOperator::createNot(Op1);
2275
2276     // C - ~X == X + (1+C)
2277     Value *X = 0;
2278     if (match(Op1, m_Not(m_Value(X))))
2279       return BinaryOperator::createAdd(X, AddOne(C));
2280
2281     // -(X >>u 31) -> (X >>s 31)
2282     // -(X >>s 31) -> (X >>u 31)
2283     if (C->isZero()) {
2284       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2285         if (SI->getOpcode() == Instruction::LShr) {
2286           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2287             // Check to see if we are shifting out everything but the sign bit.
2288             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2289                 SI->getType()->getPrimitiveSizeInBits()-1) {
2290               // Ok, the transformation is safe.  Insert AShr.
2291               return BinaryOperator::create(Instruction::AShr, 
2292                                           SI->getOperand(0), CU, SI->getName());
2293             }
2294           }
2295         }
2296         else if (SI->getOpcode() == Instruction::AShr) {
2297           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2298             // Check to see if we are shifting out everything but the sign bit.
2299             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2300                 SI->getType()->getPrimitiveSizeInBits()-1) {
2301               // Ok, the transformation is safe.  Insert LShr. 
2302               return BinaryOperator::createLShr(
2303                                           SI->getOperand(0), CU, SI->getName());
2304             }
2305           }
2306         } 
2307     }
2308
2309     // Try to fold constant sub into select arguments.
2310     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2311       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2312         return R;
2313
2314     if (isa<PHINode>(Op0))
2315       if (Instruction *NV = FoldOpIntoPhi(I))
2316         return NV;
2317   }
2318
2319   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2320     if (Op1I->getOpcode() == Instruction::Add &&
2321         !Op0->getType()->isFPOrFPVector()) {
2322       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2323         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2324       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2325         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2326       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2327         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2328           // C1-(X+C2) --> (C1-C2)-X
2329           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2330                                            Op1I->getOperand(0));
2331       }
2332     }
2333
2334     if (Op1I->hasOneUse()) {
2335       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2336       // is not used by anyone else...
2337       //
2338       if (Op1I->getOpcode() == Instruction::Sub &&
2339           !Op1I->getType()->isFPOrFPVector()) {
2340         // Swap the two operands of the subexpr...
2341         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2342         Op1I->setOperand(0, IIOp1);
2343         Op1I->setOperand(1, IIOp0);
2344
2345         // Create the new top level add instruction...
2346         return BinaryOperator::createAdd(Op0, Op1);
2347       }
2348
2349       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2350       //
2351       if (Op1I->getOpcode() == Instruction::And &&
2352           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2353         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2354
2355         Value *NewNot =
2356           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2357         return BinaryOperator::createAnd(Op0, NewNot);
2358       }
2359
2360       // 0 - (X sdiv C)  -> (X sdiv -C)
2361       if (Op1I->getOpcode() == Instruction::SDiv)
2362         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2363           if (CSI->isZero())
2364             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2365               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2366                                                ConstantExpr::getNeg(DivRHS));
2367
2368       // X - X*C --> X * (1-C)
2369       ConstantInt *C2 = 0;
2370       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2371         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2372         return BinaryOperator::createMul(Op0, CP1);
2373       }
2374
2375       // X - ((X / Y) * Y) --> X % Y
2376       if (Op1I->getOpcode() == Instruction::Mul)
2377         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2378           if (Op0 == I->getOperand(0) &&
2379               Op1I->getOperand(1) == I->getOperand(1)) {
2380             if (I->getOpcode() == Instruction::SDiv)
2381               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2382             if (I->getOpcode() == Instruction::UDiv)
2383               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2384           }
2385     }
2386   }
2387
2388   if (!Op0->getType()->isFPOrFPVector())
2389     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2390       if (Op0I->getOpcode() == Instruction::Add) {
2391         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2392           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2393         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2394           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2395       } else if (Op0I->getOpcode() == Instruction::Sub) {
2396         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2397           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2398       }
2399
2400   ConstantInt *C1;
2401   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2402     if (X == Op1)  // X*C - X --> X * (C-1)
2403       return BinaryOperator::createMul(Op1, SubOne(C1));
2404
2405     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2406     if (X == dyn_castFoldableMul(Op1, C2))
2407       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2408   }
2409   return 0;
2410 }
2411
2412 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2413 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2414 /// TrueIfSigned if the result of the comparison is true when the input value is
2415 /// signed.
2416 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2417                            bool &TrueIfSigned) {
2418   switch (pred) {
2419   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2420     TrueIfSigned = true;
2421     return RHS->isZero();
2422   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2423     TrueIfSigned = true;
2424     return RHS->isAllOnesValue();
2425   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2426     TrueIfSigned = false;
2427     return RHS->isAllOnesValue();
2428   case ICmpInst::ICMP_UGT:
2429     // True if LHS u> RHS and RHS == high-bit-mask - 1
2430     TrueIfSigned = true;
2431     return RHS->getValue() ==
2432       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2433   case ICmpInst::ICMP_UGE: 
2434     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2435     TrueIfSigned = true;
2436     return RHS->getValue() == 
2437       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2438   default:
2439     return false;
2440   }
2441 }
2442
2443 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2444   bool Changed = SimplifyCommutative(I);
2445   Value *Op0 = I.getOperand(0);
2446
2447   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2448     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2449
2450   // Simplify mul instructions with a constant RHS...
2451   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2452     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2453
2454       // ((X << C1)*C2) == (X * (C2 << C1))
2455       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2456         if (SI->getOpcode() == Instruction::Shl)
2457           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2458             return BinaryOperator::createMul(SI->getOperand(0),
2459                                              ConstantExpr::getShl(CI, ShOp));
2460
2461       if (CI->isZero())
2462         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2463       if (CI->equalsInt(1))                  // X * 1  == X
2464         return ReplaceInstUsesWith(I, Op0);
2465       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2466         return BinaryOperator::createNeg(Op0, I.getName());
2467
2468       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2469       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2470         return BinaryOperator::createShl(Op0,
2471                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2472       }
2473     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2474       if (Op1F->isNullValue())
2475         return ReplaceInstUsesWith(I, Op1);
2476
2477       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2478       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2479       // We need a better interface for long double here.
2480       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2481         if (Op1F->isExactlyValue(1.0))
2482           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2483     }
2484     
2485     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2486       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2487           isa<ConstantInt>(Op0I->getOperand(1))) {
2488         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2489         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2490                                                      Op1, "tmp");
2491         InsertNewInstBefore(Add, I);
2492         Value *C1C2 = ConstantExpr::getMul(Op1, 
2493                                            cast<Constant>(Op0I->getOperand(1)));
2494         return BinaryOperator::createAdd(Add, C1C2);
2495         
2496       }
2497
2498     // Try to fold constant mul into select arguments.
2499     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2500       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2501         return R;
2502
2503     if (isa<PHINode>(Op0))
2504       if (Instruction *NV = FoldOpIntoPhi(I))
2505         return NV;
2506   }
2507
2508   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2509     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2510       return BinaryOperator::createMul(Op0v, Op1v);
2511
2512   // If one of the operands of the multiply is a cast from a boolean value, then
2513   // we know the bool is either zero or one, so this is a 'masking' multiply.
2514   // See if we can simplify things based on how the boolean was originally
2515   // formed.
2516   CastInst *BoolCast = 0;
2517   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2518     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2519       BoolCast = CI;
2520   if (!BoolCast)
2521     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2522       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2523         BoolCast = CI;
2524   if (BoolCast) {
2525     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2526       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2527       const Type *SCOpTy = SCIOp0->getType();
2528       bool TIS = false;
2529       
2530       // If the icmp is true iff the sign bit of X is set, then convert this
2531       // multiply into a shift/and combination.
2532       if (isa<ConstantInt>(SCIOp1) &&
2533           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2534           TIS) {
2535         // Shift the X value right to turn it into "all signbits".
2536         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2537                                           SCOpTy->getPrimitiveSizeInBits()-1);
2538         Value *V =
2539           InsertNewInstBefore(
2540             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2541                                             BoolCast->getOperand(0)->getName()+
2542                                             ".mask"), I);
2543
2544         // If the multiply type is not the same as the source type, sign extend
2545         // or truncate to the multiply type.
2546         if (I.getType() != V->getType()) {
2547           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2548           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2549           Instruction::CastOps opcode = 
2550             (SrcBits == DstBits ? Instruction::BitCast : 
2551              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2552           V = InsertCastBefore(opcode, V, I.getType(), I);
2553         }
2554
2555         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2556         return BinaryOperator::createAnd(V, OtherOp);
2557       }
2558     }
2559   }
2560
2561   return Changed ? &I : 0;
2562 }
2563
2564 /// This function implements the transforms on div instructions that work
2565 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2566 /// used by the visitors to those instructions.
2567 /// @brief Transforms common to all three div instructions
2568 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2569   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2570
2571   // undef / X -> 0
2572   if (isa<UndefValue>(Op0))
2573     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2574
2575   // X / undef -> undef
2576   if (isa<UndefValue>(Op1))
2577     return ReplaceInstUsesWith(I, Op1);
2578
2579   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2580   // This does not apply for fdiv.
2581   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2582     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2583     // the same basic block, then we replace the select with Y, and the
2584     // condition of the select with false (if the cond value is in the same BB).
2585     // If the select has uses other than the div, this allows them to be
2586     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2587     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2588       if (ST->isNullValue()) {
2589         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2590         if (CondI && CondI->getParent() == I.getParent())
2591           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2592         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2593           I.setOperand(1, SI->getOperand(2));
2594         else
2595           UpdateValueUsesWith(SI, SI->getOperand(2));
2596         return &I;
2597       }
2598
2599     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2600     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2601       if (ST->isNullValue()) {
2602         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2603         if (CondI && CondI->getParent() == I.getParent())
2604           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2605         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2606           I.setOperand(1, SI->getOperand(1));
2607         else
2608           UpdateValueUsesWith(SI, SI->getOperand(1));
2609         return &I;
2610       }
2611   }
2612
2613   return 0;
2614 }
2615
2616 /// This function implements the transforms common to both integer division
2617 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2618 /// division instructions.
2619 /// @brief Common integer divide transforms
2620 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2621   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2622
2623   if (Instruction *Common = commonDivTransforms(I))
2624     return Common;
2625
2626   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2627     // div X, 1 == X
2628     if (RHS->equalsInt(1))
2629       return ReplaceInstUsesWith(I, Op0);
2630
2631     // (X / C1) / C2  -> X / (C1*C2)
2632     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2633       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2634         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2635           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2636                                         Multiply(RHS, LHSRHS));
2637         }
2638
2639     if (!RHS->isZero()) { // avoid X udiv 0
2640       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2641         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2642           return R;
2643       if (isa<PHINode>(Op0))
2644         if (Instruction *NV = FoldOpIntoPhi(I))
2645           return NV;
2646     }
2647   }
2648
2649   // 0 / X == 0, we don't need to preserve faults!
2650   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2651     if (LHS->equalsInt(0))
2652       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2653
2654   return 0;
2655 }
2656
2657 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2658   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2659
2660   // Handle the integer div common cases
2661   if (Instruction *Common = commonIDivTransforms(I))
2662     return Common;
2663
2664   // X udiv C^2 -> X >> C
2665   // Check to see if this is an unsigned division with an exact power of 2,
2666   // if so, convert to a right shift.
2667   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2668     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2669       return BinaryOperator::createLShr(Op0, 
2670                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2671   }
2672
2673   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2674   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2675     if (RHSI->getOpcode() == Instruction::Shl &&
2676         isa<ConstantInt>(RHSI->getOperand(0))) {
2677       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2678       if (C1.isPowerOf2()) {
2679         Value *N = RHSI->getOperand(1);
2680         const Type *NTy = N->getType();
2681         if (uint32_t C2 = C1.logBase2()) {
2682           Constant *C2V = ConstantInt::get(NTy, C2);
2683           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2684         }
2685         return BinaryOperator::createLShr(Op0, N);
2686       }
2687     }
2688   }
2689   
2690   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2691   // where C1&C2 are powers of two.
2692   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2693     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2694       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2695         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2696         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2697           // Compute the shift amounts
2698           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2699           // Construct the "on true" case of the select
2700           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2701           Instruction *TSI = BinaryOperator::createLShr(
2702                                                  Op0, TC, SI->getName()+".t");
2703           TSI = InsertNewInstBefore(TSI, I);
2704   
2705           // Construct the "on false" case of the select
2706           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2707           Instruction *FSI = BinaryOperator::createLShr(
2708                                                  Op0, FC, SI->getName()+".f");
2709           FSI = InsertNewInstBefore(FSI, I);
2710
2711           // construct the select instruction and return it.
2712           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2713         }
2714       }
2715   return 0;
2716 }
2717
2718 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2719   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2720
2721   // Handle the integer div common cases
2722   if (Instruction *Common = commonIDivTransforms(I))
2723     return Common;
2724
2725   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2726     // sdiv X, -1 == -X
2727     if (RHS->isAllOnesValue())
2728       return BinaryOperator::createNeg(Op0);
2729
2730     // -X/C -> X/-C
2731     if (Value *LHSNeg = dyn_castNegVal(Op0))
2732       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2733   }
2734
2735   // If the sign bits of both operands are zero (i.e. we can prove they are
2736   // unsigned inputs), turn this into a udiv.
2737   if (I.getType()->isInteger()) {
2738     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2739     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2740       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2741       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2742     }
2743   }      
2744   
2745   return 0;
2746 }
2747
2748 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2749   return commonDivTransforms(I);
2750 }
2751
2752 /// GetFactor - If we can prove that the specified value is at least a multiple
2753 /// of some factor, return that factor.
2754 static Constant *GetFactor(Value *V) {
2755   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2756     return CI;
2757   
2758   // Unless we can be tricky, we know this is a multiple of 1.
2759   Constant *Result = ConstantInt::get(V->getType(), 1);
2760   
2761   Instruction *I = dyn_cast<Instruction>(V);
2762   if (!I) return Result;
2763   
2764   if (I->getOpcode() == Instruction::Mul) {
2765     // Handle multiplies by a constant, etc.
2766     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2767                                 GetFactor(I->getOperand(1)));
2768   } else if (I->getOpcode() == Instruction::Shl) {
2769     // (X<<C) -> X * (1 << C)
2770     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2771       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2772       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2773     }
2774   } else if (I->getOpcode() == Instruction::And) {
2775     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2776       // X & 0xFFF0 is known to be a multiple of 16.
2777       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2778       if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
2779         return ConstantExpr::getShl(Result, 
2780                                     ConstantInt::get(Result->getType(), Zeros));
2781     }
2782   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2783     // Only handle int->int casts.
2784     if (!CI->isIntegerCast())
2785       return Result;
2786     Value *Op = CI->getOperand(0);
2787     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2788   }    
2789   return Result;
2790 }
2791
2792 /// This function implements the transforms on rem instructions that work
2793 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2794 /// is used by the visitors to those instructions.
2795 /// @brief Transforms common to all three rem instructions
2796 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2797   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798
2799   // 0 % X == 0, we don't need to preserve faults!
2800   if (Constant *LHS = dyn_cast<Constant>(Op0))
2801     if (LHS->isNullValue())
2802       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2803
2804   if (isa<UndefValue>(Op0))              // undef % X -> 0
2805     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2806   if (isa<UndefValue>(Op1))
2807     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2808
2809   // Handle cases involving: rem X, (select Cond, Y, Z)
2810   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2811     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2812     // the same basic block, then we replace the select with Y, and the
2813     // condition of the select with false (if the cond value is in the same
2814     // BB).  If the select has uses other than the div, this allows them to be
2815     // simplified also.
2816     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2817       if (ST->isNullValue()) {
2818         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2819         if (CondI && CondI->getParent() == I.getParent())
2820           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2821         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2822           I.setOperand(1, SI->getOperand(2));
2823         else
2824           UpdateValueUsesWith(SI, SI->getOperand(2));
2825         return &I;
2826       }
2827     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2828     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2829       if (ST->isNullValue()) {
2830         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2831         if (CondI && CondI->getParent() == I.getParent())
2832           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2833         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2834           I.setOperand(1, SI->getOperand(1));
2835         else
2836           UpdateValueUsesWith(SI, SI->getOperand(1));
2837         return &I;
2838       }
2839   }
2840
2841   return 0;
2842 }
2843
2844 /// This function implements the transforms common to both integer remainder
2845 /// instructions (urem and srem). It is called by the visitors to those integer
2846 /// remainder instructions.
2847 /// @brief Common integer remainder transforms
2848 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2849   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2850
2851   if (Instruction *common = commonRemTransforms(I))
2852     return common;
2853
2854   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2855     // X % 0 == undef, we don't need to preserve faults!
2856     if (RHS->equalsInt(0))
2857       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2858     
2859     if (RHS->equalsInt(1))  // X % 1 == 0
2860       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2861
2862     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2863       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2864         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2865           return R;
2866       } else if (isa<PHINode>(Op0I)) {
2867         if (Instruction *NV = FoldOpIntoPhi(I))
2868           return NV;
2869       }
2870       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2871       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2872         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2873     }
2874   }
2875
2876   return 0;
2877 }
2878
2879 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2880   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2881
2882   if (Instruction *common = commonIRemTransforms(I))
2883     return common;
2884   
2885   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2886     // X urem C^2 -> X and C
2887     // Check to see if this is an unsigned remainder with an exact power of 2,
2888     // if so, convert to a bitwise and.
2889     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2890       if (C->getValue().isPowerOf2())
2891         return BinaryOperator::createAnd(Op0, SubOne(C));
2892   }
2893
2894   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2895     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2896     if (RHSI->getOpcode() == Instruction::Shl &&
2897         isa<ConstantInt>(RHSI->getOperand(0))) {
2898       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2899         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2900         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2901                                                                    "tmp"), I);
2902         return BinaryOperator::createAnd(Op0, Add);
2903       }
2904     }
2905   }
2906
2907   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2908   // where C1&C2 are powers of two.
2909   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2910     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2911       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2912         // STO == 0 and SFO == 0 handled above.
2913         if ((STO->getValue().isPowerOf2()) && 
2914             (SFO->getValue().isPowerOf2())) {
2915           Value *TrueAnd = InsertNewInstBefore(
2916             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2917           Value *FalseAnd = InsertNewInstBefore(
2918             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2919           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2920         }
2921       }
2922   }
2923   
2924   return 0;
2925 }
2926
2927 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2928   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
2930   // Handle the integer rem common cases
2931   if (Instruction *common = commonIRemTransforms(I))
2932     return common;
2933   
2934   if (Value *RHSNeg = dyn_castNegVal(Op1))
2935     if (!isa<ConstantInt>(RHSNeg) || 
2936         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2937       // X % -Y -> X % Y
2938       AddUsesToWorkList(I);
2939       I.setOperand(1, RHSNeg);
2940       return &I;
2941     }
2942  
2943   // If the sign bits of both operands are zero (i.e. we can prove they are
2944   // unsigned inputs), turn this into a urem.
2945   if (I.getType()->isInteger()) {
2946     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2947     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2948       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2949       return BinaryOperator::createURem(Op0, Op1, I.getName());
2950     }
2951   }
2952
2953   return 0;
2954 }
2955
2956 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2957   return commonRemTransforms(I);
2958 }
2959
2960 // isMaxValueMinusOne - return true if this is Max-1
2961 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2962   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2963   if (!isSigned)
2964     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2965   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2966 }
2967
2968 // isMinValuePlusOne - return true if this is Min+1
2969 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2970   if (!isSigned)
2971     return C->getValue() == 1; // unsigned
2972     
2973   // Calculate 1111111111000000000000
2974   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2975   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2976 }
2977
2978 // isOneBitSet - Return true if there is exactly one bit set in the specified
2979 // constant.
2980 static bool isOneBitSet(const ConstantInt *CI) {
2981   return CI->getValue().isPowerOf2();
2982 }
2983
2984 // isHighOnes - Return true if the constant is of the form 1+0+.
2985 // This is the same as lowones(~X).
2986 static bool isHighOnes(const ConstantInt *CI) {
2987   return (~CI->getValue() + 1).isPowerOf2();
2988 }
2989
2990 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2991 /// are carefully arranged to allow folding of expressions such as:
2992 ///
2993 ///      (A < B) | (A > B) --> (A != B)
2994 ///
2995 /// Note that this is only valid if the first and second predicates have the
2996 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2997 ///
2998 /// Three bits are used to represent the condition, as follows:
2999 ///   0  A > B
3000 ///   1  A == B
3001 ///   2  A < B
3002 ///
3003 /// <=>  Value  Definition
3004 /// 000     0   Always false
3005 /// 001     1   A >  B
3006 /// 010     2   A == B
3007 /// 011     3   A >= B
3008 /// 100     4   A <  B
3009 /// 101     5   A != B
3010 /// 110     6   A <= B
3011 /// 111     7   Always true
3012 ///  
3013 static unsigned getICmpCode(const ICmpInst *ICI) {
3014   switch (ICI->getPredicate()) {
3015     // False -> 0
3016   case ICmpInst::ICMP_UGT: return 1;  // 001
3017   case ICmpInst::ICMP_SGT: return 1;  // 001
3018   case ICmpInst::ICMP_EQ:  return 2;  // 010
3019   case ICmpInst::ICMP_UGE: return 3;  // 011
3020   case ICmpInst::ICMP_SGE: return 3;  // 011
3021   case ICmpInst::ICMP_ULT: return 4;  // 100
3022   case ICmpInst::ICMP_SLT: return 4;  // 100
3023   case ICmpInst::ICMP_NE:  return 5;  // 101
3024   case ICmpInst::ICMP_ULE: return 6;  // 110
3025   case ICmpInst::ICMP_SLE: return 6;  // 110
3026     // True -> 7
3027   default:
3028     assert(0 && "Invalid ICmp predicate!");
3029     return 0;
3030   }
3031 }
3032
3033 /// getICmpValue - This is the complement of getICmpCode, which turns an
3034 /// opcode and two operands into either a constant true or false, or a brand 
3035 /// new ICmp instruction. The sign is passed in to determine which kind
3036 /// of predicate to use in new icmp instructions.
3037 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3038   switch (code) {
3039   default: assert(0 && "Illegal ICmp code!");
3040   case  0: return ConstantInt::getFalse();
3041   case  1: 
3042     if (sign)
3043       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3044     else
3045       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3046   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3047   case  3: 
3048     if (sign)
3049       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3050     else
3051       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3052   case  4: 
3053     if (sign)
3054       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3055     else
3056       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3057   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3058   case  6: 
3059     if (sign)
3060       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3061     else
3062       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3063   case  7: return ConstantInt::getTrue();
3064   }
3065 }
3066
3067 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3068   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3069     (ICmpInst::isSignedPredicate(p1) && 
3070      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3071     (ICmpInst::isSignedPredicate(p2) && 
3072      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3073 }
3074
3075 namespace { 
3076 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3077 struct FoldICmpLogical {
3078   InstCombiner &IC;
3079   Value *LHS, *RHS;
3080   ICmpInst::Predicate pred;
3081   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3082     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3083       pred(ICI->getPredicate()) {}
3084   bool shouldApply(Value *V) const {
3085     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3086       if (PredicatesFoldable(pred, ICI->getPredicate()))
3087         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3088                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3089     return false;
3090   }
3091   Instruction *apply(Instruction &Log) const {
3092     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3093     if (ICI->getOperand(0) != LHS) {
3094       assert(ICI->getOperand(1) == LHS);
3095       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3096     }
3097
3098     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3099     unsigned LHSCode = getICmpCode(ICI);
3100     unsigned RHSCode = getICmpCode(RHSICI);
3101     unsigned Code;
3102     switch (Log.getOpcode()) {
3103     case Instruction::And: Code = LHSCode & RHSCode; break;
3104     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3105     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3106     default: assert(0 && "Illegal logical opcode!"); return 0;
3107     }
3108
3109     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3110                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3111       
3112     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3113     if (Instruction *I = dyn_cast<Instruction>(RV))
3114       return I;
3115     // Otherwise, it's a constant boolean value...
3116     return IC.ReplaceInstUsesWith(Log, RV);
3117   }
3118 };
3119 } // end anonymous namespace
3120
3121 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3122 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3123 // guaranteed to be a binary operator.
3124 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3125                                     ConstantInt *OpRHS,
3126                                     ConstantInt *AndRHS,
3127                                     BinaryOperator &TheAnd) {
3128   Value *X = Op->getOperand(0);
3129   Constant *Together = 0;
3130   if (!Op->isShift())
3131     Together = And(AndRHS, OpRHS);
3132
3133   switch (Op->getOpcode()) {
3134   case Instruction::Xor:
3135     if (Op->hasOneUse()) {
3136       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3137       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3138       InsertNewInstBefore(And, TheAnd);
3139       And->takeName(Op);
3140       return BinaryOperator::createXor(And, Together);
3141     }
3142     break;
3143   case Instruction::Or:
3144     if (Together == AndRHS) // (X | C) & C --> C
3145       return ReplaceInstUsesWith(TheAnd, AndRHS);
3146
3147     if (Op->hasOneUse() && Together != OpRHS) {
3148       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3149       Instruction *Or = BinaryOperator::createOr(X, Together);
3150       InsertNewInstBefore(Or, TheAnd);
3151       Or->takeName(Op);
3152       return BinaryOperator::createAnd(Or, AndRHS);
3153     }
3154     break;
3155   case Instruction::Add:
3156     if (Op->hasOneUse()) {
3157       // Adding a one to a single bit bit-field should be turned into an XOR
3158       // of the bit.  First thing to check is to see if this AND is with a
3159       // single bit constant.
3160       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3161
3162       // If there is only one bit set...
3163       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3164         // Ok, at this point, we know that we are masking the result of the
3165         // ADD down to exactly one bit.  If the constant we are adding has
3166         // no bits set below this bit, then we can eliminate the ADD.
3167         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3168
3169         // Check to see if any bits below the one bit set in AndRHSV are set.
3170         if ((AddRHS & (AndRHSV-1)) == 0) {
3171           // If not, the only thing that can effect the output of the AND is
3172           // the bit specified by AndRHSV.  If that bit is set, the effect of
3173           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3174           // no effect.
3175           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3176             TheAnd.setOperand(0, X);
3177             return &TheAnd;
3178           } else {
3179             // Pull the XOR out of the AND.
3180             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3181             InsertNewInstBefore(NewAnd, TheAnd);
3182             NewAnd->takeName(Op);
3183             return BinaryOperator::createXor(NewAnd, AndRHS);
3184           }
3185         }
3186       }
3187     }
3188     break;
3189
3190   case Instruction::Shl: {
3191     // We know that the AND will not produce any of the bits shifted in, so if
3192     // the anded constant includes them, clear them now!
3193     //
3194     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3195     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3196     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3197     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3198
3199     if (CI->getValue() == ShlMask) { 
3200     // Masking out bits that the shift already masks
3201       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3202     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3203       TheAnd.setOperand(1, CI);
3204       return &TheAnd;
3205     }
3206     break;
3207   }
3208   case Instruction::LShr:
3209   {
3210     // We know that the AND will not produce any of the bits shifted in, so if
3211     // the anded constant includes them, clear them now!  This only applies to
3212     // unsigned shifts, because a signed shr may bring in set bits!
3213     //
3214     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3215     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3216     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3217     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3218
3219     if (CI->getValue() == ShrMask) {   
3220     // Masking out bits that the shift already masks.
3221       return ReplaceInstUsesWith(TheAnd, Op);
3222     } else if (CI != AndRHS) {
3223       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3224       return &TheAnd;
3225     }
3226     break;
3227   }
3228   case Instruction::AShr:
3229     // Signed shr.
3230     // See if this is shifting in some sign extension, then masking it out
3231     // with an and.
3232     if (Op->hasOneUse()) {
3233       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3234       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3235       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3236       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3237       if (C == AndRHS) {          // Masking out bits shifted in.
3238         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3239         // Make the argument unsigned.
3240         Value *ShVal = Op->getOperand(0);
3241         ShVal = InsertNewInstBefore(
3242             BinaryOperator::createLShr(ShVal, OpRHS, 
3243                                    Op->getName()), TheAnd);
3244         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3245       }
3246     }
3247     break;
3248   }
3249   return 0;
3250 }
3251
3252
3253 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3254 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3255 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3256 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3257 /// insert new instructions.
3258 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3259                                            bool isSigned, bool Inside, 
3260                                            Instruction &IB) {
3261   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3262             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3263          "Lo is not <= Hi in range emission code!");
3264     
3265   if (Inside) {
3266     if (Lo == Hi)  // Trivially false.
3267       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3268
3269     // V >= Min && V < Hi --> V < Hi
3270     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3271       ICmpInst::Predicate pred = (isSigned ? 
3272         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3273       return new ICmpInst(pred, V, Hi);
3274     }
3275
3276     // Emit V-Lo <u Hi-Lo
3277     Constant *NegLo = ConstantExpr::getNeg(Lo);
3278     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3279     InsertNewInstBefore(Add, IB);
3280     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3281     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3282   }
3283
3284   if (Lo == Hi)  // Trivially true.
3285     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3286
3287   // V < Min || V >= Hi -> V > Hi-1
3288   Hi = SubOne(cast<ConstantInt>(Hi));
3289   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3290     ICmpInst::Predicate pred = (isSigned ? 
3291         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3292     return new ICmpInst(pred, V, Hi);
3293   }
3294
3295   // Emit V-Lo >u Hi-1-Lo
3296   // Note that Hi has already had one subtracted from it, above.
3297   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3298   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3299   InsertNewInstBefore(Add, IB);
3300   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3301   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3302 }
3303
3304 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3305 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3306 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3307 // not, since all 1s are not contiguous.
3308 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3309   const APInt& V = Val->getValue();
3310   uint32_t BitWidth = Val->getType()->getBitWidth();
3311   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3312
3313   // look for the first zero bit after the run of ones
3314   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3315   // look for the first non-zero bit
3316   ME = V.getActiveBits(); 
3317   return true;
3318 }
3319
3320 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3321 /// where isSub determines whether the operator is a sub.  If we can fold one of
3322 /// the following xforms:
3323 /// 
3324 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3325 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3326 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3327 ///
3328 /// return (A +/- B).
3329 ///
3330 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3331                                         ConstantInt *Mask, bool isSub,
3332                                         Instruction &I) {
3333   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3334   if (!LHSI || LHSI->getNumOperands() != 2 ||
3335       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3336
3337   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3338
3339   switch (LHSI->getOpcode()) {
3340   default: return 0;
3341   case Instruction::And:
3342     if (And(N, Mask) == Mask) {
3343       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3344       if ((Mask->getValue().countLeadingZeros() + 
3345            Mask->getValue().countPopulation()) == 
3346           Mask->getValue().getBitWidth())
3347         break;
3348
3349       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3350       // part, we don't need any explicit masks to take them out of A.  If that
3351       // is all N is, ignore it.
3352       uint32_t MB = 0, ME = 0;
3353       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3354         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3355         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3356         if (MaskedValueIsZero(RHS, Mask))
3357           break;
3358       }
3359     }
3360     return 0;
3361   case Instruction::Or:
3362   case Instruction::Xor:
3363     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3364     if ((Mask->getValue().countLeadingZeros() + 
3365          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3366         && And(N, Mask)->isZero())
3367       break;
3368     return 0;
3369   }
3370   
3371   Instruction *New;
3372   if (isSub)
3373     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3374   else
3375     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3376   return InsertNewInstBefore(New, I);
3377 }
3378
3379 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3380   bool Changed = SimplifyCommutative(I);
3381   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3382
3383   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3384     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3385
3386   // and X, X = X
3387   if (Op0 == Op1)
3388     return ReplaceInstUsesWith(I, Op1);
3389
3390   // See if we can simplify any instructions used by the instruction whose sole 
3391   // purpose is to compute bits we don't care about.
3392   if (!isa<VectorType>(I.getType())) {
3393     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3394     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3395     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3396                              KnownZero, KnownOne))
3397       return &I;
3398   } else {
3399     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3400       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3401         return ReplaceInstUsesWith(I, I.getOperand(0));
3402     } else if (isa<ConstantAggregateZero>(Op1)) {
3403       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3404     }
3405   }
3406   
3407   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3408     const APInt& AndRHSMask = AndRHS->getValue();
3409     APInt NotAndRHS(~AndRHSMask);
3410
3411     // Optimize a variety of ((val OP C1) & C2) combinations...
3412     if (isa<BinaryOperator>(Op0)) {
3413       Instruction *Op0I = cast<Instruction>(Op0);
3414       Value *Op0LHS = Op0I->getOperand(0);
3415       Value *Op0RHS = Op0I->getOperand(1);
3416       switch (Op0I->getOpcode()) {
3417       case Instruction::Xor:
3418       case Instruction::Or:
3419         // If the mask is only needed on one incoming arm, push it up.
3420         if (Op0I->hasOneUse()) {
3421           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3422             // Not masking anything out for the LHS, move to RHS.
3423             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3424                                                    Op0RHS->getName()+".masked");
3425             InsertNewInstBefore(NewRHS, I);
3426             return BinaryOperator::create(
3427                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3428           }
3429           if (!isa<Constant>(Op0RHS) &&
3430               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3431             // Not masking anything out for the RHS, move to LHS.
3432             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3433                                                    Op0LHS->getName()+".masked");
3434             InsertNewInstBefore(NewLHS, I);
3435             return BinaryOperator::create(
3436                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3437           }
3438         }
3439
3440         break;
3441       case Instruction::Add:
3442         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3443         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3444         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3445         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3446           return BinaryOperator::createAnd(V, AndRHS);
3447         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3448           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3449         break;
3450
3451       case Instruction::Sub:
3452         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3453         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3454         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3455         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3456           return BinaryOperator::createAnd(V, AndRHS);
3457         break;
3458       }
3459
3460       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3461         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3462           return Res;
3463     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3464       // If this is an integer truncation or change from signed-to-unsigned, and
3465       // if the source is an and/or with immediate, transform it.  This
3466       // frequently occurs for bitfield accesses.
3467       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3468         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3469             CastOp->getNumOperands() == 2)
3470           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3471             if (CastOp->getOpcode() == Instruction::And) {
3472               // Change: and (cast (and X, C1) to T), C2
3473               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3474               // This will fold the two constants together, which may allow 
3475               // other simplifications.
3476               Instruction *NewCast = CastInst::createTruncOrBitCast(
3477                 CastOp->getOperand(0), I.getType(), 
3478                 CastOp->getName()+".shrunk");
3479               NewCast = InsertNewInstBefore(NewCast, I);
3480               // trunc_or_bitcast(C1)&C2
3481               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3482               C3 = ConstantExpr::getAnd(C3, AndRHS);
3483               return BinaryOperator::createAnd(NewCast, C3);
3484             } else if (CastOp->getOpcode() == Instruction::Or) {
3485               // Change: and (cast (or X, C1) to T), C2
3486               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3487               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3488               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3489                 return ReplaceInstUsesWith(I, AndRHS);
3490             }
3491       }
3492     }
3493
3494     // Try to fold constant and into select arguments.
3495     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3496       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3497         return R;
3498     if (isa<PHINode>(Op0))
3499       if (Instruction *NV = FoldOpIntoPhi(I))
3500         return NV;
3501   }
3502
3503   Value *Op0NotVal = dyn_castNotVal(Op0);
3504   Value *Op1NotVal = dyn_castNotVal(Op1);
3505
3506   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3507     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3508
3509   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3510   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3511     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3512                                                I.getName()+".demorgan");
3513     InsertNewInstBefore(Or, I);
3514     return BinaryOperator::createNot(Or);
3515   }
3516   
3517   {
3518     Value *A = 0, *B = 0, *C = 0, *D = 0;
3519     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3520       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3521         return ReplaceInstUsesWith(I, Op1);
3522     
3523       // (A|B) & ~(A&B) -> A^B
3524       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3525         if ((A == C && B == D) || (A == D && B == C))
3526           return BinaryOperator::createXor(A, B);
3527       }
3528     }
3529     
3530     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3531       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3532         return ReplaceInstUsesWith(I, Op0);
3533
3534       // ~(A&B) & (A|B) -> A^B
3535       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3536         if ((A == C && B == D) || (A == D && B == C))
3537           return BinaryOperator::createXor(A, B);
3538       }
3539     }
3540     
3541     if (Op0->hasOneUse() &&
3542         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3543       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3544         I.swapOperands();     // Simplify below
3545         std::swap(Op0, Op1);
3546       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3547         cast<BinaryOperator>(Op0)->swapOperands();
3548         I.swapOperands();     // Simplify below
3549         std::swap(Op0, Op1);
3550       }
3551     }
3552     if (Op1->hasOneUse() &&
3553         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3554       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3555         cast<BinaryOperator>(Op1)->swapOperands();
3556         std::swap(A, B);
3557       }
3558       if (A == Op0) {                                // A&(A^B) -> A & ~B
3559         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3560         InsertNewInstBefore(NotB, I);
3561         return BinaryOperator::createAnd(A, NotB);
3562       }
3563     }
3564   }
3565   
3566   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3567     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3568     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3569       return R;
3570
3571     Value *LHSVal, *RHSVal;
3572     ConstantInt *LHSCst, *RHSCst;
3573     ICmpInst::Predicate LHSCC, RHSCC;
3574     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3575       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3576         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3577             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3578             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3579             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3580             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3581             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3582             
3583             // Don't try to fold ICMP_SLT + ICMP_ULT.
3584             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3585              ICmpInst::isSignedPredicate(LHSCC) == 
3586                  ICmpInst::isSignedPredicate(RHSCC))) {
3587           // Ensure that the larger constant is on the RHS.
3588           ICmpInst::Predicate GT;
3589           if (ICmpInst::isSignedPredicate(LHSCC) ||
3590               (ICmpInst::isEquality(LHSCC) && 
3591                ICmpInst::isSignedPredicate(RHSCC)))
3592             GT = ICmpInst::ICMP_SGT;
3593           else
3594             GT = ICmpInst::ICMP_UGT;
3595           
3596           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3597           ICmpInst *LHS = cast<ICmpInst>(Op0);
3598           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3599             std::swap(LHS, RHS);
3600             std::swap(LHSCst, RHSCst);
3601             std::swap(LHSCC, RHSCC);
3602           }
3603
3604           // At this point, we know we have have two icmp instructions
3605           // comparing a value against two constants and and'ing the result
3606           // together.  Because of the above check, we know that we only have
3607           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3608           // (from the FoldICmpLogical check above), that the two constants 
3609           // are not equal and that the larger constant is on the RHS
3610           assert(LHSCst != RHSCst && "Compares not folded above?");
3611
3612           switch (LHSCC) {
3613           default: assert(0 && "Unknown integer condition code!");
3614           case ICmpInst::ICMP_EQ:
3615             switch (RHSCC) {
3616             default: assert(0 && "Unknown integer condition code!");
3617             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3618             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3619             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3620               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3621             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3622             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3623             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3624               return ReplaceInstUsesWith(I, LHS);
3625             }
3626           case ICmpInst::ICMP_NE:
3627             switch (RHSCC) {
3628             default: assert(0 && "Unknown integer condition code!");
3629             case ICmpInst::ICMP_ULT:
3630               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3631                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3632               break;                        // (X != 13 & X u< 15) -> no change
3633             case ICmpInst::ICMP_SLT:
3634               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3635                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3636               break;                        // (X != 13 & X s< 15) -> no change
3637             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3638             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3639             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3640               return ReplaceInstUsesWith(I, RHS);
3641             case ICmpInst::ICMP_NE:
3642               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3643                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3644                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3645                                                       LHSVal->getName()+".off");
3646                 InsertNewInstBefore(Add, I);
3647                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3648                                     ConstantInt::get(Add->getType(), 1));
3649               }
3650               break;                        // (X != 13 & X != 15) -> no change
3651             }
3652             break;
3653           case ICmpInst::ICMP_ULT:
3654             switch (RHSCC) {
3655             default: assert(0 && "Unknown integer condition code!");
3656             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3657             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3658               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3659             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3660               break;
3661             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3662             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3663               return ReplaceInstUsesWith(I, LHS);
3664             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3665               break;
3666             }
3667             break;
3668           case ICmpInst::ICMP_SLT:
3669             switch (RHSCC) {
3670             default: assert(0 && "Unknown integer condition code!");
3671             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3672             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3673               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3674             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3675               break;
3676             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3677             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3678               return ReplaceInstUsesWith(I, LHS);
3679             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3680               break;
3681             }
3682             break;
3683           case ICmpInst::ICMP_UGT:
3684             switch (RHSCC) {
3685             default: assert(0 && "Unknown integer condition code!");
3686             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3687               return ReplaceInstUsesWith(I, LHS);
3688             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3689               return ReplaceInstUsesWith(I, RHS);
3690             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3691               break;
3692             case ICmpInst::ICMP_NE:
3693               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3694                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3695               break;                        // (X u> 13 & X != 15) -> no change
3696             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3697               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3698                                      true, I);
3699             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3700               break;
3701             }
3702             break;
3703           case ICmpInst::ICMP_SGT:
3704             switch (RHSCC) {
3705             default: assert(0 && "Unknown integer condition code!");
3706             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3707             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3708               return ReplaceInstUsesWith(I, RHS);
3709             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3710               break;
3711             case ICmpInst::ICMP_NE:
3712               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3713                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3714               break;                        // (X s> 13 & X != 15) -> no change
3715             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3716               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3717                                      true, I);
3718             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3719               break;
3720             }
3721             break;
3722           }
3723         }
3724   }
3725
3726   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3727   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3728     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3729       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3730         const Type *SrcTy = Op0C->getOperand(0)->getType();
3731         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3732             // Only do this if the casts both really cause code to be generated.
3733             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3734                               I.getType(), TD) &&
3735             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3736                               I.getType(), TD)) {
3737           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3738                                                          Op1C->getOperand(0),
3739                                                          I.getName());
3740           InsertNewInstBefore(NewOp, I);
3741           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3742         }
3743       }
3744     
3745   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3746   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3747     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3748       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3749           SI0->getOperand(1) == SI1->getOperand(1) &&
3750           (SI0->hasOneUse() || SI1->hasOneUse())) {
3751         Instruction *NewOp =
3752           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3753                                                         SI1->getOperand(0),
3754                                                         SI0->getName()), I);
3755         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3756                                       SI1->getOperand(1));
3757       }
3758   }
3759
3760   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3761   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3762     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3763       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3764           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3765         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3766           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3767             // If either of the constants are nans, then the whole thing returns
3768             // false.
3769             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3770               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3771             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3772                                 RHS->getOperand(0));
3773           }
3774     }
3775   }
3776       
3777   return Changed ? &I : 0;
3778 }
3779
3780 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3781 /// in the result.  If it does, and if the specified byte hasn't been filled in
3782 /// yet, fill it in and return false.
3783 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3784   Instruction *I = dyn_cast<Instruction>(V);
3785   if (I == 0) return true;
3786
3787   // If this is an or instruction, it is an inner node of the bswap.
3788   if (I->getOpcode() == Instruction::Or)
3789     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3790            CollectBSwapParts(I->getOperand(1), ByteValues);
3791   
3792   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3793   // If this is a shift by a constant int, and it is "24", then its operand
3794   // defines a byte.  We only handle unsigned types here.
3795   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3796     // Not shifting the entire input by N-1 bytes?
3797     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3798         8*(ByteValues.size()-1))
3799       return true;
3800     
3801     unsigned DestNo;
3802     if (I->getOpcode() == Instruction::Shl) {
3803       // X << 24 defines the top byte with the lowest of the input bytes.
3804       DestNo = ByteValues.size()-1;
3805     } else {
3806       // X >>u 24 defines the low byte with the highest of the input bytes.
3807       DestNo = 0;
3808     }
3809     
3810     // If the destination byte value is already defined, the values are or'd
3811     // together, which isn't a bswap (unless it's an or of the same bits).
3812     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3813       return true;
3814     ByteValues[DestNo] = I->getOperand(0);
3815     return false;
3816   }
3817   
3818   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3819   // don't have this.
3820   Value *Shift = 0, *ShiftLHS = 0;
3821   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3822   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3823       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3824     return true;
3825   Instruction *SI = cast<Instruction>(Shift);
3826
3827   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3828   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3829       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3830     return true;
3831   
3832   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3833   unsigned DestByte;
3834   if (AndAmt->getValue().getActiveBits() > 64)
3835     return true;
3836   uint64_t AndAmtVal = AndAmt->getZExtValue();
3837   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3838     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3839       break;
3840   // Unknown mask for bswap.
3841   if (DestByte == ByteValues.size()) return true;
3842   
3843   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3844   unsigned SrcByte;
3845   if (SI->getOpcode() == Instruction::Shl)
3846     SrcByte = DestByte - ShiftBytes;
3847   else
3848     SrcByte = DestByte + ShiftBytes;
3849   
3850   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3851   if (SrcByte != ByteValues.size()-DestByte-1)
3852     return true;
3853   
3854   // If the destination byte value is already defined, the values are or'd
3855   // together, which isn't a bswap (unless it's an or of the same bits).
3856   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3857     return true;
3858   ByteValues[DestByte] = SI->getOperand(0);
3859   return false;
3860 }
3861
3862 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3863 /// If so, insert the new bswap intrinsic and return it.
3864 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3865   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3866   if (!ITy || ITy->getBitWidth() % 16) 
3867     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3868   
3869   /// ByteValues - For each byte of the result, we keep track of which value
3870   /// defines each byte.
3871   SmallVector<Value*, 8> ByteValues;
3872   ByteValues.resize(ITy->getBitWidth()/8);
3873     
3874   // Try to find all the pieces corresponding to the bswap.
3875   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3876       CollectBSwapParts(I.getOperand(1), ByteValues))
3877     return 0;
3878   
3879   // Check to see if all of the bytes come from the same value.
3880   Value *V = ByteValues[0];
3881   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3882   
3883   // Check to make sure that all of the bytes come from the same value.
3884   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3885     if (ByteValues[i] != V)
3886       return 0;
3887   const Type *Tys[] = { ITy };
3888   Module *M = I.getParent()->getParent()->getParent();
3889   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3890   return new CallInst(F, V);
3891 }
3892
3893
3894 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3895   bool Changed = SimplifyCommutative(I);
3896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3897
3898   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3899     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3900
3901   // or X, X = X
3902   if (Op0 == Op1)
3903     return ReplaceInstUsesWith(I, Op0);
3904
3905   // See if we can simplify any instructions used by the instruction whose sole 
3906   // purpose is to compute bits we don't care about.
3907   if (!isa<VectorType>(I.getType())) {
3908     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3909     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3910     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3911                              KnownZero, KnownOne))
3912       return &I;
3913   } else if (isa<ConstantAggregateZero>(Op1)) {
3914     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3915   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3916     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3917       return ReplaceInstUsesWith(I, I.getOperand(1));
3918   }
3919     
3920
3921   
3922   // or X, -1 == -1
3923   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3924     ConstantInt *C1 = 0; Value *X = 0;
3925     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3926     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3927       Instruction *Or = BinaryOperator::createOr(X, RHS);
3928       InsertNewInstBefore(Or, I);
3929       Or->takeName(Op0);
3930       return BinaryOperator::createAnd(Or, 
3931                ConstantInt::get(RHS->getValue() | C1->getValue()));
3932     }
3933
3934     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3935     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3936       Instruction *Or = BinaryOperator::createOr(X, RHS);
3937       InsertNewInstBefore(Or, I);
3938       Or->takeName(Op0);
3939       return BinaryOperator::createXor(Or,
3940                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3941     }
3942
3943     // Try to fold constant and into select arguments.
3944     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3945       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3946         return R;
3947     if (isa<PHINode>(Op0))
3948       if (Instruction *NV = FoldOpIntoPhi(I))
3949         return NV;
3950   }
3951
3952   Value *A = 0, *B = 0;
3953   ConstantInt *C1 = 0, *C2 = 0;
3954
3955   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3956     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3957       return ReplaceInstUsesWith(I, Op1);
3958   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3959     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3960       return ReplaceInstUsesWith(I, Op0);
3961
3962   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3963   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3964   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3965       match(Op1, m_Or(m_Value(), m_Value())) ||
3966       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3967        match(Op1, m_Shift(m_Value(), m_Value())))) {
3968     if (Instruction *BSwap = MatchBSwap(I))
3969       return BSwap;
3970   }
3971   
3972   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3973   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3974       MaskedValueIsZero(Op1, C1->getValue())) {
3975     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3976     InsertNewInstBefore(NOr, I);
3977     NOr->takeName(Op0);
3978     return BinaryOperator::createXor(NOr, C1);
3979   }
3980
3981   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3982   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3983       MaskedValueIsZero(Op0, C1->getValue())) {
3984     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3985     InsertNewInstBefore(NOr, I);
3986     NOr->takeName(Op0);
3987     return BinaryOperator::createXor(NOr, C1);
3988   }
3989
3990   // (A & C)|(B & D)
3991   Value *C = 0, *D = 0;
3992   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3993       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3994     Value *V1 = 0, *V2 = 0, *V3 = 0;
3995     C1 = dyn_cast<ConstantInt>(C);
3996     C2 = dyn_cast<ConstantInt>(D);
3997     if (C1 && C2) {  // (A & C1)|(B & C2)
3998       // If we have: ((V + N) & C1) | (V & C2)
3999       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4000       // replace with V+N.
4001       if (C1->getValue() == ~C2->getValue()) {
4002         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4003             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4004           // Add commutes, try both ways.
4005           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4006             return ReplaceInstUsesWith(I, A);
4007           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4008             return ReplaceInstUsesWith(I, A);
4009         }
4010         // Or commutes, try both ways.
4011         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4012             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4013           // Add commutes, try both ways.
4014           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4015             return ReplaceInstUsesWith(I, B);
4016           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4017             return ReplaceInstUsesWith(I, B);
4018         }
4019       }
4020       V1 = 0; V2 = 0; V3 = 0;
4021     }
4022     
4023     // Check to see if we have any common things being and'ed.  If so, find the
4024     // terms for V1 & (V2|V3).
4025     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4026       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4027         V1 = A, V2 = C, V3 = D;
4028       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4029         V1 = A, V2 = B, V3 = C;
4030       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4031         V1 = C, V2 = A, V3 = D;
4032       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4033         V1 = C, V2 = A, V3 = B;
4034       
4035       if (V1) {
4036         Value *Or =
4037           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4038         return BinaryOperator::createAnd(V1, Or);
4039       }
4040     }
4041   }
4042   
4043   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4044   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4045     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4046       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4047           SI0->getOperand(1) == SI1->getOperand(1) &&
4048           (SI0->hasOneUse() || SI1->hasOneUse())) {
4049         Instruction *NewOp =
4050         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4051                                                      SI1->getOperand(0),
4052                                                      SI0->getName()), I);
4053         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4054                                       SI1->getOperand(1));
4055       }
4056   }
4057
4058   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4059     if (A == Op1)   // ~A | A == -1
4060       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4061   } else {
4062     A = 0;
4063   }
4064   // Note, A is still live here!
4065   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4066     if (Op0 == B)
4067       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4068
4069     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4070     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4071       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4072                                               I.getName()+".demorgan"), I);
4073       return BinaryOperator::createNot(And);
4074     }
4075   }
4076
4077   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4078   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4079     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4080       return R;
4081
4082     Value *LHSVal, *RHSVal;
4083     ConstantInt *LHSCst, *RHSCst;
4084     ICmpInst::Predicate LHSCC, RHSCC;
4085     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4086       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4087         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4088             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4089             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4090             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4091             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4092             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4093             // We can't fold (ugt x, C) | (sgt x, C2).
4094             PredicatesFoldable(LHSCC, RHSCC)) {
4095           // Ensure that the larger constant is on the RHS.
4096           ICmpInst *LHS = cast<ICmpInst>(Op0);
4097           bool NeedsSwap;
4098           if (ICmpInst::isSignedPredicate(LHSCC))
4099             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4100           else
4101             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4102             
4103           if (NeedsSwap) {
4104             std::swap(LHS, RHS);
4105             std::swap(LHSCst, RHSCst);
4106             std::swap(LHSCC, RHSCC);
4107           }
4108
4109           // At this point, we know we have have two icmp instructions
4110           // comparing a value against two constants and or'ing the result
4111           // together.  Because of the above check, we know that we only have
4112           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4113           // FoldICmpLogical check above), that the two constants are not
4114           // equal.
4115           assert(LHSCst != RHSCst && "Compares not folded above?");
4116
4117           switch (LHSCC) {
4118           default: assert(0 && "Unknown integer condition code!");
4119           case ICmpInst::ICMP_EQ:
4120             switch (RHSCC) {
4121             default: assert(0 && "Unknown integer condition code!");
4122             case ICmpInst::ICMP_EQ:
4123               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4124                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4125                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4126                                                       LHSVal->getName()+".off");
4127                 InsertNewInstBefore(Add, I);
4128                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4129                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4130               }
4131               break;                         // (X == 13 | X == 15) -> no change
4132             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4133             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4134               break;
4135             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4136             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4137             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4138               return ReplaceInstUsesWith(I, RHS);
4139             }
4140             break;
4141           case ICmpInst::ICMP_NE:
4142             switch (RHSCC) {
4143             default: assert(0 && "Unknown integer condition code!");
4144             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4145             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4146             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4147               return ReplaceInstUsesWith(I, LHS);
4148             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4149             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4150             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4151               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4152             }
4153             break;
4154           case ICmpInst::ICMP_ULT:
4155             switch (RHSCC) {
4156             default: assert(0 && "Unknown integer condition code!");
4157             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4158               break;
4159             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4160               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4161               // this can cause overflow.
4162               if (RHSCst->isMaxValue(false))
4163                 return ReplaceInstUsesWith(I, LHS);
4164               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4165                                      false, I);
4166             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4167               break;
4168             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4169             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4170               return ReplaceInstUsesWith(I, RHS);
4171             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4172               break;
4173             }
4174             break;
4175           case ICmpInst::ICMP_SLT:
4176             switch (RHSCC) {
4177             default: assert(0 && "Unknown integer condition code!");
4178             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4179               break;
4180             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4181               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4182               // this can cause overflow.
4183               if (RHSCst->isMaxValue(true))
4184                 return ReplaceInstUsesWith(I, LHS);
4185               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4186                                      false, I);
4187             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4188               break;
4189             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4190             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4191               return ReplaceInstUsesWith(I, RHS);
4192             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4193               break;
4194             }
4195             break;
4196           case ICmpInst::ICMP_UGT:
4197             switch (RHSCC) {
4198             default: assert(0 && "Unknown integer condition code!");
4199             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4200             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4201               return ReplaceInstUsesWith(I, LHS);
4202             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4203               break;
4204             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4205             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4206               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4207             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4208               break;
4209             }
4210             break;
4211           case ICmpInst::ICMP_SGT:
4212             switch (RHSCC) {
4213             default: assert(0 && "Unknown integer condition code!");
4214             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4215             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4216               return ReplaceInstUsesWith(I, LHS);
4217             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4218               break;
4219             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4220             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4221               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4222             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4223               break;
4224             }
4225             break;
4226           }
4227         }
4228   }
4229     
4230   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4231   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4232     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4233       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4234         const Type *SrcTy = Op0C->getOperand(0)->getType();
4235         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4236             // Only do this if the casts both really cause code to be generated.
4237             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4238                               I.getType(), TD) &&
4239             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4240                               I.getType(), TD)) {
4241           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4242                                                         Op1C->getOperand(0),
4243                                                         I.getName());
4244           InsertNewInstBefore(NewOp, I);
4245           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4246         }
4247       }
4248   }
4249   
4250     
4251   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4252   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4253     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4254       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4255           RHS->getPredicate() == FCmpInst::FCMP_UNO)
4256         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4257           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4258             // If either of the constants are nans, then the whole thing returns
4259             // true.
4260             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4261               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4262             
4263             // Otherwise, no need to compare the two constants, compare the
4264             // rest.
4265             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4266                                 RHS->getOperand(0));
4267           }
4268     }
4269   }
4270
4271   return Changed ? &I : 0;
4272 }
4273
4274 // XorSelf - Implements: X ^ X --> 0
4275 struct XorSelf {
4276   Value *RHS;
4277   XorSelf(Value *rhs) : RHS(rhs) {}
4278   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4279   Instruction *apply(BinaryOperator &Xor) const {
4280     return &Xor;
4281   }
4282 };
4283
4284
4285 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4286   bool Changed = SimplifyCommutative(I);
4287   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4288
4289   if (isa<UndefValue>(Op1))
4290     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4291
4292   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4293   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4294     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4295     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4296   }
4297   
4298   // See if we can simplify any instructions used by the instruction whose sole 
4299   // purpose is to compute bits we don't care about.
4300   if (!isa<VectorType>(I.getType())) {
4301     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4302     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4303     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4304                              KnownZero, KnownOne))
4305       return &I;
4306   } else if (isa<ConstantAggregateZero>(Op1)) {
4307     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4308   }
4309
4310   // Is this a ~ operation?
4311   if (Value *NotOp = dyn_castNotVal(&I)) {
4312     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4313     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4314     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4315       if (Op0I->getOpcode() == Instruction::And || 
4316           Op0I->getOpcode() == Instruction::Or) {
4317         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4318         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4319           Instruction *NotY =
4320             BinaryOperator::createNot(Op0I->getOperand(1),
4321                                       Op0I->getOperand(1)->getName()+".not");
4322           InsertNewInstBefore(NotY, I);
4323           if (Op0I->getOpcode() == Instruction::And)
4324             return BinaryOperator::createOr(Op0NotVal, NotY);
4325           else
4326             return BinaryOperator::createAnd(Op0NotVal, NotY);
4327         }
4328       }
4329     }
4330   }
4331   
4332   
4333   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4334     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4335     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4336       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4337         return new ICmpInst(ICI->getInversePredicate(),
4338                             ICI->getOperand(0), ICI->getOperand(1));
4339
4340       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4341         return new FCmpInst(FCI->getInversePredicate(),
4342                             FCI->getOperand(0), FCI->getOperand(1));
4343     }
4344
4345     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4346       // ~(c-X) == X-c-1 == X+(-c-1)
4347       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4348         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4349           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4350           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4351                                               ConstantInt::get(I.getType(), 1));
4352           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4353         }
4354           
4355       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4356         if (Op0I->getOpcode() == Instruction::Add) {
4357           // ~(X-c) --> (-c-1)-X
4358           if (RHS->isAllOnesValue()) {
4359             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4360             return BinaryOperator::createSub(
4361                            ConstantExpr::getSub(NegOp0CI,
4362                                              ConstantInt::get(I.getType(), 1)),
4363                                           Op0I->getOperand(0));
4364           } else if (RHS->getValue().isSignBit()) {
4365             // (X + C) ^ signbit -> (X + C + signbit)
4366             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4367             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4368
4369           }
4370         } else if (Op0I->getOpcode() == Instruction::Or) {
4371           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4372           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4373             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4374             // Anything in both C1 and C2 is known to be zero, remove it from
4375             // NewRHS.
4376             Constant *CommonBits = And(Op0CI, RHS);
4377             NewRHS = ConstantExpr::getAnd(NewRHS, 
4378                                           ConstantExpr::getNot(CommonBits));
4379             AddToWorkList(Op0I);
4380             I.setOperand(0, Op0I->getOperand(0));
4381             I.setOperand(1, NewRHS);
4382             return &I;
4383           }
4384         }
4385     }
4386
4387     // Try to fold constant and into select arguments.
4388     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4389       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4390         return R;
4391     if (isa<PHINode>(Op0))
4392       if (Instruction *NV = FoldOpIntoPhi(I))
4393         return NV;
4394   }
4395
4396   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4397     if (X == Op1)
4398       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4399
4400   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4401     if (X == Op0)
4402       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4403
4404   
4405   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4406   if (Op1I) {
4407     Value *A, *B;
4408     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4409       if (A == Op0) {              // B^(B|A) == (A|B)^B
4410         Op1I->swapOperands();
4411         I.swapOperands();
4412         std::swap(Op0, Op1);
4413       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4414         I.swapOperands();     // Simplified below.
4415         std::swap(Op0, Op1);
4416       }
4417     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4418       if (Op0 == A)                                          // A^(A^B) == B
4419         return ReplaceInstUsesWith(I, B);
4420       else if (Op0 == B)                                     // A^(B^A) == B
4421         return ReplaceInstUsesWith(I, A);
4422     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4423       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4424         Op1I->swapOperands();
4425         std::swap(A, B);
4426       }
4427       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4428         I.swapOperands();     // Simplified below.
4429         std::swap(Op0, Op1);
4430       }
4431     }
4432   }
4433   
4434   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4435   if (Op0I) {
4436     Value *A, *B;
4437     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4438       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4439         std::swap(A, B);
4440       if (B == Op1) {                                // (A|B)^B == A & ~B
4441         Instruction *NotB =
4442           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4443         return BinaryOperator::createAnd(A, NotB);
4444       }
4445     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4446       if (Op1 == A)                                          // (A^B)^A == B
4447         return ReplaceInstUsesWith(I, B);
4448       else if (Op1 == B)                                     // (B^A)^A == B
4449         return ReplaceInstUsesWith(I, A);
4450     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4451       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4452         std::swap(A, B);
4453       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4454           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4455         Instruction *N =
4456           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4457         return BinaryOperator::createAnd(N, Op1);
4458       }
4459     }
4460   }
4461   
4462   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4463   if (Op0I && Op1I && Op0I->isShift() && 
4464       Op0I->getOpcode() == Op1I->getOpcode() && 
4465       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4466       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4467     Instruction *NewOp =
4468       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4469                                                     Op1I->getOperand(0),
4470                                                     Op0I->getName()), I);
4471     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4472                                   Op1I->getOperand(1));
4473   }
4474     
4475   if (Op0I && Op1I) {
4476     Value *A, *B, *C, *D;
4477     // (A & B)^(A | B) -> A ^ B
4478     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4479         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4480       if ((A == C && B == D) || (A == D && B == C)) 
4481         return BinaryOperator::createXor(A, B);
4482     }
4483     // (A | B)^(A & B) -> A ^ B
4484     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4485         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4486       if ((A == C && B == D) || (A == D && B == C)) 
4487         return BinaryOperator::createXor(A, B);
4488     }
4489     
4490     // (A & B)^(C & D)
4491     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4492         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4493         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4494       // (X & Y)^(X & Y) -> (Y^Z) & X
4495       Value *X = 0, *Y = 0, *Z = 0;
4496       if (A == C)
4497         X = A, Y = B, Z = D;
4498       else if (A == D)
4499         X = A, Y = B, Z = C;
4500       else if (B == C)
4501         X = B, Y = A, Z = D;
4502       else if (B == D)
4503         X = B, Y = A, Z = C;
4504       
4505       if (X) {
4506         Instruction *NewOp =
4507         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4508         return BinaryOperator::createAnd(NewOp, X);
4509       }
4510     }
4511   }
4512     
4513   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4514   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4515     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4516       return R;
4517
4518   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4519   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4520     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4521       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4522         const Type *SrcTy = Op0C->getOperand(0)->getType();
4523         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4524             // Only do this if the casts both really cause code to be generated.
4525             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4526                               I.getType(), TD) &&
4527             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4528                               I.getType(), TD)) {
4529           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4530                                                          Op1C->getOperand(0),
4531                                                          I.getName());
4532           InsertNewInstBefore(NewOp, I);
4533           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4534         }
4535       }
4536   }
4537   return Changed ? &I : 0;
4538 }
4539
4540 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4541 /// overflowed for this type.
4542 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4543                             ConstantInt *In2, bool IsSigned = false) {
4544   Result = cast<ConstantInt>(Add(In1, In2));
4545
4546   if (IsSigned)
4547     if (In2->getValue().isNegative())
4548       return Result->getValue().sgt(In1->getValue());
4549     else
4550       return Result->getValue().slt(In1->getValue());
4551   else
4552     return Result->getValue().ult(In1->getValue());
4553 }
4554
4555 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4556 /// code necessary to compute the offset from the base pointer (without adding
4557 /// in the base pointer).  Return the result as a signed integer of intptr size.
4558 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4559   TargetData &TD = IC.getTargetData();
4560   gep_type_iterator GTI = gep_type_begin(GEP);
4561   const Type *IntPtrTy = TD.getIntPtrType();
4562   Value *Result = Constant::getNullValue(IntPtrTy);
4563
4564   // Build a mask for high order bits.
4565   unsigned IntPtrWidth = TD.getPointerSize()*8;
4566   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4567
4568   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4569     Value *Op = GEP->getOperand(i);
4570     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4571     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4572       if (OpC->isZero()) continue;
4573       
4574       // Handle a struct index, which adds its field offset to the pointer.
4575       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4576         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4577         
4578         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4579           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4580         else
4581           Result = IC.InsertNewInstBefore(
4582                    BinaryOperator::createAdd(Result,
4583                                              ConstantInt::get(IntPtrTy, Size),
4584                                              GEP->getName()+".offs"), I);
4585         continue;
4586       }
4587       
4588       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4589       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4590       Scale = ConstantExpr::getMul(OC, Scale);
4591       if (Constant *RC = dyn_cast<Constant>(Result))
4592         Result = ConstantExpr::getAdd(RC, Scale);
4593       else {
4594         // Emit an add instruction.
4595         Result = IC.InsertNewInstBefore(
4596            BinaryOperator::createAdd(Result, Scale,
4597                                      GEP->getName()+".offs"), I);
4598       }
4599       continue;
4600     }
4601     // Convert to correct type.
4602     if (Op->getType() != IntPtrTy) {
4603       if (Constant *OpC = dyn_cast<Constant>(Op))
4604         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4605       else
4606         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4607                                                  Op->getName()+".c"), I);
4608     }
4609     if (Size != 1) {
4610       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4611       if (Constant *OpC = dyn_cast<Constant>(Op))
4612         Op = ConstantExpr::getMul(OpC, Scale);
4613       else    // We'll let instcombine(mul) convert this to a shl if possible.
4614         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4615                                                   GEP->getName()+".idx"), I);
4616     }
4617
4618     // Emit an add instruction.
4619     if (isa<Constant>(Op) && isa<Constant>(Result))
4620       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4621                                     cast<Constant>(Result));
4622     else
4623       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4624                                                   GEP->getName()+".offs"), I);
4625   }
4626   return Result;
4627 }
4628
4629 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4630 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4631 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4632                                        ICmpInst::Predicate Cond,
4633                                        Instruction &I) {
4634   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4635
4636   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4637     if (isa<PointerType>(CI->getOperand(0)->getType()))
4638       RHS = CI->getOperand(0);
4639
4640   Value *PtrBase = GEPLHS->getOperand(0);
4641   if (PtrBase == RHS) {
4642     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4643     // This transformation is valid because we know pointers can't overflow.
4644     Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4645     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4646                         Constant::getNullValue(Offset->getType()));
4647   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4648     // If the base pointers are different, but the indices are the same, just
4649     // compare the base pointer.
4650     if (PtrBase != GEPRHS->getOperand(0)) {
4651       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4652       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4653                         GEPRHS->getOperand(0)->getType();
4654       if (IndicesTheSame)
4655         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4656           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4657             IndicesTheSame = false;
4658             break;
4659           }
4660
4661       // If all indices are the same, just compare the base pointers.
4662       if (IndicesTheSame)
4663         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4664                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4665
4666       // Otherwise, the base pointers are different and the indices are
4667       // different, bail out.
4668       return 0;
4669     }
4670
4671     // If one of the GEPs has all zero indices, recurse.
4672     bool AllZeros = true;
4673     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4674       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4675           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4676         AllZeros = false;
4677         break;
4678       }
4679     if (AllZeros)
4680       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4681                           ICmpInst::getSwappedPredicate(Cond), I);
4682
4683     // If the other GEP has all zero indices, recurse.
4684     AllZeros = true;
4685     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4686       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4687           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4688         AllZeros = false;
4689         break;
4690       }
4691     if (AllZeros)
4692       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4693
4694     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4695       // If the GEPs only differ by one index, compare it.
4696       unsigned NumDifferences = 0;  // Keep track of # differences.
4697       unsigned DiffOperand = 0;     // The operand that differs.
4698       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4699         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4700           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4701                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4702             // Irreconcilable differences.
4703             NumDifferences = 2;
4704             break;
4705           } else {
4706             if (NumDifferences++) break;
4707             DiffOperand = i;
4708           }
4709         }
4710
4711       if (NumDifferences == 0)   // SAME GEP?
4712         return ReplaceInstUsesWith(I, // No comparison is needed here.
4713                                    ConstantInt::get(Type::Int1Ty,
4714                                                     isTrueWhenEqual(Cond)));
4715
4716       else if (NumDifferences == 1) {
4717         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4718         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4719         // Make sure we do a signed comparison here.
4720         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4721       }
4722     }
4723
4724     // Only lower this if the icmp is the only user of the GEP or if we expect
4725     // the result to fold to a constant!
4726     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4727         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4728       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4729       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4730       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4731       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4732     }
4733   }
4734   return 0;
4735 }
4736
4737 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4738   bool Changed = SimplifyCompare(I);
4739   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4740
4741   // Fold trivial predicates.
4742   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4743     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4744   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4745     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4746   
4747   // Simplify 'fcmp pred X, X'
4748   if (Op0 == Op1) {
4749     switch (I.getPredicate()) {
4750     default: assert(0 && "Unknown predicate!");
4751     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4752     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4753     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4754       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4755     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4756     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4757     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4758       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4759       
4760     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4761     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4762     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4763     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4764       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4765       I.setPredicate(FCmpInst::FCMP_UNO);
4766       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4767       return &I;
4768       
4769     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4770     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4771     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4772     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4773       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4774       I.setPredicate(FCmpInst::FCMP_ORD);
4775       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4776       return &I;
4777     }
4778   }
4779     
4780   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4781     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4782
4783   // Handle fcmp with constant RHS
4784   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4785     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4786       switch (LHSI->getOpcode()) {
4787       case Instruction::PHI:
4788         if (Instruction *NV = FoldOpIntoPhi(I))
4789           return NV;
4790         break;
4791       case Instruction::Select:
4792         // If either operand of the select is a constant, we can fold the
4793         // comparison into the select arms, which will cause one to be
4794         // constant folded and the select turned into a bitwise or.
4795         Value *Op1 = 0, *Op2 = 0;
4796         if (LHSI->hasOneUse()) {
4797           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4798             // Fold the known value into the constant operand.
4799             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4800             // Insert a new FCmp of the other select operand.
4801             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4802                                                       LHSI->getOperand(2), RHSC,
4803                                                       I.getName()), I);
4804           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4805             // Fold the known value into the constant operand.
4806             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4807             // Insert a new FCmp of the other select operand.
4808             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4809                                                       LHSI->getOperand(1), RHSC,
4810                                                       I.getName()), I);
4811           }
4812         }
4813
4814         if (Op1)
4815           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4816         break;
4817       }
4818   }
4819
4820   return Changed ? &I : 0;
4821 }
4822
4823 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4824   bool Changed = SimplifyCompare(I);
4825   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4826   const Type *Ty = Op0->getType();
4827
4828   // icmp X, X
4829   if (Op0 == Op1)
4830     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4831                                                    isTrueWhenEqual(I)));
4832
4833   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4834     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4835   
4836   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4837   // addresses never equal each other!  We already know that Op0 != Op1.
4838   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4839        isa<ConstantPointerNull>(Op0)) &&
4840       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4841        isa<ConstantPointerNull>(Op1)))
4842     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4843                                                    !isTrueWhenEqual(I)));
4844
4845   // icmp's with boolean values can always be turned into bitwise operations
4846   if (Ty == Type::Int1Ty) {
4847     switch (I.getPredicate()) {
4848     default: assert(0 && "Invalid icmp instruction!");
4849     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4850       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4851       InsertNewInstBefore(Xor, I);
4852       return BinaryOperator::createNot(Xor);
4853     }
4854     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4855       return BinaryOperator::createXor(Op0, Op1);
4856
4857     case ICmpInst::ICMP_UGT:
4858     case ICmpInst::ICMP_SGT:
4859       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4860       // FALL THROUGH
4861     case ICmpInst::ICMP_ULT:
4862     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4863       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4864       InsertNewInstBefore(Not, I);
4865       return BinaryOperator::createAnd(Not, Op1);
4866     }
4867     case ICmpInst::ICMP_UGE:
4868     case ICmpInst::ICMP_SGE:
4869       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4870       // FALL THROUGH
4871     case ICmpInst::ICMP_ULE:
4872     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4873       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4874       InsertNewInstBefore(Not, I);
4875       return BinaryOperator::createOr(Not, Op1);
4876     }
4877     }
4878   }
4879
4880   // See if we are doing a comparison between a constant and an instruction that
4881   // can be folded into the comparison.
4882   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4883       Value *A, *B;
4884     
4885     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4886     if (I.isEquality() && CI->isNullValue() &&
4887         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4888       // (icmp cond A B) if cond is equality
4889       return new ICmpInst(I.getPredicate(), A, B);
4890     }
4891     
4892     switch (I.getPredicate()) {
4893     default: break;
4894     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4895       if (CI->isMinValue(false))
4896         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4897       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4898         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4899       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4900         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4901       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4902       if (CI->isMinValue(true))
4903         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4904                             ConstantInt::getAllOnesValue(Op0->getType()));
4905           
4906       break;
4907
4908     case ICmpInst::ICMP_SLT:
4909       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4910         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4911       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4912         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4913       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4914         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4915       break;
4916
4917     case ICmpInst::ICMP_UGT:
4918       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4919         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4920       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4921         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4922       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4923         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4924         
4925       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4926       if (CI->isMaxValue(true))
4927         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4928                             ConstantInt::getNullValue(Op0->getType()));
4929       break;
4930
4931     case ICmpInst::ICMP_SGT:
4932       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4933         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4934       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4935         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4936       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4937         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4938       break;
4939
4940     case ICmpInst::ICMP_ULE:
4941       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4942         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4943       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4944         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4945       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4946         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4947       break;
4948
4949     case ICmpInst::ICMP_SLE:
4950       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4951         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4952       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4953         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4954       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4955         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4956       break;
4957
4958     case ICmpInst::ICMP_UGE:
4959       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4960         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4961       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4962         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4963       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4964         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4965       break;
4966
4967     case ICmpInst::ICMP_SGE:
4968       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4969         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4970       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4971         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4972       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4973         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4974       break;
4975     }
4976
4977     // If we still have a icmp le or icmp ge instruction, turn it into the
4978     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4979     // already been handled above, this requires little checking.
4980     //
4981     switch (I.getPredicate()) {
4982     default: break;
4983     case ICmpInst::ICMP_ULE: 
4984       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4985     case ICmpInst::ICMP_SLE:
4986       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4987     case ICmpInst::ICMP_UGE:
4988       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4989     case ICmpInst::ICMP_SGE:
4990       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4991     }
4992     
4993     // See if we can fold the comparison based on bits known to be zero or one
4994     // in the input.  If this comparison is a normal comparison, it demands all
4995     // bits, if it is a sign bit comparison, it only demands the sign bit.
4996     
4997     bool UnusedBit;
4998     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4999     
5000     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5001     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5002     if (SimplifyDemandedBits(Op0, 
5003                              isSignBit ? APInt::getSignBit(BitWidth)
5004                                        : APInt::getAllOnesValue(BitWidth),
5005                              KnownZero, KnownOne, 0))
5006       return &I;
5007         
5008     // Given the known and unknown bits, compute a range that the LHS could be
5009     // in.
5010     if ((KnownOne | KnownZero) != 0) {
5011       // Compute the Min, Max and RHS values based on the known bits. For the
5012       // EQ and NE we use unsigned values.
5013       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5014       const APInt& RHSVal = CI->getValue();
5015       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5016         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5017                                                Max);
5018       } else {
5019         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5020                                                  Max);
5021       }
5022       switch (I.getPredicate()) {  // LE/GE have been folded already.
5023       default: assert(0 && "Unknown icmp opcode!");
5024       case ICmpInst::ICMP_EQ:
5025         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5026           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5027         break;
5028       case ICmpInst::ICMP_NE:
5029         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5030           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5031         break;
5032       case ICmpInst::ICMP_ULT:
5033         if (Max.ult(RHSVal))
5034           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5035         if (Min.uge(RHSVal))
5036           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5037         break;
5038       case ICmpInst::ICMP_UGT:
5039         if (Min.ugt(RHSVal))
5040           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5041         if (Max.ule(RHSVal))
5042           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5043         break;
5044       case ICmpInst::ICMP_SLT:
5045         if (Max.slt(RHSVal))
5046           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5047         if (Min.sgt(RHSVal))
5048           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5049         break;
5050       case ICmpInst::ICMP_SGT: 
5051         if (Min.sgt(RHSVal))
5052           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5053         if (Max.sle(RHSVal))
5054           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5055         break;
5056       }
5057     }
5058           
5059     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5060     // instruction, see if that instruction also has constants so that the 
5061     // instruction can be folded into the icmp 
5062     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5063       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5064         return Res;
5065   }
5066
5067   // Handle icmp with constant (but not simple integer constant) RHS
5068   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5069     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5070       switch (LHSI->getOpcode()) {
5071       case Instruction::GetElementPtr:
5072         if (RHSC->isNullValue()) {
5073           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5074           bool isAllZeros = true;
5075           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5076             if (!isa<Constant>(LHSI->getOperand(i)) ||
5077                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5078               isAllZeros = false;
5079               break;
5080             }
5081           if (isAllZeros)
5082             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5083                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5084         }
5085         break;
5086
5087       case Instruction::PHI:
5088         if (Instruction *NV = FoldOpIntoPhi(I))
5089           return NV;
5090         break;
5091       case Instruction::Select: {
5092         // If either operand of the select is a constant, we can fold the
5093         // comparison into the select arms, which will cause one to be
5094         // constant folded and the select turned into a bitwise or.
5095         Value *Op1 = 0, *Op2 = 0;
5096         if (LHSI->hasOneUse()) {
5097           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5098             // Fold the known value into the constant operand.
5099             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5100             // Insert a new ICmp of the other select operand.
5101             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5102                                                    LHSI->getOperand(2), RHSC,
5103                                                    I.getName()), I);
5104           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5105             // Fold the known value into the constant operand.
5106             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5107             // Insert a new ICmp of the other select operand.
5108             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5109                                                    LHSI->getOperand(1), RHSC,
5110                                                    I.getName()), I);
5111           }
5112         }
5113
5114         if (Op1)
5115           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5116         break;
5117       }
5118       case Instruction::Malloc:
5119         // If we have (malloc != null), and if the malloc has a single use, we
5120         // can assume it is successful and remove the malloc.
5121         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5122           AddToWorkList(LHSI);
5123           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5124                                                          !isTrueWhenEqual(I)));
5125         }
5126         break;
5127       }
5128   }
5129
5130   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5131   if (User *GEP = dyn_castGetElementPtr(Op0))
5132     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5133       return NI;
5134   if (User *GEP = dyn_castGetElementPtr(Op1))
5135     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5136                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5137       return NI;
5138
5139   // Test to see if the operands of the icmp are casted versions of other
5140   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5141   // now.
5142   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5143     if (isa<PointerType>(Op0->getType()) && 
5144         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5145       // We keep moving the cast from the left operand over to the right
5146       // operand, where it can often be eliminated completely.
5147       Op0 = CI->getOperand(0);
5148
5149       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5150       // so eliminate it as well.
5151       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5152         Op1 = CI2->getOperand(0);
5153
5154       // If Op1 is a constant, we can fold the cast into the constant.
5155       if (Op0->getType() != Op1->getType())
5156         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5157           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5158         } else {
5159           // Otherwise, cast the RHS right before the icmp
5160           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5161         }
5162       return new ICmpInst(I.getPredicate(), Op0, Op1);
5163     }
5164   }
5165   
5166   if (isa<CastInst>(Op0)) {
5167     // Handle the special case of: icmp (cast bool to X), <cst>
5168     // This comes up when you have code like
5169     //   int X = A < B;
5170     //   if (X) ...
5171     // For generality, we handle any zero-extension of any operand comparison
5172     // with a constant or another cast from the same type.
5173     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5174       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5175         return R;
5176   }
5177   
5178   if (I.isEquality()) {
5179     Value *A, *B, *C, *D;
5180     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5181       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5182         Value *OtherVal = A == Op1 ? B : A;
5183         return new ICmpInst(I.getPredicate(), OtherVal,
5184                             Constant::getNullValue(A->getType()));
5185       }
5186
5187       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5188         // A^c1 == C^c2 --> A == C^(c1^c2)
5189         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5190           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5191             if (Op1->hasOneUse()) {
5192               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5193               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5194               return new ICmpInst(I.getPredicate(), A,
5195                                   InsertNewInstBefore(Xor, I));
5196             }
5197         
5198         // A^B == A^D -> B == D
5199         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5200         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5201         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5202         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5203       }
5204     }
5205     
5206     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5207         (A == Op0 || B == Op0)) {
5208       // A == (A^B)  ->  B == 0
5209       Value *OtherVal = A == Op0 ? B : A;
5210       return new ICmpInst(I.getPredicate(), OtherVal,
5211                           Constant::getNullValue(A->getType()));
5212     }
5213     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5214       // (A-B) == A  ->  B == 0
5215       return new ICmpInst(I.getPredicate(), B,
5216                           Constant::getNullValue(B->getType()));
5217     }
5218     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5219       // A == (A-B)  ->  B == 0
5220       return new ICmpInst(I.getPredicate(), B,
5221                           Constant::getNullValue(B->getType()));
5222     }
5223     
5224     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5225     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5226         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5227         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5228       Value *X = 0, *Y = 0, *Z = 0;
5229       
5230       if (A == C) {
5231         X = B; Y = D; Z = A;
5232       } else if (A == D) {
5233         X = B; Y = C; Z = A;
5234       } else if (B == C) {
5235         X = A; Y = D; Z = B;
5236       } else if (B == D) {
5237         X = A; Y = C; Z = B;
5238       }
5239       
5240       if (X) {   // Build (X^Y) & Z
5241         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5242         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5243         I.setOperand(0, Op1);
5244         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5245         return &I;
5246       }
5247     }
5248   }
5249   return Changed ? &I : 0;
5250 }
5251
5252
5253 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5254 /// and CmpRHS are both known to be integer constants.
5255 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5256                                           ConstantInt *DivRHS) {
5257   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5258   const APInt &CmpRHSV = CmpRHS->getValue();
5259   
5260   // FIXME: If the operand types don't match the type of the divide 
5261   // then don't attempt this transform. The code below doesn't have the
5262   // logic to deal with a signed divide and an unsigned compare (and
5263   // vice versa). This is because (x /s C1) <s C2  produces different 
5264   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5265   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5266   // work. :(  The if statement below tests that condition and bails 
5267   // if it finds it. 
5268   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5269   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5270     return 0;
5271   if (DivRHS->isZero())
5272     return 0; // The ProdOV computation fails on divide by zero.
5273
5274   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5275   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5276   // C2 (CI). By solving for X we can turn this into a range check 
5277   // instead of computing a divide. 
5278   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5279
5280   // Determine if the product overflows by seeing if the product is
5281   // not equal to the divide. Make sure we do the same kind of divide
5282   // as in the LHS instruction that we're folding. 
5283   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5284                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5285
5286   // Get the ICmp opcode
5287   ICmpInst::Predicate Pred = ICI.getPredicate();
5288
5289   // Figure out the interval that is being checked.  For example, a comparison
5290   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5291   // Compute this interval based on the constants involved and the signedness of
5292   // the compare/divide.  This computes a half-open interval, keeping track of
5293   // whether either value in the interval overflows.  After analysis each
5294   // overflow variable is set to 0 if it's corresponding bound variable is valid
5295   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5296   int LoOverflow = 0, HiOverflow = 0;
5297   ConstantInt *LoBound = 0, *HiBound = 0;
5298   
5299   
5300   if (!DivIsSigned) {  // udiv
5301     // e.g. X/5 op 3  --> [15, 20)
5302     LoBound = Prod;
5303     HiOverflow = LoOverflow = ProdOV;
5304     if (!HiOverflow)
5305       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5306   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5307     if (CmpRHSV == 0) {       // (X / pos) op 0
5308       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5309       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5310       HiBound = DivRHS;
5311     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5312       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5313       HiOverflow = LoOverflow = ProdOV;
5314       if (!HiOverflow)
5315         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5316     } else {                       // (X / pos) op neg
5317       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5318       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5319       LoOverflow = AddWithOverflow(LoBound, Prod,
5320                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5321       HiBound = AddOne(Prod);
5322       HiOverflow = ProdOV ? -1 : 0;
5323     }
5324   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5325     if (CmpRHSV == 0) {       // (X / neg) op 0
5326       // e.g. X/-5 op 0  --> [-4, 5)
5327       LoBound = AddOne(DivRHS);
5328       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5329       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5330         HiOverflow = 1;            // [INTMIN+1, overflow)
5331         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5332       }
5333     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5334       // e.g. X/-5 op 3  --> [-19, -14)
5335       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5336       if (!LoOverflow)
5337         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5338       HiBound = AddOne(Prod);
5339     } else {                       // (X / neg) op neg
5340       // e.g. X/-5 op -3  --> [15, 20)
5341       LoBound = Prod;
5342       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5343       HiBound = Subtract(Prod, DivRHS);
5344     }
5345     
5346     // Dividing by a negative swaps the condition.  LT <-> GT
5347     Pred = ICmpInst::getSwappedPredicate(Pred);
5348   }
5349
5350   Value *X = DivI->getOperand(0);
5351   switch (Pred) {
5352   default: assert(0 && "Unhandled icmp opcode!");
5353   case ICmpInst::ICMP_EQ:
5354     if (LoOverflow && HiOverflow)
5355       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5356     else if (HiOverflow)
5357       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5358                           ICmpInst::ICMP_UGE, X, LoBound);
5359     else if (LoOverflow)
5360       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5361                           ICmpInst::ICMP_ULT, X, HiBound);
5362     else
5363       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5364   case ICmpInst::ICMP_NE:
5365     if (LoOverflow && HiOverflow)
5366       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5367     else if (HiOverflow)
5368       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5369                           ICmpInst::ICMP_ULT, X, LoBound);
5370     else if (LoOverflow)
5371       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5372                           ICmpInst::ICMP_UGE, X, HiBound);
5373     else
5374       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5375   case ICmpInst::ICMP_ULT:
5376   case ICmpInst::ICMP_SLT:
5377     if (LoOverflow == +1)   // Low bound is greater than input range.
5378       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5379     if (LoOverflow == -1)   // Low bound is less than input range.
5380       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5381     return new ICmpInst(Pred, X, LoBound);
5382   case ICmpInst::ICMP_UGT:
5383   case ICmpInst::ICMP_SGT:
5384     if (HiOverflow == +1)       // High bound greater than input range.
5385       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5386     else if (HiOverflow == -1)  // High bound less than input range.
5387       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5388     if (Pred == ICmpInst::ICMP_UGT)
5389       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5390     else
5391       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5392   }
5393 }
5394
5395
5396 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5397 ///
5398 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5399                                                           Instruction *LHSI,
5400                                                           ConstantInt *RHS) {
5401   const APInt &RHSV = RHS->getValue();
5402   
5403   switch (LHSI->getOpcode()) {
5404   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5405     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5406       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5407       // fold the xor.
5408       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5409           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5410         Value *CompareVal = LHSI->getOperand(0);
5411         
5412         // If the sign bit of the XorCST is not set, there is no change to
5413         // the operation, just stop using the Xor.
5414         if (!XorCST->getValue().isNegative()) {
5415           ICI.setOperand(0, CompareVal);
5416           AddToWorkList(LHSI);
5417           return &ICI;
5418         }
5419         
5420         // Was the old condition true if the operand is positive?
5421         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5422         
5423         // If so, the new one isn't.
5424         isTrueIfPositive ^= true;
5425         
5426         if (isTrueIfPositive)
5427           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5428         else
5429           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5430       }
5431     }
5432     break;
5433   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5434     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5435         LHSI->getOperand(0)->hasOneUse()) {
5436       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5437       
5438       // If the LHS is an AND of a truncating cast, we can widen the
5439       // and/compare to be the input width without changing the value
5440       // produced, eliminating a cast.
5441       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5442         // We can do this transformation if either the AND constant does not
5443         // have its sign bit set or if it is an equality comparison. 
5444         // Extending a relational comparison when we're checking the sign
5445         // bit would not work.
5446         if (Cast->hasOneUse() &&
5447             (ICI.isEquality() || AndCST->getValue().isNonNegative() && 
5448              RHSV.isNonNegative())) {
5449           uint32_t BitWidth = 
5450             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5451           APInt NewCST = AndCST->getValue();
5452           NewCST.zext(BitWidth);
5453           APInt NewCI = RHSV;
5454           NewCI.zext(BitWidth);
5455           Instruction *NewAnd = 
5456             BinaryOperator::createAnd(Cast->getOperand(0),
5457                                       ConstantInt::get(NewCST),LHSI->getName());
5458           InsertNewInstBefore(NewAnd, ICI);
5459           return new ICmpInst(ICI.getPredicate(), NewAnd,
5460                               ConstantInt::get(NewCI));
5461         }
5462       }
5463       
5464       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5465       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5466       // happens a LOT in code produced by the C front-end, for bitfield
5467       // access.
5468       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5469       if (Shift && !Shift->isShift())
5470         Shift = 0;
5471       
5472       ConstantInt *ShAmt;
5473       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5474       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5475       const Type *AndTy = AndCST->getType();          // Type of the and.
5476       
5477       // We can fold this as long as we can't shift unknown bits
5478       // into the mask.  This can only happen with signed shift
5479       // rights, as they sign-extend.
5480       if (ShAmt) {
5481         bool CanFold = Shift->isLogicalShift();
5482         if (!CanFold) {
5483           // To test for the bad case of the signed shr, see if any
5484           // of the bits shifted in could be tested after the mask.
5485           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5486           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5487           
5488           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5489           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5490                AndCST->getValue()) == 0)
5491             CanFold = true;
5492         }
5493         
5494         if (CanFold) {
5495           Constant *NewCst;
5496           if (Shift->getOpcode() == Instruction::Shl)
5497             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5498           else
5499             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5500           
5501           // Check to see if we are shifting out any of the bits being
5502           // compared.
5503           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5504             // If we shifted bits out, the fold is not going to work out.
5505             // As a special case, check to see if this means that the
5506             // result is always true or false now.
5507             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5508               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5509             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5510               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5511           } else {
5512             ICI.setOperand(1, NewCst);
5513             Constant *NewAndCST;
5514             if (Shift->getOpcode() == Instruction::Shl)
5515               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5516             else
5517               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5518             LHSI->setOperand(1, NewAndCST);
5519             LHSI->setOperand(0, Shift->getOperand(0));
5520             AddToWorkList(Shift); // Shift is dead.
5521             AddUsesToWorkList(ICI);
5522             return &ICI;
5523           }
5524         }
5525       }
5526       
5527       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5528       // preferable because it allows the C<<Y expression to be hoisted out
5529       // of a loop if Y is invariant and X is not.
5530       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5531           ICI.isEquality() && !Shift->isArithmeticShift() &&
5532           isa<Instruction>(Shift->getOperand(0))) {
5533         // Compute C << Y.
5534         Value *NS;
5535         if (Shift->getOpcode() == Instruction::LShr) {
5536           NS = BinaryOperator::createShl(AndCST, 
5537                                          Shift->getOperand(1), "tmp");
5538         } else {
5539           // Insert a logical shift.
5540           NS = BinaryOperator::createLShr(AndCST,
5541                                           Shift->getOperand(1), "tmp");
5542         }
5543         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5544         
5545         // Compute X & (C << Y).
5546         Instruction *NewAnd = 
5547           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5548         InsertNewInstBefore(NewAnd, ICI);
5549         
5550         ICI.setOperand(0, NewAnd);
5551         return &ICI;
5552       }
5553     }
5554     break;
5555     
5556   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5557     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5558     if (!ShAmt) break;
5559     
5560     uint32_t TypeBits = RHSV.getBitWidth();
5561     
5562     // Check that the shift amount is in range.  If not, don't perform
5563     // undefined shifts.  When the shift is visited it will be
5564     // simplified.
5565     if (ShAmt->uge(TypeBits))
5566       break;
5567     
5568     if (ICI.isEquality()) {
5569       // If we are comparing against bits always shifted out, the
5570       // comparison cannot succeed.
5571       Constant *Comp =
5572         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5573       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5574         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5575         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5576         return ReplaceInstUsesWith(ICI, Cst);
5577       }
5578       
5579       if (LHSI->hasOneUse()) {
5580         // Otherwise strength reduce the shift into an and.
5581         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5582         Constant *Mask =
5583           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5584         
5585         Instruction *AndI =
5586           BinaryOperator::createAnd(LHSI->getOperand(0),
5587                                     Mask, LHSI->getName()+".mask");
5588         Value *And = InsertNewInstBefore(AndI, ICI);
5589         return new ICmpInst(ICI.getPredicate(), And,
5590                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5591       }
5592     }
5593     
5594     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5595     bool TrueIfSigned = false;
5596     if (LHSI->hasOneUse() &&
5597         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5598       // (X << 31) <s 0  --> (X&1) != 0
5599       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5600                                            (TypeBits-ShAmt->getZExtValue()-1));
5601       Instruction *AndI =
5602         BinaryOperator::createAnd(LHSI->getOperand(0),
5603                                   Mask, LHSI->getName()+".mask");
5604       Value *And = InsertNewInstBefore(AndI, ICI);
5605       
5606       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5607                           And, Constant::getNullValue(And->getType()));
5608     }
5609     break;
5610   }
5611     
5612   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5613   case Instruction::AShr: {
5614     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5615     if (!ShAmt) break;
5616
5617     if (ICI.isEquality()) {
5618       // Check that the shift amount is in range.  If not, don't perform
5619       // undefined shifts.  When the shift is visited it will be
5620       // simplified.
5621       uint32_t TypeBits = RHSV.getBitWidth();
5622       if (ShAmt->uge(TypeBits))
5623         break;
5624       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5625       
5626       // If we are comparing against bits always shifted out, the
5627       // comparison cannot succeed.
5628       APInt Comp = RHSV << ShAmtVal;
5629       if (LHSI->getOpcode() == Instruction::LShr)
5630         Comp = Comp.lshr(ShAmtVal);
5631       else
5632         Comp = Comp.ashr(ShAmtVal);
5633       
5634       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5635         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5636         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5637         return ReplaceInstUsesWith(ICI, Cst);
5638       }
5639       
5640       if (LHSI->hasOneUse() || RHSV == 0) {
5641         // Otherwise strength reduce the shift into an and.
5642         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5643         Constant *Mask = ConstantInt::get(Val);
5644         
5645         Instruction *AndI =
5646           BinaryOperator::createAnd(LHSI->getOperand(0),
5647                                     Mask, LHSI->getName()+".mask");
5648         Value *And = InsertNewInstBefore(AndI, ICI);
5649         return new ICmpInst(ICI.getPredicate(), And,
5650                             ConstantExpr::getShl(RHS, ShAmt));
5651       }
5652     }
5653     break;
5654   }
5655     
5656   case Instruction::SDiv:
5657   case Instruction::UDiv:
5658     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5659     // Fold this div into the comparison, producing a range check. 
5660     // Determine, based on the divide type, what the range is being 
5661     // checked.  If there is an overflow on the low or high side, remember 
5662     // it, otherwise compute the range [low, hi) bounding the new value.
5663     // See: InsertRangeTest above for the kinds of replacements possible.
5664     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5665       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5666                                           DivRHS))
5667         return R;
5668     break;
5669
5670   case Instruction::Add:
5671     // Fold: icmp pred (add, X, C1), C2
5672
5673     if (!ICI.isEquality()) {
5674       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5675       if (!LHSC) break;
5676       const APInt &LHSV = LHSC->getValue();
5677
5678       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5679                             .subtract(LHSV);
5680
5681       if (ICI.isSignedPredicate()) {
5682         if (CR.getLower().isSignBit()) {
5683           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5684                               ConstantInt::get(CR.getUpper()));
5685         } else if (CR.getUpper().isSignBit()) {
5686           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5687                               ConstantInt::get(CR.getLower()));
5688         }
5689       } else {
5690         if (CR.getLower().isMinValue()) {
5691           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5692                               ConstantInt::get(CR.getUpper()));
5693         } else if (CR.getUpper().isMinValue()) {
5694           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5695                               ConstantInt::get(CR.getLower()));
5696         }
5697       }
5698     }
5699     break;
5700   }
5701   
5702   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5703   if (ICI.isEquality()) {
5704     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5705     
5706     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5707     // the second operand is a constant, simplify a bit.
5708     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5709       switch (BO->getOpcode()) {
5710       case Instruction::SRem:
5711         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5712         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5713           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5714           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5715             Instruction *NewRem =
5716               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5717                                          BO->getName());
5718             InsertNewInstBefore(NewRem, ICI);
5719             return new ICmpInst(ICI.getPredicate(), NewRem, 
5720                                 Constant::getNullValue(BO->getType()));
5721           }
5722         }
5723         break;
5724       case Instruction::Add:
5725         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5726         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5727           if (BO->hasOneUse())
5728             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5729                                 Subtract(RHS, BOp1C));
5730         } else if (RHSV == 0) {
5731           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5732           // efficiently invertible, or if the add has just this one use.
5733           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5734           
5735           if (Value *NegVal = dyn_castNegVal(BOp1))
5736             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5737           else if (Value *NegVal = dyn_castNegVal(BOp0))
5738             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5739           else if (BO->hasOneUse()) {
5740             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5741             InsertNewInstBefore(Neg, ICI);
5742             Neg->takeName(BO);
5743             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5744           }
5745         }
5746         break;
5747       case Instruction::Xor:
5748         // For the xor case, we can xor two constants together, eliminating
5749         // the explicit xor.
5750         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5751           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5752                               ConstantExpr::getXor(RHS, BOC));
5753         
5754         // FALLTHROUGH
5755       case Instruction::Sub:
5756         // Replace (([sub|xor] A, B) != 0) with (A != B)
5757         if (RHSV == 0)
5758           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5759                               BO->getOperand(1));
5760         break;
5761         
5762       case Instruction::Or:
5763         // If bits are being or'd in that are not present in the constant we
5764         // are comparing against, then the comparison could never succeed!
5765         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5766           Constant *NotCI = ConstantExpr::getNot(RHS);
5767           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5768             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5769                                                              isICMP_NE));
5770         }
5771         break;
5772         
5773       case Instruction::And:
5774         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5775           // If bits are being compared against that are and'd out, then the
5776           // comparison can never succeed!
5777           if ((RHSV & ~BOC->getValue()) != 0)
5778             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5779                                                              isICMP_NE));
5780           
5781           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5782           if (RHS == BOC && RHSV.isPowerOf2())
5783             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5784                                 ICmpInst::ICMP_NE, LHSI,
5785                                 Constant::getNullValue(RHS->getType()));
5786           
5787           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5788           if (isSignBit(BOC)) {
5789             Value *X = BO->getOperand(0);
5790             Constant *Zero = Constant::getNullValue(X->getType());
5791             ICmpInst::Predicate pred = isICMP_NE ? 
5792               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5793             return new ICmpInst(pred, X, Zero);
5794           }
5795           
5796           // ((X & ~7) == 0) --> X < 8
5797           if (RHSV == 0 && isHighOnes(BOC)) {
5798             Value *X = BO->getOperand(0);
5799             Constant *NegX = ConstantExpr::getNeg(BOC);
5800             ICmpInst::Predicate pred = isICMP_NE ? 
5801               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5802             return new ICmpInst(pred, X, NegX);
5803           }
5804         }
5805       default: break;
5806       }
5807     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5808       // Handle icmp {eq|ne} <intrinsic>, intcst.
5809       if (II->getIntrinsicID() == Intrinsic::bswap) {
5810         AddToWorkList(II);
5811         ICI.setOperand(0, II->getOperand(1));
5812         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5813         return &ICI;
5814       }
5815     }
5816   } else {  // Not a ICMP_EQ/ICMP_NE
5817             // If the LHS is a cast from an integral value of the same size, 
5818             // then since we know the RHS is a constant, try to simlify.
5819     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5820       Value *CastOp = Cast->getOperand(0);
5821       const Type *SrcTy = CastOp->getType();
5822       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5823       if (SrcTy->isInteger() && 
5824           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5825         // If this is an unsigned comparison, try to make the comparison use
5826         // smaller constant values.
5827         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5828           // X u< 128 => X s> -1
5829           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5830                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5831         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5832                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5833           // X u> 127 => X s< 0
5834           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5835                               Constant::getNullValue(SrcTy));
5836         }
5837       }
5838     }
5839   }
5840   return 0;
5841 }
5842
5843 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5844 /// We only handle extending casts so far.
5845 ///
5846 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5847   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5848   Value *LHSCIOp        = LHSCI->getOperand(0);
5849   const Type *SrcTy     = LHSCIOp->getType();
5850   const Type *DestTy    = LHSCI->getType();
5851   Value *RHSCIOp;
5852
5853   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5854   // integer type is the same size as the pointer type.
5855   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5856       getTargetData().getPointerSizeInBits() == 
5857          cast<IntegerType>(DestTy)->getBitWidth()) {
5858     Value *RHSOp = 0;
5859     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5860       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5861     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5862       RHSOp = RHSC->getOperand(0);
5863       // If the pointer types don't match, insert a bitcast.
5864       if (LHSCIOp->getType() != RHSOp->getType())
5865         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
5866     }
5867
5868     if (RHSOp)
5869       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5870   }
5871   
5872   // The code below only handles extension cast instructions, so far.
5873   // Enforce this.
5874   if (LHSCI->getOpcode() != Instruction::ZExt &&
5875       LHSCI->getOpcode() != Instruction::SExt)
5876     return 0;
5877
5878   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5879   bool isSignedCmp = ICI.isSignedPredicate();
5880
5881   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5882     // Not an extension from the same type?
5883     RHSCIOp = CI->getOperand(0);
5884     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5885       return 0;
5886     
5887     // If the signedness of the two casts doesn't agree (i.e. one is a sext
5888     // and the other is a zext), then we can't handle this.
5889     if (CI->getOpcode() != LHSCI->getOpcode())
5890       return 0;
5891
5892     // Deal with equality cases early.
5893     if (ICI.isEquality())
5894       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5895
5896     // A signed comparison of sign extended values simplifies into a
5897     // signed comparison.
5898     if (isSignedCmp && isSignedExt)
5899       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5900
5901     // The other three cases all fold into an unsigned comparison.
5902     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
5903   }
5904
5905   // If we aren't dealing with a constant on the RHS, exit early
5906   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5907   if (!CI)
5908     return 0;
5909
5910   // Compute the constant that would happen if we truncated to SrcTy then
5911   // reextended to DestTy.
5912   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5913   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5914
5915   // If the re-extended constant didn't change...
5916   if (Res2 == CI) {
5917     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5918     // For example, we might have:
5919     //    %A = sext short %X to uint
5920     //    %B = icmp ugt uint %A, 1330
5921     // It is incorrect to transform this into 
5922     //    %B = icmp ugt short %X, 1330 
5923     // because %A may have negative value. 
5924     //
5925     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5926     // OR operation is EQ/NE.
5927     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5928       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5929     else
5930       return 0;
5931   }
5932
5933   // The re-extended constant changed so the constant cannot be represented 
5934   // in the shorter type. Consequently, we cannot emit a simple comparison.
5935
5936   // First, handle some easy cases. We know the result cannot be equal at this
5937   // point so handle the ICI.isEquality() cases
5938   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5939     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5940   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5941     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5942
5943   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5944   // should have been folded away previously and not enter in here.
5945   Value *Result;
5946   if (isSignedCmp) {
5947     // We're performing a signed comparison.
5948     if (cast<ConstantInt>(CI)->getValue().isNegative())
5949       Result = ConstantInt::getFalse();          // X < (small) --> false
5950     else
5951       Result = ConstantInt::getTrue();           // X < (large) --> true
5952   } else {
5953     // We're performing an unsigned comparison.
5954     if (isSignedExt) {
5955       // We're performing an unsigned comp with a sign extended value.
5956       // This is true if the input is >= 0. [aka >s -1]
5957       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5958       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5959                                    NegOne, ICI.getName()), ICI);
5960     } else {
5961       // Unsigned extend & unsigned compare -> always true.
5962       Result = ConstantInt::getTrue();
5963     }
5964   }
5965
5966   // Finally, return the value computed.
5967   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5968       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5969     return ReplaceInstUsesWith(ICI, Result);
5970   } else {
5971     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5972             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5973            "ICmp should be folded!");
5974     if (Constant *CI = dyn_cast<Constant>(Result))
5975       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5976     else
5977       return BinaryOperator::createNot(Result);
5978   }
5979 }
5980
5981 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5982   return commonShiftTransforms(I);
5983 }
5984
5985 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5986   return commonShiftTransforms(I);
5987 }
5988
5989 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5990   if (Instruction *R = commonShiftTransforms(I))
5991     return R;
5992   
5993   Value *Op0 = I.getOperand(0);
5994   
5995   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5996   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5997     if (CSI->isAllOnesValue())
5998       return ReplaceInstUsesWith(I, CSI);
5999   
6000   // See if we can turn a signed shr into an unsigned shr.
6001   if (MaskedValueIsZero(Op0, 
6002                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6003     return BinaryOperator::createLShr(Op0, I.getOperand(1));
6004   
6005   return 0;
6006 }
6007
6008 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6009   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6010   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6011
6012   // shl X, 0 == X and shr X, 0 == X
6013   // shl 0, X == 0 and shr 0, X == 0
6014   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6015       Op0 == Constant::getNullValue(Op0->getType()))
6016     return ReplaceInstUsesWith(I, Op0);
6017   
6018   if (isa<UndefValue>(Op0)) {            
6019     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6020       return ReplaceInstUsesWith(I, Op0);
6021     else                                    // undef << X -> 0, undef >>u X -> 0
6022       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6023   }
6024   if (isa<UndefValue>(Op1)) {
6025     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6026       return ReplaceInstUsesWith(I, Op0);          
6027     else                                     // X << undef, X >>u undef -> 0
6028       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6029   }
6030
6031   // Try to fold constant and into select arguments.
6032   if (isa<Constant>(Op0))
6033     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6034       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6035         return R;
6036
6037   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6038     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6039       return Res;
6040   return 0;
6041 }
6042
6043 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6044                                                BinaryOperator &I) {
6045   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6046
6047   // See if we can simplify any instructions used by the instruction whose sole 
6048   // purpose is to compute bits we don't care about.
6049   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6050   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6051   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6052                            KnownZero, KnownOne))
6053     return &I;
6054   
6055   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6056   // of a signed value.
6057   //
6058   if (Op1->uge(TypeBits)) {
6059     if (I.getOpcode() != Instruction::AShr)
6060       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6061     else {
6062       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6063       return &I;
6064     }
6065   }
6066   
6067   // ((X*C1) << C2) == (X * (C1 << C2))
6068   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6069     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6070       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6071         return BinaryOperator::createMul(BO->getOperand(0),
6072                                          ConstantExpr::getShl(BOOp, Op1));
6073   
6074   // Try to fold constant and into select arguments.
6075   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6076     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6077       return R;
6078   if (isa<PHINode>(Op0))
6079     if (Instruction *NV = FoldOpIntoPhi(I))
6080       return NV;
6081   
6082   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6083   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6084     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6085     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6086     // place.  Don't try to do this transformation in this case.  Also, we
6087     // require that the input operand is a shift-by-constant so that we have
6088     // confidence that the shifts will get folded together.  We could do this
6089     // xform in more cases, but it is unlikely to be profitable.
6090     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6091         isa<ConstantInt>(TrOp->getOperand(1))) {
6092       // Okay, we'll do this xform.  Make the shift of shift.
6093       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6094       Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6095                                                 I.getName());
6096       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6097
6098       // For logical shifts, the truncation has the effect of making the high
6099       // part of the register be zeros.  Emulate this by inserting an AND to
6100       // clear the top bits as needed.  This 'and' will usually be zapped by
6101       // other xforms later if dead.
6102       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6103       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6104       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6105       
6106       // The mask we constructed says what the trunc would do if occurring
6107       // between the shifts.  We want to know the effect *after* the second
6108       // shift.  We know that it is a logical shift by a constant, so adjust the
6109       // mask as appropriate.
6110       if (I.getOpcode() == Instruction::Shl)
6111         MaskV <<= Op1->getZExtValue();
6112       else {
6113         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6114         MaskV = MaskV.lshr(Op1->getZExtValue());
6115       }
6116
6117       Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6118                                                    TI->getName());
6119       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6120
6121       // Return the value truncated to the interesting size.
6122       return new TruncInst(And, I.getType());
6123     }
6124   }
6125   
6126   if (Op0->hasOneUse()) {
6127     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6128       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6129       Value *V1, *V2;
6130       ConstantInt *CC;
6131       switch (Op0BO->getOpcode()) {
6132         default: break;
6133         case Instruction::Add:
6134         case Instruction::And:
6135         case Instruction::Or:
6136         case Instruction::Xor: {
6137           // These operators commute.
6138           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6139           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6140               match(Op0BO->getOperand(1),
6141                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6142             Instruction *YS = BinaryOperator::createShl(
6143                                             Op0BO->getOperand(0), Op1,
6144                                             Op0BO->getName());
6145             InsertNewInstBefore(YS, I); // (Y << C)
6146             Instruction *X = 
6147               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6148                                      Op0BO->getOperand(1)->getName());
6149             InsertNewInstBefore(X, I);  // (X + (Y << C))
6150             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6151             return BinaryOperator::createAnd(X, ConstantInt::get(
6152                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6153           }
6154           
6155           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6156           Value *Op0BOOp1 = Op0BO->getOperand(1);
6157           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6158               match(Op0BOOp1, 
6159                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6160               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6161               V2 == Op1) {
6162             Instruction *YS = BinaryOperator::createShl(
6163                                                      Op0BO->getOperand(0), Op1,
6164                                                      Op0BO->getName());
6165             InsertNewInstBefore(YS, I); // (Y << C)
6166             Instruction *XM =
6167               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6168                                         V1->getName()+".mask");
6169             InsertNewInstBefore(XM, I); // X & (CC << C)
6170             
6171             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6172           }
6173         }
6174           
6175         // FALL THROUGH.
6176         case Instruction::Sub: {
6177           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6178           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6179               match(Op0BO->getOperand(0),
6180                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6181             Instruction *YS = BinaryOperator::createShl(
6182                                                      Op0BO->getOperand(1), Op1,
6183                                                      Op0BO->getName());
6184             InsertNewInstBefore(YS, I); // (Y << C)
6185             Instruction *X =
6186               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6187                                      Op0BO->getOperand(0)->getName());
6188             InsertNewInstBefore(X, I);  // (X + (Y << C))
6189             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6190             return BinaryOperator::createAnd(X, ConstantInt::get(
6191                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6192           }
6193           
6194           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6195           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6196               match(Op0BO->getOperand(0),
6197                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6198                           m_ConstantInt(CC))) && V2 == Op1 &&
6199               cast<BinaryOperator>(Op0BO->getOperand(0))
6200                   ->getOperand(0)->hasOneUse()) {
6201             Instruction *YS = BinaryOperator::createShl(
6202                                                      Op0BO->getOperand(1), Op1,
6203                                                      Op0BO->getName());
6204             InsertNewInstBefore(YS, I); // (Y << C)
6205             Instruction *XM =
6206               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6207                                         V1->getName()+".mask");
6208             InsertNewInstBefore(XM, I); // X & (CC << C)
6209             
6210             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6211           }
6212           
6213           break;
6214         }
6215       }
6216       
6217       
6218       // If the operand is an bitwise operator with a constant RHS, and the
6219       // shift is the only use, we can pull it out of the shift.
6220       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6221         bool isValid = true;     // Valid only for And, Or, Xor
6222         bool highBitSet = false; // Transform if high bit of constant set?
6223         
6224         switch (Op0BO->getOpcode()) {
6225           default: isValid = false; break;   // Do not perform transform!
6226           case Instruction::Add:
6227             isValid = isLeftShift;
6228             break;
6229           case Instruction::Or:
6230           case Instruction::Xor:
6231             highBitSet = false;
6232             break;
6233           case Instruction::And:
6234             highBitSet = true;
6235             break;
6236         }
6237         
6238         // If this is a signed shift right, and the high bit is modified
6239         // by the logical operation, do not perform the transformation.
6240         // The highBitSet boolean indicates the value of the high bit of
6241         // the constant which would cause it to be modified for this
6242         // operation.
6243         //
6244         if (isValid && I.getOpcode() == Instruction::AShr)
6245           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6246         
6247         if (isValid) {
6248           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6249           
6250           Instruction *NewShift =
6251             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6252           InsertNewInstBefore(NewShift, I);
6253           NewShift->takeName(Op0BO);
6254           
6255           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6256                                         NewRHS);
6257         }
6258       }
6259     }
6260   }
6261   
6262   // Find out if this is a shift of a shift by a constant.
6263   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6264   if (ShiftOp && !ShiftOp->isShift())
6265     ShiftOp = 0;
6266   
6267   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6268     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6269     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6270     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6271     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6272     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6273     Value *X = ShiftOp->getOperand(0);
6274     
6275     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6276     if (AmtSum > TypeBits)
6277       AmtSum = TypeBits;
6278     
6279     const IntegerType *Ty = cast<IntegerType>(I.getType());
6280     
6281     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6282     if (I.getOpcode() == ShiftOp->getOpcode()) {
6283       return BinaryOperator::create(I.getOpcode(), X,
6284                                     ConstantInt::get(Ty, AmtSum));
6285     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6286                I.getOpcode() == Instruction::AShr) {
6287       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6288       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6289     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6290                I.getOpcode() == Instruction::LShr) {
6291       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6292       Instruction *Shift =
6293         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6294       InsertNewInstBefore(Shift, I);
6295
6296       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6297       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6298     }
6299     
6300     // Okay, if we get here, one shift must be left, and the other shift must be
6301     // right.  See if the amounts are equal.
6302     if (ShiftAmt1 == ShiftAmt2) {
6303       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6304       if (I.getOpcode() == Instruction::Shl) {
6305         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6306         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6307       }
6308       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6309       if (I.getOpcode() == Instruction::LShr) {
6310         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6311         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6312       }
6313       // We can simplify ((X << C) >>s C) into a trunc + sext.
6314       // NOTE: we could do this for any C, but that would make 'unusual' integer
6315       // types.  For now, just stick to ones well-supported by the code
6316       // generators.
6317       const Type *SExtType = 0;
6318       switch (Ty->getBitWidth() - ShiftAmt1) {
6319       case 1  :
6320       case 8  :
6321       case 16 :
6322       case 32 :
6323       case 64 :
6324       case 128:
6325         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6326         break;
6327       default: break;
6328       }
6329       if (SExtType) {
6330         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6331         InsertNewInstBefore(NewTrunc, I);
6332         return new SExtInst(NewTrunc, Ty);
6333       }
6334       // Otherwise, we can't handle it yet.
6335     } else if (ShiftAmt1 < ShiftAmt2) {
6336       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6337       
6338       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6339       if (I.getOpcode() == Instruction::Shl) {
6340         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6341                ShiftOp->getOpcode() == Instruction::AShr);
6342         Instruction *Shift =
6343           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6344         InsertNewInstBefore(Shift, I);
6345         
6346         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6347         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6348       }
6349       
6350       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6351       if (I.getOpcode() == Instruction::LShr) {
6352         assert(ShiftOp->getOpcode() == Instruction::Shl);
6353         Instruction *Shift =
6354           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6355         InsertNewInstBefore(Shift, I);
6356         
6357         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6358         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6359       }
6360       
6361       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6362     } else {
6363       assert(ShiftAmt2 < ShiftAmt1);
6364       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6365
6366       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6367       if (I.getOpcode() == Instruction::Shl) {
6368         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6369                ShiftOp->getOpcode() == Instruction::AShr);
6370         Instruction *Shift =
6371           BinaryOperator::create(ShiftOp->getOpcode(), X,
6372                                  ConstantInt::get(Ty, ShiftDiff));
6373         InsertNewInstBefore(Shift, I);
6374         
6375         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6376         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6377       }
6378       
6379       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6380       if (I.getOpcode() == Instruction::LShr) {
6381         assert(ShiftOp->getOpcode() == Instruction::Shl);
6382         Instruction *Shift =
6383           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6384         InsertNewInstBefore(Shift, I);
6385         
6386         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6387         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6388       }
6389       
6390       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6391     }
6392   }
6393   return 0;
6394 }
6395
6396
6397 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6398 /// expression.  If so, decompose it, returning some value X, such that Val is
6399 /// X*Scale+Offset.
6400 ///
6401 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6402                                         int &Offset) {
6403   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6404   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6405     Offset = CI->getZExtValue();
6406     Scale  = 0;
6407     return ConstantInt::get(Type::Int32Ty, 0);
6408   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6409     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6410       if (I->getOpcode() == Instruction::Shl) {
6411         // This is a value scaled by '1 << the shift amt'.
6412         Scale = 1U << RHS->getZExtValue();
6413         Offset = 0;
6414         return I->getOperand(0);
6415       } else if (I->getOpcode() == Instruction::Mul) {
6416         // This value is scaled by 'RHS'.
6417         Scale = RHS->getZExtValue();
6418         Offset = 0;
6419         return I->getOperand(0);
6420       } else if (I->getOpcode() == Instruction::Add) {
6421         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6422         // where C1 is divisible by C2.
6423         unsigned SubScale;
6424         Value *SubVal = 
6425           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6426         Offset += RHS->getZExtValue();
6427         Scale = SubScale;
6428         return SubVal;
6429       }
6430     }
6431   }
6432
6433   // Otherwise, we can't look past this.
6434   Scale = 1;
6435   Offset = 0;
6436   return Val;
6437 }
6438
6439
6440 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6441 /// try to eliminate the cast by moving the type information into the alloc.
6442 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6443                                                    AllocationInst &AI) {
6444   const PointerType *PTy = cast<PointerType>(CI.getType());
6445   
6446   // Remove any uses of AI that are dead.
6447   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6448   
6449   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6450     Instruction *User = cast<Instruction>(*UI++);
6451     if (isInstructionTriviallyDead(User)) {
6452       while (UI != E && *UI == User)
6453         ++UI; // If this instruction uses AI more than once, don't break UI.
6454       
6455       ++NumDeadInst;
6456       DOUT << "IC: DCE: " << *User;
6457       EraseInstFromFunction(*User);
6458     }
6459   }
6460   
6461   // Get the type really allocated and the type casted to.
6462   const Type *AllocElTy = AI.getAllocatedType();
6463   const Type *CastElTy = PTy->getElementType();
6464   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6465
6466   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6467   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6468   if (CastElTyAlign < AllocElTyAlign) return 0;
6469
6470   // If the allocation has multiple uses, only promote it if we are strictly
6471   // increasing the alignment of the resultant allocation.  If we keep it the
6472   // same, we open the door to infinite loops of various kinds.
6473   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6474
6475   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6476   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6477   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6478
6479   // See if we can satisfy the modulus by pulling a scale out of the array
6480   // size argument.
6481   unsigned ArraySizeScale;
6482   int ArrayOffset;
6483   Value *NumElements = // See if the array size is a decomposable linear expr.
6484     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6485  
6486   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6487   // do the xform.
6488   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6489       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6490
6491   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6492   Value *Amt = 0;
6493   if (Scale == 1) {
6494     Amt = NumElements;
6495   } else {
6496     // If the allocation size is constant, form a constant mul expression
6497     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6498     if (isa<ConstantInt>(NumElements))
6499       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6500     // otherwise multiply the amount and the number of elements
6501     else if (Scale != 1) {
6502       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6503       Amt = InsertNewInstBefore(Tmp, AI);
6504     }
6505   }
6506   
6507   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6508     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6509     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6510     Amt = InsertNewInstBefore(Tmp, AI);
6511   }
6512   
6513   AllocationInst *New;
6514   if (isa<MallocInst>(AI))
6515     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6516   else
6517     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6518   InsertNewInstBefore(New, AI);
6519   New->takeName(&AI);
6520   
6521   // If the allocation has multiple uses, insert a cast and change all things
6522   // that used it to use the new cast.  This will also hack on CI, but it will
6523   // die soon.
6524   if (!AI.hasOneUse()) {
6525     AddUsesToWorkList(AI);
6526     // New is the allocation instruction, pointer typed. AI is the original
6527     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6528     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6529     InsertNewInstBefore(NewCast, AI);
6530     AI.replaceAllUsesWith(NewCast);
6531   }
6532   return ReplaceInstUsesWith(CI, New);
6533 }
6534
6535 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6536 /// and return it as type Ty without inserting any new casts and without
6537 /// changing the computed value.  This is used by code that tries to decide
6538 /// whether promoting or shrinking integer operations to wider or smaller types
6539 /// will allow us to eliminate a truncate or extend.
6540 ///
6541 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6542 /// extension operation if Ty is larger.
6543 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6544                                        unsigned CastOpc, int &NumCastsRemoved) {
6545   // We can always evaluate constants in another type.
6546   if (isa<ConstantInt>(V))
6547     return true;
6548   
6549   Instruction *I = dyn_cast<Instruction>(V);
6550   if (!I) return false;
6551   
6552   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6553   
6554   // If this is an extension or truncate, we can often eliminate it.
6555   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6556     // If this is a cast from the destination type, we can trivially eliminate
6557     // it, and this will remove a cast overall.
6558     if (I->getOperand(0)->getType() == Ty) {
6559       // If the first operand is itself a cast, and is eliminable, do not count
6560       // this as an eliminable cast.  We would prefer to eliminate those two
6561       // casts first.
6562       if (!isa<CastInst>(I->getOperand(0)))
6563         ++NumCastsRemoved;
6564       return true;
6565     }
6566   }
6567
6568   // We can't extend or shrink something that has multiple uses: doing so would
6569   // require duplicating the instruction in general, which isn't profitable.
6570   if (!I->hasOneUse()) return false;
6571
6572   switch (I->getOpcode()) {
6573   case Instruction::Add:
6574   case Instruction::Sub:
6575   case Instruction::And:
6576   case Instruction::Or:
6577   case Instruction::Xor:
6578     // These operators can all arbitrarily be extended or truncated.
6579     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6580                                       NumCastsRemoved) &&
6581            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6582                                       NumCastsRemoved);
6583
6584   case Instruction::Mul:
6585     // A multiply can be truncated by truncating its operands.
6586     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6587            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6588                                       NumCastsRemoved) &&
6589            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6590                                       NumCastsRemoved);
6591
6592   case Instruction::Shl:
6593     // If we are truncating the result of this SHL, and if it's a shift of a
6594     // constant amount, we can always perform a SHL in a smaller type.
6595     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6596       uint32_t BitWidth = Ty->getBitWidth();
6597       if (BitWidth < OrigTy->getBitWidth() && 
6598           CI->getLimitedValue(BitWidth) < BitWidth)
6599         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6600                                           NumCastsRemoved);
6601     }
6602     break;
6603   case Instruction::LShr:
6604     // If this is a truncate of a logical shr, we can truncate it to a smaller
6605     // lshr iff we know that the bits we would otherwise be shifting in are
6606     // already zeros.
6607     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6608       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6609       uint32_t BitWidth = Ty->getBitWidth();
6610       if (BitWidth < OrigBitWidth &&
6611           MaskedValueIsZero(I->getOperand(0),
6612             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6613           CI->getLimitedValue(BitWidth) < BitWidth) {
6614         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6615                                           NumCastsRemoved);
6616       }
6617     }
6618     break;
6619   case Instruction::ZExt:
6620   case Instruction::SExt:
6621   case Instruction::Trunc:
6622     // If this is the same kind of case as our original (e.g. zext+zext), we
6623     // can safely replace it.  Note that replacing it does not reduce the number
6624     // of casts in the input.
6625     if (I->getOpcode() == CastOpc)
6626       return true;
6627     
6628     break;
6629   default:
6630     // TODO: Can handle more cases here.
6631     break;
6632   }
6633   
6634   return false;
6635 }
6636
6637 /// EvaluateInDifferentType - Given an expression that 
6638 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6639 /// evaluate the expression.
6640 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6641                                              bool isSigned) {
6642   if (Constant *C = dyn_cast<Constant>(V))
6643     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6644
6645   // Otherwise, it must be an instruction.
6646   Instruction *I = cast<Instruction>(V);
6647   Instruction *Res = 0;
6648   switch (I->getOpcode()) {
6649   case Instruction::Add:
6650   case Instruction::Sub:
6651   case Instruction::Mul:
6652   case Instruction::And:
6653   case Instruction::Or:
6654   case Instruction::Xor:
6655   case Instruction::AShr:
6656   case Instruction::LShr:
6657   case Instruction::Shl: {
6658     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6659     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6660     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6661                                  LHS, RHS, I->getName());
6662     break;
6663   }    
6664   case Instruction::Trunc:
6665   case Instruction::ZExt:
6666   case Instruction::SExt:
6667     // If the source type of the cast is the type we're trying for then we can
6668     // just return the source.  There's no need to insert it because it is not
6669     // new.
6670     if (I->getOperand(0)->getType() == Ty)
6671       return I->getOperand(0);
6672     
6673     // Otherwise, must be the same type of case, so just reinsert a new one.
6674     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6675                            Ty, I->getName());
6676     break;
6677   default: 
6678     // TODO: Can handle more cases here.
6679     assert(0 && "Unreachable!");
6680     break;
6681   }
6682   
6683   return InsertNewInstBefore(Res, *I);
6684 }
6685
6686 /// @brief Implement the transforms common to all CastInst visitors.
6687 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6688   Value *Src = CI.getOperand(0);
6689
6690   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6691   // eliminate it now.
6692   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6693     if (Instruction::CastOps opc = 
6694         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6695       // The first cast (CSrc) is eliminable so we need to fix up or replace
6696       // the second cast (CI). CSrc will then have a good chance of being dead.
6697       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6698     }
6699   }
6700
6701   // If we are casting a select then fold the cast into the select
6702   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6703     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6704       return NV;
6705
6706   // If we are casting a PHI then fold the cast into the PHI
6707   if (isa<PHINode>(Src))
6708     if (Instruction *NV = FoldOpIntoPhi(CI))
6709       return NV;
6710   
6711   return 0;
6712 }
6713
6714 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6715 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6716   Value *Src = CI.getOperand(0);
6717   
6718   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6719     // If casting the result of a getelementptr instruction with no offset, turn
6720     // this into a cast of the original pointer!
6721     if (GEP->hasAllZeroIndices()) {
6722       // Changing the cast operand is usually not a good idea but it is safe
6723       // here because the pointer operand is being replaced with another 
6724       // pointer operand so the opcode doesn't need to change.
6725       AddToWorkList(GEP);
6726       CI.setOperand(0, GEP->getOperand(0));
6727       return &CI;
6728     }
6729     
6730     // If the GEP has a single use, and the base pointer is a bitcast, and the
6731     // GEP computes a constant offset, see if we can convert these three
6732     // instructions into fewer.  This typically happens with unions and other
6733     // non-type-safe code.
6734     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6735       if (GEP->hasAllConstantIndices()) {
6736         // We are guaranteed to get a constant from EmitGEPOffset.
6737         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6738         int64_t Offset = OffsetV->getSExtValue();
6739         
6740         // Get the base pointer input of the bitcast, and the type it points to.
6741         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6742         const Type *GEPIdxTy =
6743           cast<PointerType>(OrigBase->getType())->getElementType();
6744         if (GEPIdxTy->isSized()) {
6745           SmallVector<Value*, 8> NewIndices;
6746           
6747           // Start with the index over the outer type.  Note that the type size
6748           // might be zero (even if the offset isn't zero) if the indexed type
6749           // is something like [0 x {int, int}]
6750           const Type *IntPtrTy = TD->getIntPtrType();
6751           int64_t FirstIdx = 0;
6752           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6753             FirstIdx = Offset/TySize;
6754             Offset %= TySize;
6755           
6756             // Handle silly modulus not returning values values [0..TySize).
6757             if (Offset < 0) {
6758               --FirstIdx;
6759               Offset += TySize;
6760               assert(Offset >= 0);
6761             }
6762             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6763           }
6764           
6765           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6766
6767           // Index into the types.  If we fail, set OrigBase to null.
6768           while (Offset) {
6769             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6770               const StructLayout *SL = TD->getStructLayout(STy);
6771               if (Offset < (int64_t)SL->getSizeInBytes()) {
6772                 unsigned Elt = SL->getElementContainingOffset(Offset);
6773                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6774               
6775                 Offset -= SL->getElementOffset(Elt);
6776                 GEPIdxTy = STy->getElementType(Elt);
6777               } else {
6778                 // Otherwise, we can't index into this, bail out.
6779                 Offset = 0;
6780                 OrigBase = 0;
6781               }
6782             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6783               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6784               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6785                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6786                 Offset %= EltSize;
6787               } else {
6788                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6789               }
6790               GEPIdxTy = STy->getElementType();
6791             } else {
6792               // Otherwise, we can't index into this, bail out.
6793               Offset = 0;
6794               OrigBase = 0;
6795             }
6796           }
6797           if (OrigBase) {
6798             // If we were able to index down into an element, create the GEP
6799             // and bitcast the result.  This eliminates one bitcast, potentially
6800             // two.
6801             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6802                                                       NewIndices.begin(),
6803                                                       NewIndices.end(), "");
6804             InsertNewInstBefore(NGEP, CI);
6805             NGEP->takeName(GEP);
6806             
6807             if (isa<BitCastInst>(CI))
6808               return new BitCastInst(NGEP, CI.getType());
6809             assert(isa<PtrToIntInst>(CI));
6810             return new PtrToIntInst(NGEP, CI.getType());
6811           }
6812         }
6813       }      
6814     }
6815   }
6816     
6817   return commonCastTransforms(CI);
6818 }
6819
6820
6821
6822 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6823 /// integer types. This function implements the common transforms for all those
6824 /// cases.
6825 /// @brief Implement the transforms common to CastInst with integer operands
6826 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6827   if (Instruction *Result = commonCastTransforms(CI))
6828     return Result;
6829
6830   Value *Src = CI.getOperand(0);
6831   const Type *SrcTy = Src->getType();
6832   const Type *DestTy = CI.getType();
6833   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6834   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6835
6836   // See if we can simplify any instructions used by the LHS whose sole 
6837   // purpose is to compute bits we don't care about.
6838   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6839   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6840                            KnownZero, KnownOne))
6841     return &CI;
6842
6843   // If the source isn't an instruction or has more than one use then we
6844   // can't do anything more. 
6845   Instruction *SrcI = dyn_cast<Instruction>(Src);
6846   if (!SrcI || !Src->hasOneUse())
6847     return 0;
6848
6849   // Attempt to propagate the cast into the instruction for int->int casts.
6850   int NumCastsRemoved = 0;
6851   if (!isa<BitCastInst>(CI) &&
6852       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6853                                  CI.getOpcode(), NumCastsRemoved)) {
6854     // If this cast is a truncate, evaluting in a different type always
6855     // eliminates the cast, so it is always a win.  If this is a zero-extension,
6856     // we need to do an AND to maintain the clear top-part of the computation,
6857     // so we require that the input have eliminated at least one cast.  If this
6858     // is a sign extension, we insert two new casts (to do the extension) so we
6859     // require that two casts have been eliminated.
6860     bool DoXForm;
6861     switch (CI.getOpcode()) {
6862     default:
6863       // All the others use floating point so we shouldn't actually 
6864       // get here because of the check above.
6865       assert(0 && "Unknown cast type");
6866     case Instruction::Trunc:
6867       DoXForm = true;
6868       break;
6869     case Instruction::ZExt:
6870       DoXForm = NumCastsRemoved >= 1;
6871       break;
6872     case Instruction::SExt:
6873       DoXForm = NumCastsRemoved >= 2;
6874       break;
6875     }
6876     
6877     if (DoXForm) {
6878       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6879                                            CI.getOpcode() == Instruction::SExt);
6880       assert(Res->getType() == DestTy);
6881       switch (CI.getOpcode()) {
6882       default: assert(0 && "Unknown cast type!");
6883       case Instruction::Trunc:
6884       case Instruction::BitCast:
6885         // Just replace this cast with the result.
6886         return ReplaceInstUsesWith(CI, Res);
6887       case Instruction::ZExt: {
6888         // We need to emit an AND to clear the high bits.
6889         assert(SrcBitSize < DestBitSize && "Not a zext?");
6890         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6891                                                             SrcBitSize));
6892         return BinaryOperator::createAnd(Res, C);
6893       }
6894       case Instruction::SExt:
6895         // We need to emit a cast to truncate, then a cast to sext.
6896         return CastInst::create(Instruction::SExt,
6897             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6898                              CI), DestTy);
6899       }
6900     }
6901   }
6902   
6903   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6904   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6905
6906   switch (SrcI->getOpcode()) {
6907   case Instruction::Add:
6908   case Instruction::Mul:
6909   case Instruction::And:
6910   case Instruction::Or:
6911   case Instruction::Xor:
6912     // If we are discarding information, rewrite.
6913     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6914       // Don't insert two casts if they cannot be eliminated.  We allow 
6915       // two casts to be inserted if the sizes are the same.  This could 
6916       // only be converting signedness, which is a noop.
6917       if (DestBitSize == SrcBitSize || 
6918           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6919           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6920         Instruction::CastOps opcode = CI.getOpcode();
6921         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6922         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6923         return BinaryOperator::create(
6924             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6925       }
6926     }
6927
6928     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6929     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6930         SrcI->getOpcode() == Instruction::Xor &&
6931         Op1 == ConstantInt::getTrue() &&
6932         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6933       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6934       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6935     }
6936     break;
6937   case Instruction::SDiv:
6938   case Instruction::UDiv:
6939   case Instruction::SRem:
6940   case Instruction::URem:
6941     // If we are just changing the sign, rewrite.
6942     if (DestBitSize == SrcBitSize) {
6943       // Don't insert two casts if they cannot be eliminated.  We allow 
6944       // two casts to be inserted if the sizes are the same.  This could 
6945       // only be converting signedness, which is a noop.
6946       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6947           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6948         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6949                                               Op0, DestTy, SrcI);
6950         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6951                                               Op1, DestTy, SrcI);
6952         return BinaryOperator::create(
6953           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6954       }
6955     }
6956     break;
6957
6958   case Instruction::Shl:
6959     // Allow changing the sign of the source operand.  Do not allow 
6960     // changing the size of the shift, UNLESS the shift amount is a 
6961     // constant.  We must not change variable sized shifts to a smaller 
6962     // size, because it is undefined to shift more bits out than exist 
6963     // in the value.
6964     if (DestBitSize == SrcBitSize ||
6965         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6966       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6967           Instruction::BitCast : Instruction::Trunc);
6968       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6969       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6970       return BinaryOperator::createShl(Op0c, Op1c);
6971     }
6972     break;
6973   case Instruction::AShr:
6974     // If this is a signed shr, and if all bits shifted in are about to be
6975     // truncated off, turn it into an unsigned shr to allow greater
6976     // simplifications.
6977     if (DestBitSize < SrcBitSize &&
6978         isa<ConstantInt>(Op1)) {
6979       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6980       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6981         // Insert the new logical shift right.
6982         return BinaryOperator::createLShr(Op0, Op1);
6983       }
6984     }
6985     break;
6986   }
6987   return 0;
6988 }
6989
6990 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6991   if (Instruction *Result = commonIntCastTransforms(CI))
6992     return Result;
6993   
6994   Value *Src = CI.getOperand(0);
6995   const Type *Ty = CI.getType();
6996   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6997   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6998   
6999   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7000     switch (SrcI->getOpcode()) {
7001     default: break;
7002     case Instruction::LShr:
7003       // We can shrink lshr to something smaller if we know the bits shifted in
7004       // are already zeros.
7005       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7006         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7007         
7008         // Get a mask for the bits shifting in.
7009         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7010         Value* SrcIOp0 = SrcI->getOperand(0);
7011         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7012           if (ShAmt >= DestBitWidth)        // All zeros.
7013             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7014
7015           // Okay, we can shrink this.  Truncate the input, then return a new
7016           // shift.
7017           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7018           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7019                                        Ty, CI);
7020           return BinaryOperator::createLShr(V1, V2);
7021         }
7022       } else {     // This is a variable shr.
7023         
7024         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7025         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7026         // loop-invariant and CSE'd.
7027         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7028           Value *One = ConstantInt::get(SrcI->getType(), 1);
7029
7030           Value *V = InsertNewInstBefore(
7031               BinaryOperator::createShl(One, SrcI->getOperand(1),
7032                                      "tmp"), CI);
7033           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7034                                                             SrcI->getOperand(0),
7035                                                             "tmp"), CI);
7036           Value *Zero = Constant::getNullValue(V->getType());
7037           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7038         }
7039       }
7040       break;
7041     }
7042   }
7043   
7044   return 0;
7045 }
7046
7047 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7048   // If one of the common conversion will work ..
7049   if (Instruction *Result = commonIntCastTransforms(CI))
7050     return Result;
7051
7052   Value *Src = CI.getOperand(0);
7053
7054   // If this is a cast of a cast
7055   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7056     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7057     // types and if the sizes are just right we can convert this into a logical
7058     // 'and' which will be much cheaper than the pair of casts.
7059     if (isa<TruncInst>(CSrc)) {
7060       // Get the sizes of the types involved
7061       Value *A = CSrc->getOperand(0);
7062       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7063       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7064       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7065       // If we're actually extending zero bits and the trunc is a no-op
7066       if (MidSize < DstSize && SrcSize == DstSize) {
7067         // Replace both of the casts with an And of the type mask.
7068         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7069         Constant *AndConst = ConstantInt::get(AndValue);
7070         Instruction *And = 
7071           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7072         // Unfortunately, if the type changed, we need to cast it back.
7073         if (And->getType() != CI.getType()) {
7074           And->setName(CSrc->getName()+".mask");
7075           InsertNewInstBefore(And, CI);
7076           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7077         }
7078         return And;
7079       }
7080     }
7081   }
7082
7083   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7084     // If we are just checking for a icmp eq of a single bit and zext'ing it
7085     // to an integer, then shift the bit to the appropriate place and then
7086     // cast to integer to avoid the comparison.
7087     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7088       const APInt &Op1CV = Op1C->getValue();
7089       
7090       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7091       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7092       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7093           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7094         Value *In = ICI->getOperand(0);
7095         Value *Sh = ConstantInt::get(In->getType(),
7096                                     In->getType()->getPrimitiveSizeInBits()-1);
7097         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7098                                                         In->getName()+".lobit"),
7099                                  CI);
7100         if (In->getType() != CI.getType())
7101           In = CastInst::createIntegerCast(In, CI.getType(),
7102                                            false/*ZExt*/, "tmp", &CI);
7103
7104         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7105           Constant *One = ConstantInt::get(In->getType(), 1);
7106           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7107                                                           In->getName()+".not"),
7108                                    CI);
7109         }
7110
7111         return ReplaceInstUsesWith(CI, In);
7112       }
7113       
7114       
7115       
7116       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7117       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7118       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7119       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7120       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7121       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7122       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7123       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7124       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7125           // This only works for EQ and NE
7126           ICI->isEquality()) {
7127         // If Op1C some other power of two, convert:
7128         uint32_t BitWidth = Op1C->getType()->getBitWidth();
7129         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7130         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7131         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7132         
7133         APInt KnownZeroMask(~KnownZero);
7134         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7135           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7136           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7137             // (X&4) == 2 --> false
7138             // (X&4) != 2 --> true
7139             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7140             Res = ConstantExpr::getZExt(Res, CI.getType());
7141             return ReplaceInstUsesWith(CI, Res);
7142           }
7143           
7144           uint32_t ShiftAmt = KnownZeroMask.logBase2();
7145           Value *In = ICI->getOperand(0);
7146           if (ShiftAmt) {
7147             // Perform a logical shr by shiftamt.
7148             // Insert the shift to put the result in the low bit.
7149             In = InsertNewInstBefore(
7150                    BinaryOperator::createLShr(In,
7151                                      ConstantInt::get(In->getType(), ShiftAmt),
7152                                               In->getName()+".lobit"), CI);
7153           }
7154           
7155           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7156             Constant *One = ConstantInt::get(In->getType(), 1);
7157             In = BinaryOperator::createXor(In, One, "tmp");
7158             InsertNewInstBefore(cast<Instruction>(In), CI);
7159           }
7160           
7161           if (CI.getType() == In->getType())
7162             return ReplaceInstUsesWith(CI, In);
7163           else
7164             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7165         }
7166       }
7167     }
7168   }    
7169   return 0;
7170 }
7171
7172 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7173   if (Instruction *I = commonIntCastTransforms(CI))
7174     return I;
7175   
7176   Value *Src = CI.getOperand(0);
7177   
7178   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7179   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7180   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7181     // If we are just checking for a icmp eq of a single bit and zext'ing it
7182     // to an integer, then shift the bit to the appropriate place and then
7183     // cast to integer to avoid the comparison.
7184     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7185       const APInt &Op1CV = Op1C->getValue();
7186       
7187       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7188       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7189       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7190           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7191         Value *In = ICI->getOperand(0);
7192         Value *Sh = ConstantInt::get(In->getType(),
7193                                      In->getType()->getPrimitiveSizeInBits()-1);
7194         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7195                                                         In->getName()+".lobit"),
7196                                  CI);
7197         if (In->getType() != CI.getType())
7198           In = CastInst::createIntegerCast(In, CI.getType(),
7199                                            true/*SExt*/, "tmp", &CI);
7200         
7201         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7202           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7203                                      In->getName()+".not"), CI);
7204         
7205         return ReplaceInstUsesWith(CI, In);
7206       }
7207     }
7208   }
7209       
7210   return 0;
7211 }
7212
7213 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7214 /// in the specified FP type without changing its value.
7215 static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy, 
7216                               const fltSemantics &Sem) {
7217   APFloat F = CFP->getValueAPF();
7218   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7219     return ConstantFP::get(FPTy, F);
7220   return 0;
7221 }
7222
7223 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7224 /// through it until we get the source value.
7225 static Value *LookThroughFPExtensions(Value *V) {
7226   if (Instruction *I = dyn_cast<Instruction>(V))
7227     if (I->getOpcode() == Instruction::FPExt)
7228       return LookThroughFPExtensions(I->getOperand(0));
7229   
7230   // If this value is a constant, return the constant in the smallest FP type
7231   // that can accurately represent it.  This allows us to turn
7232   // (float)((double)X+2.0) into x+2.0f.
7233   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7234     if (CFP->getType() == Type::PPC_FP128Ty)
7235       return V;  // No constant folding of this.
7236     // See if the value can be truncated to float and then reextended.
7237     if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7238       return V;
7239     if (CFP->getType() == Type::DoubleTy)
7240       return V;  // Won't shrink.
7241     if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7242       return V;
7243     // Don't try to shrink to various long double types.
7244   }
7245   
7246   return V;
7247 }
7248
7249 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7250   if (Instruction *I = commonCastTransforms(CI))
7251     return I;
7252   
7253   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7254   // smaller than the destination type, we can eliminate the truncate by doing
7255   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7256   // many builtins (sqrt, etc).
7257   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7258   if (OpI && OpI->hasOneUse()) {
7259     switch (OpI->getOpcode()) {
7260     default: break;
7261     case Instruction::Add:
7262     case Instruction::Sub:
7263     case Instruction::Mul:
7264     case Instruction::FDiv:
7265     case Instruction::FRem:
7266       const Type *SrcTy = OpI->getType();
7267       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7268       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7269       if (LHSTrunc->getType() != SrcTy && 
7270           RHSTrunc->getType() != SrcTy) {
7271         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7272         // If the source types were both smaller than the destination type of
7273         // the cast, do this xform.
7274         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7275             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7276           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7277                                       CI.getType(), CI);
7278           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7279                                       CI.getType(), CI);
7280           return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7281         }
7282       }
7283       break;  
7284     }
7285   }
7286   return 0;
7287 }
7288
7289 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7290   return commonCastTransforms(CI);
7291 }
7292
7293 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7294   return commonCastTransforms(CI);
7295 }
7296
7297 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7298   return commonCastTransforms(CI);
7299 }
7300
7301 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7302   return commonCastTransforms(CI);
7303 }
7304
7305 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7306   return commonCastTransforms(CI);
7307 }
7308
7309 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7310   return commonPointerCastTransforms(CI);
7311 }
7312
7313 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7314   if (Instruction *I = commonCastTransforms(CI))
7315     return I;
7316   
7317   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7318   if (!DestPointee->isSized()) return 0;
7319
7320   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7321   ConstantInt *Cst;
7322   Value *X;
7323   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7324                                     m_ConstantInt(Cst)))) {
7325     // If the source and destination operands have the same type, see if this
7326     // is a single-index GEP.
7327     if (X->getType() == CI.getType()) {
7328       // Get the size of the pointee type.
7329       uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7330
7331       // Convert the constant to intptr type.
7332       APInt Offset = Cst->getValue();
7333       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7334
7335       // If Offset is evenly divisible by Size, we can do this xform.
7336       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7337         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7338         return new GetElementPtrInst(X, ConstantInt::get(Offset));
7339       }
7340     }
7341     // TODO: Could handle other cases, e.g. where add is indexing into field of
7342     // struct etc.
7343   } else if (CI.getOperand(0)->hasOneUse() &&
7344              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7345     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7346     // "inttoptr+GEP" instead of "add+intptr".
7347     
7348     // Get the size of the pointee type.
7349     uint64_t Size = TD->getABITypeSize(DestPointee);
7350     
7351     // Convert the constant to intptr type.
7352     APInt Offset = Cst->getValue();
7353     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7354     
7355     // If Offset is evenly divisible by Size, we can do this xform.
7356     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7357       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7358       
7359       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7360                                                             "tmp"), CI);
7361       return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7362     }
7363   }
7364   return 0;
7365 }
7366
7367 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7368   // If the operands are integer typed then apply the integer transforms,
7369   // otherwise just apply the common ones.
7370   Value *Src = CI.getOperand(0);
7371   const Type *SrcTy = Src->getType();
7372   const Type *DestTy = CI.getType();
7373
7374   if (SrcTy->isInteger() && DestTy->isInteger()) {
7375     if (Instruction *Result = commonIntCastTransforms(CI))
7376       return Result;
7377   } else if (isa<PointerType>(SrcTy)) {
7378     if (Instruction *I = commonPointerCastTransforms(CI))
7379       return I;
7380   } else {
7381     if (Instruction *Result = commonCastTransforms(CI))
7382       return Result;
7383   }
7384
7385
7386   // Get rid of casts from one type to the same type. These are useless and can
7387   // be replaced by the operand.
7388   if (DestTy == Src->getType())
7389     return ReplaceInstUsesWith(CI, Src);
7390
7391   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7392     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7393     const Type *DstElTy = DstPTy->getElementType();
7394     const Type *SrcElTy = SrcPTy->getElementType();
7395     
7396     // If we are casting a malloc or alloca to a pointer to a type of the same
7397     // size, rewrite the allocation instruction to allocate the "right" type.
7398     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7399       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7400         return V;
7401     
7402     // If the source and destination are pointers, and this cast is equivalent
7403     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7404     // This can enhance SROA and other transforms that want type-safe pointers.
7405     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7406     unsigned NumZeros = 0;
7407     while (SrcElTy != DstElTy && 
7408            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7409            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7410       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7411       ++NumZeros;
7412     }
7413
7414     // If we found a path from the src to dest, create the getelementptr now.
7415     if (SrcElTy == DstElTy) {
7416       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7417       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7418                                    ((Instruction*) NULL));
7419     }
7420   }
7421
7422   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7423     if (SVI->hasOneUse()) {
7424       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7425       // a bitconvert to a vector with the same # elts.
7426       if (isa<VectorType>(DestTy) && 
7427           cast<VectorType>(DestTy)->getNumElements() == 
7428                 SVI->getType()->getNumElements()) {
7429         CastInst *Tmp;
7430         // If either of the operands is a cast from CI.getType(), then
7431         // evaluating the shuffle in the casted destination's type will allow
7432         // us to eliminate at least one cast.
7433         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7434              Tmp->getOperand(0)->getType() == DestTy) ||
7435             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7436              Tmp->getOperand(0)->getType() == DestTy)) {
7437           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7438                                                SVI->getOperand(0), DestTy, &CI);
7439           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7440                                                SVI->getOperand(1), DestTy, &CI);
7441           // Return a new shuffle vector.  Use the same element ID's, as we
7442           // know the vector types match #elts.
7443           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7444         }
7445       }
7446     }
7447   }
7448   return 0;
7449 }
7450
7451 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7452 ///   %C = or %A, %B
7453 ///   %D = select %cond, %C, %A
7454 /// into:
7455 ///   %C = select %cond, %B, 0
7456 ///   %D = or %A, %C
7457 ///
7458 /// Assuming that the specified instruction is an operand to the select, return
7459 /// a bitmask indicating which operands of this instruction are foldable if they
7460 /// equal the other incoming value of the select.
7461 ///
7462 static unsigned GetSelectFoldableOperands(Instruction *I) {
7463   switch (I->getOpcode()) {
7464   case Instruction::Add:
7465   case Instruction::Mul:
7466   case Instruction::And:
7467   case Instruction::Or:
7468   case Instruction::Xor:
7469     return 3;              // Can fold through either operand.
7470   case Instruction::Sub:   // Can only fold on the amount subtracted.
7471   case Instruction::Shl:   // Can only fold on the shift amount.
7472   case Instruction::LShr:
7473   case Instruction::AShr:
7474     return 1;
7475   default:
7476     return 0;              // Cannot fold
7477   }
7478 }
7479
7480 /// GetSelectFoldableConstant - For the same transformation as the previous
7481 /// function, return the identity constant that goes into the select.
7482 static Constant *GetSelectFoldableConstant(Instruction *I) {
7483   switch (I->getOpcode()) {
7484   default: assert(0 && "This cannot happen!"); abort();
7485   case Instruction::Add:
7486   case Instruction::Sub:
7487   case Instruction::Or:
7488   case Instruction::Xor:
7489   case Instruction::Shl:
7490   case Instruction::LShr:
7491   case Instruction::AShr:
7492     return Constant::getNullValue(I->getType());
7493   case Instruction::And:
7494     return Constant::getAllOnesValue(I->getType());
7495   case Instruction::Mul:
7496     return ConstantInt::get(I->getType(), 1);
7497   }
7498 }
7499
7500 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7501 /// have the same opcode and only one use each.  Try to simplify this.
7502 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7503                                           Instruction *FI) {
7504   if (TI->getNumOperands() == 1) {
7505     // If this is a non-volatile load or a cast from the same type,
7506     // merge.
7507     if (TI->isCast()) {
7508       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7509         return 0;
7510     } else {
7511       return 0;  // unknown unary op.
7512     }
7513
7514     // Fold this by inserting a select from the input values.
7515     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7516                                        FI->getOperand(0), SI.getName()+".v");
7517     InsertNewInstBefore(NewSI, SI);
7518     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7519                             TI->getType());
7520   }
7521
7522   // Only handle binary operators here.
7523   if (!isa<BinaryOperator>(TI))
7524     return 0;
7525
7526   // Figure out if the operations have any operands in common.
7527   Value *MatchOp, *OtherOpT, *OtherOpF;
7528   bool MatchIsOpZero;
7529   if (TI->getOperand(0) == FI->getOperand(0)) {
7530     MatchOp  = TI->getOperand(0);
7531     OtherOpT = TI->getOperand(1);
7532     OtherOpF = FI->getOperand(1);
7533     MatchIsOpZero = true;
7534   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7535     MatchOp  = TI->getOperand(1);
7536     OtherOpT = TI->getOperand(0);
7537     OtherOpF = FI->getOperand(0);
7538     MatchIsOpZero = false;
7539   } else if (!TI->isCommutative()) {
7540     return 0;
7541   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7542     MatchOp  = TI->getOperand(0);
7543     OtherOpT = TI->getOperand(1);
7544     OtherOpF = FI->getOperand(0);
7545     MatchIsOpZero = true;
7546   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7547     MatchOp  = TI->getOperand(1);
7548     OtherOpT = TI->getOperand(0);
7549     OtherOpF = FI->getOperand(1);
7550     MatchIsOpZero = true;
7551   } else {
7552     return 0;
7553   }
7554
7555   // If we reach here, they do have operations in common.
7556   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7557                                      OtherOpF, SI.getName()+".v");
7558   InsertNewInstBefore(NewSI, SI);
7559
7560   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7561     if (MatchIsOpZero)
7562       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7563     else
7564       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7565   }
7566   assert(0 && "Shouldn't get here");
7567   return 0;
7568 }
7569
7570 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7571   Value *CondVal = SI.getCondition();
7572   Value *TrueVal = SI.getTrueValue();
7573   Value *FalseVal = SI.getFalseValue();
7574
7575   // select true, X, Y  -> X
7576   // select false, X, Y -> Y
7577   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7578     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7579
7580   // select C, X, X -> X
7581   if (TrueVal == FalseVal)
7582     return ReplaceInstUsesWith(SI, TrueVal);
7583
7584   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7585     return ReplaceInstUsesWith(SI, FalseVal);
7586   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7587     return ReplaceInstUsesWith(SI, TrueVal);
7588   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7589     if (isa<Constant>(TrueVal))
7590       return ReplaceInstUsesWith(SI, TrueVal);
7591     else
7592       return ReplaceInstUsesWith(SI, FalseVal);
7593   }
7594
7595   if (SI.getType() == Type::Int1Ty) {
7596     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7597       if (C->getZExtValue()) {
7598         // Change: A = select B, true, C --> A = or B, C
7599         return BinaryOperator::createOr(CondVal, FalseVal);
7600       } else {
7601         // Change: A = select B, false, C --> A = and !B, C
7602         Value *NotCond =
7603           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7604                                              "not."+CondVal->getName()), SI);
7605         return BinaryOperator::createAnd(NotCond, FalseVal);
7606       }
7607     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7608       if (C->getZExtValue() == false) {
7609         // Change: A = select B, C, false --> A = and B, C
7610         return BinaryOperator::createAnd(CondVal, TrueVal);
7611       } else {
7612         // Change: A = select B, C, true --> A = or !B, C
7613         Value *NotCond =
7614           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7615                                              "not."+CondVal->getName()), SI);
7616         return BinaryOperator::createOr(NotCond, TrueVal);
7617       }
7618     }
7619     
7620     // select a, b, a  -> a&b
7621     // select a, a, b  -> a|b
7622     if (CondVal == TrueVal)
7623       return BinaryOperator::createOr(CondVal, FalseVal);
7624     else if (CondVal == FalseVal)
7625       return BinaryOperator::createAnd(CondVal, TrueVal);
7626   }
7627
7628   // Selecting between two integer constants?
7629   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7630     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7631       // select C, 1, 0 -> zext C to int
7632       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7633         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7634       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7635         // select C, 0, 1 -> zext !C to int
7636         Value *NotCond =
7637           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7638                                                "not."+CondVal->getName()), SI);
7639         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7640       }
7641       
7642       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7643
7644       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7645
7646         // (x <s 0) ? -1 : 0 -> ashr x, 31
7647         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7648           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7649             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7650               // The comparison constant and the result are not neccessarily the
7651               // same width. Make an all-ones value by inserting a AShr.
7652               Value *X = IC->getOperand(0);
7653               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7654               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7655               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7656                                                         ShAmt, "ones");
7657               InsertNewInstBefore(SRA, SI);
7658               
7659               // Finally, convert to the type of the select RHS.  We figure out
7660               // if this requires a SExt, Trunc or BitCast based on the sizes.
7661               Instruction::CastOps opc = Instruction::BitCast;
7662               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7663               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7664               if (SRASize < SISize)
7665                 opc = Instruction::SExt;
7666               else if (SRASize > SISize)
7667                 opc = Instruction::Trunc;
7668               return CastInst::create(opc, SRA, SI.getType());
7669             }
7670           }
7671
7672
7673         // If one of the constants is zero (we know they can't both be) and we
7674         // have an icmp instruction with zero, and we have an 'and' with the
7675         // non-constant value, eliminate this whole mess.  This corresponds to
7676         // cases like this: ((X & 27) ? 27 : 0)
7677         if (TrueValC->isZero() || FalseValC->isZero())
7678           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7679               cast<Constant>(IC->getOperand(1))->isNullValue())
7680             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7681               if (ICA->getOpcode() == Instruction::And &&
7682                   isa<ConstantInt>(ICA->getOperand(1)) &&
7683                   (ICA->getOperand(1) == TrueValC ||
7684                    ICA->getOperand(1) == FalseValC) &&
7685                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7686                 // Okay, now we know that everything is set up, we just don't
7687                 // know whether we have a icmp_ne or icmp_eq and whether the 
7688                 // true or false val is the zero.
7689                 bool ShouldNotVal = !TrueValC->isZero();
7690                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7691                 Value *V = ICA;
7692                 if (ShouldNotVal)
7693                   V = InsertNewInstBefore(BinaryOperator::create(
7694                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7695                 return ReplaceInstUsesWith(SI, V);
7696               }
7697       }
7698     }
7699
7700   // See if we are selecting two values based on a comparison of the two values.
7701   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7702     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7703       // Transform (X == Y) ? X : Y  -> Y
7704       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7705         // This is not safe in general for floating point:  
7706         // consider X== -0, Y== +0.
7707         // It becomes safe if either operand is a nonzero constant.
7708         ConstantFP *CFPt, *CFPf;
7709         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7710               !CFPt->getValueAPF().isZero()) ||
7711             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7712              !CFPf->getValueAPF().isZero()))
7713         return ReplaceInstUsesWith(SI, FalseVal);
7714       }
7715       // Transform (X != Y) ? X : Y  -> X
7716       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7717         return ReplaceInstUsesWith(SI, TrueVal);
7718       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7719
7720     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7721       // Transform (X == Y) ? Y : X  -> X
7722       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7723         // This is not safe in general for floating point:  
7724         // consider X== -0, Y== +0.
7725         // It becomes safe if either operand is a nonzero constant.
7726         ConstantFP *CFPt, *CFPf;
7727         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7728               !CFPt->getValueAPF().isZero()) ||
7729             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7730              !CFPf->getValueAPF().isZero()))
7731           return ReplaceInstUsesWith(SI, FalseVal);
7732       }
7733       // Transform (X != Y) ? Y : X  -> Y
7734       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7735         return ReplaceInstUsesWith(SI, TrueVal);
7736       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7737     }
7738   }
7739
7740   // See if we are selecting two values based on a comparison of the two values.
7741   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7742     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7743       // Transform (X == Y) ? X : Y  -> Y
7744       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7745         return ReplaceInstUsesWith(SI, FalseVal);
7746       // Transform (X != Y) ? X : Y  -> X
7747       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7748         return ReplaceInstUsesWith(SI, TrueVal);
7749       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7750
7751     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7752       // Transform (X == Y) ? Y : X  -> X
7753       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7754         return ReplaceInstUsesWith(SI, FalseVal);
7755       // Transform (X != Y) ? Y : X  -> Y
7756       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7757         return ReplaceInstUsesWith(SI, TrueVal);
7758       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7759     }
7760   }
7761
7762   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7763     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7764       if (TI->hasOneUse() && FI->hasOneUse()) {
7765         Instruction *AddOp = 0, *SubOp = 0;
7766
7767         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7768         if (TI->getOpcode() == FI->getOpcode())
7769           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7770             return IV;
7771
7772         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7773         // even legal for FP.
7774         if (TI->getOpcode() == Instruction::Sub &&
7775             FI->getOpcode() == Instruction::Add) {
7776           AddOp = FI; SubOp = TI;
7777         } else if (FI->getOpcode() == Instruction::Sub &&
7778                    TI->getOpcode() == Instruction::Add) {
7779           AddOp = TI; SubOp = FI;
7780         }
7781
7782         if (AddOp) {
7783           Value *OtherAddOp = 0;
7784           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7785             OtherAddOp = AddOp->getOperand(1);
7786           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7787             OtherAddOp = AddOp->getOperand(0);
7788           }
7789
7790           if (OtherAddOp) {
7791             // So at this point we know we have (Y -> OtherAddOp):
7792             //        select C, (add X, Y), (sub X, Z)
7793             Value *NegVal;  // Compute -Z
7794             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7795               NegVal = ConstantExpr::getNeg(C);
7796             } else {
7797               NegVal = InsertNewInstBefore(
7798                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7799             }
7800
7801             Value *NewTrueOp = OtherAddOp;
7802             Value *NewFalseOp = NegVal;
7803             if (AddOp != TI)
7804               std::swap(NewTrueOp, NewFalseOp);
7805             Instruction *NewSel =
7806               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7807
7808             NewSel = InsertNewInstBefore(NewSel, SI);
7809             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7810           }
7811         }
7812       }
7813
7814   // See if we can fold the select into one of our operands.
7815   if (SI.getType()->isInteger()) {
7816     // See the comment above GetSelectFoldableOperands for a description of the
7817     // transformation we are doing here.
7818     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7819       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7820           !isa<Constant>(FalseVal))
7821         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7822           unsigned OpToFold = 0;
7823           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7824             OpToFold = 1;
7825           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7826             OpToFold = 2;
7827           }
7828
7829           if (OpToFold) {
7830             Constant *C = GetSelectFoldableConstant(TVI);
7831             Instruction *NewSel =
7832               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7833             InsertNewInstBefore(NewSel, SI);
7834             NewSel->takeName(TVI);
7835             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7836               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7837             else {
7838               assert(0 && "Unknown instruction!!");
7839             }
7840           }
7841         }
7842
7843     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7844       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7845           !isa<Constant>(TrueVal))
7846         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7847           unsigned OpToFold = 0;
7848           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7849             OpToFold = 1;
7850           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7851             OpToFold = 2;
7852           }
7853
7854           if (OpToFold) {
7855             Constant *C = GetSelectFoldableConstant(FVI);
7856             Instruction *NewSel =
7857               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7858             InsertNewInstBefore(NewSel, SI);
7859             NewSel->takeName(FVI);
7860             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7861               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7862             else
7863               assert(0 && "Unknown instruction!!");
7864           }
7865         }
7866   }
7867
7868   if (BinaryOperator::isNot(CondVal)) {
7869     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7870     SI.setOperand(1, FalseVal);
7871     SI.setOperand(2, TrueVal);
7872     return &SI;
7873   }
7874
7875   return 0;
7876 }
7877
7878 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7879 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
7880 /// and it is more than the alignment of the ultimate object, see if we can
7881 /// increase the alignment of the ultimate object, making this check succeed.
7882 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7883                                            unsigned PrefAlign = 0) {
7884   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7885     unsigned Align = GV->getAlignment();
7886     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
7887       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7888
7889     // If there is a large requested alignment and we can, bump up the alignment
7890     // of the global.
7891     if (PrefAlign > Align && GV->hasInitializer()) {
7892       GV->setAlignment(PrefAlign);
7893       Align = PrefAlign;
7894     }
7895     return Align;
7896   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7897     unsigned Align = AI->getAlignment();
7898     if (Align == 0 && TD) {
7899       if (isa<AllocaInst>(AI))
7900         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7901       else if (isa<MallocInst>(AI)) {
7902         // Malloc returns maximally aligned memory.
7903         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7904         Align =
7905           std::max(Align,
7906                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7907         Align =
7908           std::max(Align,
7909                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7910       }
7911     }
7912     
7913     // If there is a requested alignment and if this is an alloca, round up.  We
7914     // don't do this for malloc, because some systems can't respect the request.
7915     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7916       AI->setAlignment(PrefAlign);
7917       Align = PrefAlign;
7918     }
7919     return Align;
7920   } else if (isa<BitCastInst>(V) ||
7921              (isa<ConstantExpr>(V) && 
7922               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7923     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7924                                       TD, PrefAlign);
7925   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7926     // If all indexes are zero, it is just the alignment of the base pointer.
7927     bool AllZeroOperands = true;
7928     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7929       if (!isa<Constant>(GEPI->getOperand(i)) ||
7930           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7931         AllZeroOperands = false;
7932         break;
7933       }
7934
7935     if (AllZeroOperands) {
7936       // Treat this like a bitcast.
7937       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7938     }
7939
7940     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7941     if (BaseAlignment == 0) return 0;
7942
7943     // Otherwise, if the base alignment is >= the alignment we expect for the
7944     // base pointer type, then we know that the resultant pointer is aligned at
7945     // least as much as its type requires.
7946     if (!TD) return 0;
7947
7948     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7949     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7950     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7951     if (Align <= BaseAlignment) {
7952       const Type *GEPTy = GEPI->getType();
7953       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7954       Align = std::min(Align, (unsigned)
7955                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7956       return Align;
7957     }
7958     return 0;
7959   }
7960   return 0;
7961 }
7962
7963 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7964   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7965   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7966   unsigned MinAlign = std::min(DstAlign, SrcAlign);
7967   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7968
7969   if (CopyAlign < MinAlign) {
7970     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7971     return MI;
7972   }
7973   
7974   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7975   // load/store.
7976   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7977   if (MemOpLength == 0) return 0;
7978   
7979   // Source and destination pointer types are always "i8*" for intrinsic.  See
7980   // if the size is something we can handle with a single primitive load/store.
7981   // A single load+store correctly handles overlapping memory in the memmove
7982   // case.
7983   unsigned Size = MemOpLength->getZExtValue();
7984   if (Size == 0 || Size > 8 || (Size&(Size-1)))
7985     return 0;  // If not 1/2/4/8 bytes, exit.
7986   
7987   // Use an integer load+store unless we can find something better.
7988   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
7989   
7990   // Memcpy forces the use of i8* for the source and destination.  That means
7991   // that if you're using memcpy to move one double around, you'll get a cast
7992   // from double* to i8*.  We'd much rather use a double load+store rather than
7993   // an i64 load+store, here because this improves the odds that the source or
7994   // dest address will be promotable.  See if we can find a better type than the
7995   // integer datatype.
7996   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
7997     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
7998     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
7999       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8000       // down through these levels if so.
8001       while (!SrcETy->isFirstClassType()) {
8002         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8003           if (STy->getNumElements() == 1)
8004             SrcETy = STy->getElementType(0);
8005           else
8006             break;
8007         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8008           if (ATy->getNumElements() == 1)
8009             SrcETy = ATy->getElementType();
8010           else
8011             break;
8012         } else
8013           break;
8014       }
8015       
8016       if (SrcETy->isFirstClassType())
8017         NewPtrTy = PointerType::getUnqual(SrcETy);
8018     }
8019   }
8020   
8021   
8022   // If the memcpy/memmove provides better alignment info than we can
8023   // infer, use it.
8024   SrcAlign = std::max(SrcAlign, CopyAlign);
8025   DstAlign = std::max(DstAlign, CopyAlign);
8026   
8027   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8028   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8029   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8030   InsertNewInstBefore(L, *MI);
8031   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8032
8033   // Set the size of the copy to 0, it will be deleted on the next iteration.
8034   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8035   return MI;
8036 }
8037
8038 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8039 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8040 /// the heavy lifting.
8041 ///
8042 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8043   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8044   if (!II) return visitCallSite(&CI);
8045   
8046   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8047   // visitCallSite.
8048   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8049     bool Changed = false;
8050
8051     // memmove/cpy/set of zero bytes is a noop.
8052     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8053       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8054
8055       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8056         if (CI->getZExtValue() == 1) {
8057           // Replace the instruction with just byte operations.  We would
8058           // transform other cases to loads/stores, but we don't know if
8059           // alignment is sufficient.
8060         }
8061     }
8062
8063     // If we have a memmove and the source operation is a constant global,
8064     // then the source and dest pointers can't alias, so we can change this
8065     // into a call to memcpy.
8066     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8067       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8068         if (GVSrc->isConstant()) {
8069           Module *M = CI.getParent()->getParent()->getParent();
8070           Intrinsic::ID MemCpyID;
8071           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8072             MemCpyID = Intrinsic::memcpy_i32;
8073           else
8074             MemCpyID = Intrinsic::memcpy_i64;
8075           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8076           Changed = true;
8077         }
8078     }
8079
8080     // If we can determine a pointer alignment that is bigger than currently
8081     // set, update the alignment.
8082     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8083       if (Instruction *I = SimplifyMemTransfer(MI))
8084         return I;
8085     } else if (isa<MemSetInst>(MI)) {
8086       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
8087       if (MI->getAlignment()->getZExtValue() < Alignment) {
8088         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8089         Changed = true;
8090       }
8091     }
8092           
8093     if (Changed) return II;
8094   } else {
8095     switch (II->getIntrinsicID()) {
8096     default: break;
8097     case Intrinsic::ppc_altivec_lvx:
8098     case Intrinsic::ppc_altivec_lvxl:
8099     case Intrinsic::x86_sse_loadu_ps:
8100     case Intrinsic::x86_sse2_loadu_pd:
8101     case Intrinsic::x86_sse2_loadu_dq:
8102       // Turn PPC lvx     -> load if the pointer is known aligned.
8103       // Turn X86 loadups -> load if the pointer is known aligned.
8104       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8105         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8106                                          PointerType::getUnqual(II->getType()),
8107                                          CI);
8108         return new LoadInst(Ptr);
8109       }
8110       break;
8111     case Intrinsic::ppc_altivec_stvx:
8112     case Intrinsic::ppc_altivec_stvxl:
8113       // Turn stvx -> store if the pointer is known aligned.
8114       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
8115         const Type *OpPtrTy = 
8116           PointerType::getUnqual(II->getOperand(1)->getType());
8117         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8118         return new StoreInst(II->getOperand(1), Ptr);
8119       }
8120       break;
8121     case Intrinsic::x86_sse_storeu_ps:
8122     case Intrinsic::x86_sse2_storeu_pd:
8123     case Intrinsic::x86_sse2_storeu_dq:
8124     case Intrinsic::x86_sse2_storel_dq:
8125       // Turn X86 storeu -> store if the pointer is known aligned.
8126       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8127         const Type *OpPtrTy = 
8128           PointerType::getUnqual(II->getOperand(2)->getType());
8129         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8130         return new StoreInst(II->getOperand(2), Ptr);
8131       }
8132       break;
8133       
8134     case Intrinsic::x86_sse_cvttss2si: {
8135       // These intrinsics only demands the 0th element of its input vector.  If
8136       // we can simplify the input based on that, do so now.
8137       uint64_t UndefElts;
8138       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8139                                                 UndefElts)) {
8140         II->setOperand(1, V);
8141         return II;
8142       }
8143       break;
8144     }
8145       
8146     case Intrinsic::ppc_altivec_vperm:
8147       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8148       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8149         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8150         
8151         // Check that all of the elements are integer constants or undefs.
8152         bool AllEltsOk = true;
8153         for (unsigned i = 0; i != 16; ++i) {
8154           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8155               !isa<UndefValue>(Mask->getOperand(i))) {
8156             AllEltsOk = false;
8157             break;
8158           }
8159         }
8160         
8161         if (AllEltsOk) {
8162           // Cast the input vectors to byte vectors.
8163           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8164           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8165           Value *Result = UndefValue::get(Op0->getType());
8166           
8167           // Only extract each element once.
8168           Value *ExtractedElts[32];
8169           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8170           
8171           for (unsigned i = 0; i != 16; ++i) {
8172             if (isa<UndefValue>(Mask->getOperand(i)))
8173               continue;
8174             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8175             Idx &= 31;  // Match the hardware behavior.
8176             
8177             if (ExtractedElts[Idx] == 0) {
8178               Instruction *Elt = 
8179                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8180               InsertNewInstBefore(Elt, CI);
8181               ExtractedElts[Idx] = Elt;
8182             }
8183           
8184             // Insert this value into the result vector.
8185             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8186             InsertNewInstBefore(cast<Instruction>(Result), CI);
8187           }
8188           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8189         }
8190       }
8191       break;
8192
8193     case Intrinsic::stackrestore: {
8194       // If the save is right next to the restore, remove the restore.  This can
8195       // happen when variable allocas are DCE'd.
8196       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8197         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8198           BasicBlock::iterator BI = SS;
8199           if (&*++BI == II)
8200             return EraseInstFromFunction(CI);
8201         }
8202       }
8203       
8204       // Scan down this block to see if there is another stack restore in the
8205       // same block without an intervening call/alloca.
8206       BasicBlock::iterator BI = II;
8207       TerminatorInst *TI = II->getParent()->getTerminator();
8208       bool CannotRemove = false;
8209       for (++BI; &*BI != TI; ++BI) {
8210         if (isa<AllocaInst>(BI)) {
8211           CannotRemove = true;
8212           break;
8213         }
8214         if (isa<CallInst>(BI)) {
8215           if (!isa<IntrinsicInst>(BI)) {
8216             CannotRemove = true;
8217             break;
8218           }
8219           // If there is a stackrestore below this one, remove this one.
8220           return EraseInstFromFunction(CI);
8221         }
8222       }
8223       
8224       // If the stack restore is in a return/unwind block and if there are no
8225       // allocas or calls between the restore and the return, nuke the restore.
8226       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8227         return EraseInstFromFunction(CI);
8228       break;
8229     }
8230     }
8231   }
8232
8233   return visitCallSite(II);
8234 }
8235
8236 // InvokeInst simplification
8237 //
8238 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8239   return visitCallSite(&II);
8240 }
8241
8242 // visitCallSite - Improvements for call and invoke instructions.
8243 //
8244 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8245   bool Changed = false;
8246
8247   // If the callee is a constexpr cast of a function, attempt to move the cast
8248   // to the arguments of the call/invoke.
8249   if (transformConstExprCastCall(CS)) return 0;
8250
8251   Value *Callee = CS.getCalledValue();
8252
8253   if (Function *CalleeF = dyn_cast<Function>(Callee))
8254     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8255       Instruction *OldCall = CS.getInstruction();
8256       // If the call and callee calling conventions don't match, this call must
8257       // be unreachable, as the call is undefined.
8258       new StoreInst(ConstantInt::getTrue(),
8259                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8260                                     OldCall);
8261       if (!OldCall->use_empty())
8262         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8263       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8264         return EraseInstFromFunction(*OldCall);
8265       return 0;
8266     }
8267
8268   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8269     // This instruction is not reachable, just remove it.  We insert a store to
8270     // undef so that we know that this code is not reachable, despite the fact
8271     // that we can't modify the CFG here.
8272     new StoreInst(ConstantInt::getTrue(),
8273                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8274                   CS.getInstruction());
8275
8276     if (!CS.getInstruction()->use_empty())
8277       CS.getInstruction()->
8278         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8279
8280     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8281       // Don't break the CFG, insert a dummy cond branch.
8282       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8283                      ConstantInt::getTrue(), II);
8284     }
8285     return EraseInstFromFunction(*CS.getInstruction());
8286   }
8287
8288   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8289     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8290       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8291         return transformCallThroughTrampoline(CS);
8292
8293   const PointerType *PTy = cast<PointerType>(Callee->getType());
8294   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8295   if (FTy->isVarArg()) {
8296     // See if we can optimize any arguments passed through the varargs area of
8297     // the call.
8298     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8299            E = CS.arg_end(); I != E; ++I)
8300       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8301         // If this cast does not effect the value passed through the varargs
8302         // area, we can eliminate the use of the cast.
8303         Value *Op = CI->getOperand(0);
8304         if (CI->isLosslessCast()) {
8305           *I = Op;
8306           Changed = true;
8307         }
8308       }
8309   }
8310
8311   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8312     // Inline asm calls cannot throw - mark them 'nounwind'.
8313     CS.setDoesNotThrow();
8314     Changed = true;
8315   }
8316
8317   return Changed ? CS.getInstruction() : 0;
8318 }
8319
8320 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8321 // attempt to move the cast to the arguments of the call/invoke.
8322 //
8323 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8324   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8325   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8326   if (CE->getOpcode() != Instruction::BitCast || 
8327       !isa<Function>(CE->getOperand(0)))
8328     return false;
8329   Function *Callee = cast<Function>(CE->getOperand(0));
8330   Instruction *Caller = CS.getInstruction();
8331   const ParamAttrsList* CallerPAL = CS.getParamAttrs();
8332
8333   // Okay, this is a cast from a function to a different type.  Unless doing so
8334   // would cause a type conversion of one of our arguments, change this call to
8335   // be a direct call with arguments casted to the appropriate types.
8336   //
8337   const FunctionType *FT = Callee->getFunctionType();
8338   const Type *OldRetTy = Caller->getType();
8339
8340   // Check to see if we are changing the return type...
8341   if (OldRetTy != FT->getReturnType()) {
8342     if (Callee->isDeclaration() && !Caller->use_empty() && 
8343         // Conversion is ok if changing from pointer to int of same size.
8344         !(isa<PointerType>(FT->getReturnType()) &&
8345           TD->getIntPtrType() == OldRetTy))
8346       return false;   // Cannot transform this return value.
8347
8348     if (!Caller->use_empty() &&
8349         // void -> non-void is handled specially
8350         FT->getReturnType() != Type::VoidTy &&
8351         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8352       return false;   // Cannot transform this return value.
8353
8354     if (CallerPAL && !Caller->use_empty()) {
8355       uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8356       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8357         return false;   // Attribute not compatible with transformed value.
8358     }
8359
8360     // If the callsite is an invoke instruction, and the return value is used by
8361     // a PHI node in a successor, we cannot change the return type of the call
8362     // because there is no place to put the cast instruction (without breaking
8363     // the critical edge).  Bail out in this case.
8364     if (!Caller->use_empty())
8365       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8366         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8367              UI != E; ++UI)
8368           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8369             if (PN->getParent() == II->getNormalDest() ||
8370                 PN->getParent() == II->getUnwindDest())
8371               return false;
8372   }
8373
8374   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8375   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8376
8377   CallSite::arg_iterator AI = CS.arg_begin();
8378   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8379     const Type *ParamTy = FT->getParamType(i);
8380     const Type *ActTy = (*AI)->getType();
8381
8382     if (!CastInst::isCastable(ActTy, ParamTy))
8383       return false;   // Cannot transform this parameter value.
8384
8385     if (CallerPAL) {
8386       uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8387       if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8388         return false;   // Attribute not compatible with transformed value.
8389     }
8390
8391     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8392     // Some conversions are safe even if we do not have a body.
8393     // Either we can cast directly, or we can upconvert the argument
8394     bool isConvertible = ActTy == ParamTy ||
8395       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8396       (ParamTy->isInteger() && ActTy->isInteger() &&
8397        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8398       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8399        && c->getValue().isStrictlyPositive());
8400     if (Callee->isDeclaration() && !isConvertible) return false;
8401   }
8402
8403   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8404       Callee->isDeclaration())
8405     return false;   // Do not delete arguments unless we have a function body...
8406
8407   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
8408     // In this case we have more arguments than the new function type, but we
8409     // won't be dropping them.  Check that these extra arguments have attributes
8410     // that are compatible with being a vararg call argument.
8411     for (unsigned i = CallerPAL->size(); i; --i) {
8412       if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8413         break;
8414       uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8415       if (PAttrs & ParamAttr::VarArgsIncompatible)
8416         return false;
8417     }
8418
8419   // Okay, we decided that this is a safe thing to do: go ahead and start
8420   // inserting cast instructions as necessary...
8421   std::vector<Value*> Args;
8422   Args.reserve(NumActualArgs);
8423   ParamAttrsVector attrVec;
8424   attrVec.reserve(NumCommonArgs);
8425
8426   // Get any return attributes.
8427   uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8428
8429   // If the return value is not being used, the type may not be compatible
8430   // with the existing attributes.  Wipe out any problematic attributes.
8431   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
8432
8433   // Add the new return attributes.
8434   if (RAttrs)
8435     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8436
8437   AI = CS.arg_begin();
8438   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8439     const Type *ParamTy = FT->getParamType(i);
8440     if ((*AI)->getType() == ParamTy) {
8441       Args.push_back(*AI);
8442     } else {
8443       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8444           false, ParamTy, false);
8445       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8446       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8447     }
8448
8449     // Add any parameter attributes.
8450     uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8451     if (PAttrs)
8452       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8453   }
8454
8455   // If the function takes more arguments than the call was taking, add them
8456   // now...
8457   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8458     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8459
8460   // If we are removing arguments to the function, emit an obnoxious warning...
8461   if (FT->getNumParams() < NumActualArgs)
8462     if (!FT->isVarArg()) {
8463       cerr << "WARNING: While resolving call to function '"
8464            << Callee->getName() << "' arguments were dropped!\n";
8465     } else {
8466       // Add all of the arguments in their promoted form to the arg list...
8467       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8468         const Type *PTy = getPromotedType((*AI)->getType());
8469         if (PTy != (*AI)->getType()) {
8470           // Must promote to pass through va_arg area!
8471           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8472                                                                 PTy, false);
8473           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8474           InsertNewInstBefore(Cast, *Caller);
8475           Args.push_back(Cast);
8476         } else {
8477           Args.push_back(*AI);
8478         }
8479
8480         // Add any parameter attributes.
8481         uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8482         if (PAttrs)
8483           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8484       }
8485     }
8486
8487   if (FT->getReturnType() == Type::VoidTy)
8488     Caller->setName("");   // Void type should not have a name.
8489
8490   const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8491
8492   Instruction *NC;
8493   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8494     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8495                         Args.begin(), Args.end(), Caller->getName(), Caller);
8496     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8497     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8498   } else {
8499     NC = new CallInst(Callee, Args.begin(), Args.end(),
8500                       Caller->getName(), Caller);
8501     CallInst *CI = cast<CallInst>(Caller);
8502     if (CI->isTailCall())
8503       cast<CallInst>(NC)->setTailCall();
8504     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8505     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8506   }
8507
8508   // Insert a cast of the return type as necessary.
8509   Value *NV = NC;
8510   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8511     if (NV->getType() != Type::VoidTy) {
8512       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8513                                                             OldRetTy, false);
8514       NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
8515
8516       // If this is an invoke instruction, we should insert it after the first
8517       // non-phi, instruction in the normal successor block.
8518       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8519         BasicBlock::iterator I = II->getNormalDest()->begin();
8520         while (isa<PHINode>(I)) ++I;
8521         InsertNewInstBefore(NC, *I);
8522       } else {
8523         // Otherwise, it's a call, just insert cast right after the call instr
8524         InsertNewInstBefore(NC, *Caller);
8525       }
8526       AddUsersToWorkList(*Caller);
8527     } else {
8528       NV = UndefValue::get(Caller->getType());
8529     }
8530   }
8531
8532   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8533     Caller->replaceAllUsesWith(NV);
8534   Caller->eraseFromParent();
8535   RemoveFromWorkList(Caller);
8536   return true;
8537 }
8538
8539 // transformCallThroughTrampoline - Turn a call to a function created by the
8540 // init_trampoline intrinsic into a direct call to the underlying function.
8541 //
8542 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8543   Value *Callee = CS.getCalledValue();
8544   const PointerType *PTy = cast<PointerType>(Callee->getType());
8545   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8546   const ParamAttrsList *Attrs = CS.getParamAttrs();
8547
8548   // If the call already has the 'nest' attribute somewhere then give up -
8549   // otherwise 'nest' would occur twice after splicing in the chain.
8550   if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8551     return 0;
8552
8553   IntrinsicInst *Tramp =
8554     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8555
8556   Function *NestF =
8557     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8558   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8559   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8560
8561   if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
8562     unsigned NestIdx = 1;
8563     const Type *NestTy = 0;
8564     uint16_t NestAttr = 0;
8565
8566     // Look for a parameter marked with the 'nest' attribute.
8567     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8568          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8569       if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8570         // Record the parameter type and any other attributes.
8571         NestTy = *I;
8572         NestAttr = NestAttrs->getParamAttrs(NestIdx);
8573         break;
8574       }
8575
8576     if (NestTy) {
8577       Instruction *Caller = CS.getInstruction();
8578       std::vector<Value*> NewArgs;
8579       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8580
8581       ParamAttrsVector NewAttrs;
8582       NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8583
8584       // Insert the nest argument into the call argument list, which may
8585       // mean appending it.  Likewise for attributes.
8586
8587       // Add any function result attributes.
8588       uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8589       if (Attr)
8590         NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8591
8592       {
8593         unsigned Idx = 1;
8594         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8595         do {
8596           if (Idx == NestIdx) {
8597             // Add the chain argument and attributes.
8598             Value *NestVal = Tramp->getOperand(3);
8599             if (NestVal->getType() != NestTy)
8600               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8601             NewArgs.push_back(NestVal);
8602             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8603           }
8604
8605           if (I == E)
8606             break;
8607
8608           // Add the original argument and attributes.
8609           NewArgs.push_back(*I);
8610           Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8611           if (Attr)
8612             NewAttrs.push_back
8613               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8614
8615           ++Idx, ++I;
8616         } while (1);
8617       }
8618
8619       // The trampoline may have been bitcast to a bogus type (FTy).
8620       // Handle this by synthesizing a new function type, equal to FTy
8621       // with the chain parameter inserted.
8622
8623       std::vector<const Type*> NewTypes;
8624       NewTypes.reserve(FTy->getNumParams()+1);
8625
8626       // Insert the chain's type into the list of parameter types, which may
8627       // mean appending it.
8628       {
8629         unsigned Idx = 1;
8630         FunctionType::param_iterator I = FTy->param_begin(),
8631           E = FTy->param_end();
8632
8633         do {
8634           if (Idx == NestIdx)
8635             // Add the chain's type.
8636             NewTypes.push_back(NestTy);
8637
8638           if (I == E)
8639             break;
8640
8641           // Add the original type.
8642           NewTypes.push_back(*I);
8643
8644           ++Idx, ++I;
8645         } while (1);
8646       }
8647
8648       // Replace the trampoline call with a direct call.  Let the generic
8649       // code sort out any function type mismatches.
8650       FunctionType *NewFTy =
8651         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8652       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8653         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8654       const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
8655
8656       Instruction *NewCaller;
8657       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8658         NewCaller = new InvokeInst(NewCallee,
8659                                    II->getNormalDest(), II->getUnwindDest(),
8660                                    NewArgs.begin(), NewArgs.end(),
8661                                    Caller->getName(), Caller);
8662         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8663         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8664       } else {
8665         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8666                                  Caller->getName(), Caller);
8667         if (cast<CallInst>(Caller)->isTailCall())
8668           cast<CallInst>(NewCaller)->setTailCall();
8669         cast<CallInst>(NewCaller)->
8670           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8671         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8672       }
8673       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8674         Caller->replaceAllUsesWith(NewCaller);
8675       Caller->eraseFromParent();
8676       RemoveFromWorkList(Caller);
8677       return 0;
8678     }
8679   }
8680
8681   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8682   // parameter, there is no need to adjust the argument list.  Let the generic
8683   // code sort out any function type mismatches.
8684   Constant *NewCallee =
8685     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8686   CS.setCalledFunction(NewCallee);
8687   return CS.getInstruction();
8688 }
8689
8690 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8691 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8692 /// and a single binop.
8693 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8694   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8695   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8696          isa<CmpInst>(FirstInst));
8697   unsigned Opc = FirstInst->getOpcode();
8698   Value *LHSVal = FirstInst->getOperand(0);
8699   Value *RHSVal = FirstInst->getOperand(1);
8700     
8701   const Type *LHSType = LHSVal->getType();
8702   const Type *RHSType = RHSVal->getType();
8703   
8704   // Scan to see if all operands are the same opcode, all have one use, and all
8705   // kill their operands (i.e. the operands have one use).
8706   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8707     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8708     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8709         // Verify type of the LHS matches so we don't fold cmp's of different
8710         // types or GEP's with different index types.
8711         I->getOperand(0)->getType() != LHSType ||
8712         I->getOperand(1)->getType() != RHSType)
8713       return 0;
8714
8715     // If they are CmpInst instructions, check their predicates
8716     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8717       if (cast<CmpInst>(I)->getPredicate() !=
8718           cast<CmpInst>(FirstInst)->getPredicate())
8719         return 0;
8720     
8721     // Keep track of which operand needs a phi node.
8722     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8723     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8724   }
8725   
8726   // Otherwise, this is safe to transform, determine if it is profitable.
8727
8728   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8729   // Indexes are often folded into load/store instructions, so we don't want to
8730   // hide them behind a phi.
8731   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8732     return 0;
8733   
8734   Value *InLHS = FirstInst->getOperand(0);
8735   Value *InRHS = FirstInst->getOperand(1);
8736   PHINode *NewLHS = 0, *NewRHS = 0;
8737   if (LHSVal == 0) {
8738     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8739     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8740     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8741     InsertNewInstBefore(NewLHS, PN);
8742     LHSVal = NewLHS;
8743   }
8744   
8745   if (RHSVal == 0) {
8746     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8747     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8748     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8749     InsertNewInstBefore(NewRHS, PN);
8750     RHSVal = NewRHS;
8751   }
8752   
8753   // Add all operands to the new PHIs.
8754   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8755     if (NewLHS) {
8756       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8757       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8758     }
8759     if (NewRHS) {
8760       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8761       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8762     }
8763   }
8764     
8765   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8766     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8767   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8768     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8769                            RHSVal);
8770   else {
8771     assert(isa<GetElementPtrInst>(FirstInst));
8772     return new GetElementPtrInst(LHSVal, RHSVal);
8773   }
8774 }
8775
8776 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8777 /// of the block that defines it.  This means that it must be obvious the value
8778 /// of the load is not changed from the point of the load to the end of the
8779 /// block it is in.
8780 ///
8781 /// Finally, it is safe, but not profitable, to sink a load targetting a
8782 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8783 /// to a register.
8784 static bool isSafeToSinkLoad(LoadInst *L) {
8785   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8786   
8787   for (++BBI; BBI != E; ++BBI)
8788     if (BBI->mayWriteToMemory())
8789       return false;
8790   
8791   // Check for non-address taken alloca.  If not address-taken already, it isn't
8792   // profitable to do this xform.
8793   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8794     bool isAddressTaken = false;
8795     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8796          UI != E; ++UI) {
8797       if (isa<LoadInst>(UI)) continue;
8798       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8799         // If storing TO the alloca, then the address isn't taken.
8800         if (SI->getOperand(1) == AI) continue;
8801       }
8802       isAddressTaken = true;
8803       break;
8804     }
8805     
8806     if (!isAddressTaken)
8807       return false;
8808   }
8809   
8810   return true;
8811 }
8812
8813
8814 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8815 // operator and they all are only used by the PHI, PHI together their
8816 // inputs, and do the operation once, to the result of the PHI.
8817 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8818   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8819
8820   // Scan the instruction, looking for input operations that can be folded away.
8821   // If all input operands to the phi are the same instruction (e.g. a cast from
8822   // the same type or "+42") we can pull the operation through the PHI, reducing
8823   // code size and simplifying code.
8824   Constant *ConstantOp = 0;
8825   const Type *CastSrcTy = 0;
8826   bool isVolatile = false;
8827   if (isa<CastInst>(FirstInst)) {
8828     CastSrcTy = FirstInst->getOperand(0)->getType();
8829   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8830     // Can fold binop, compare or shift here if the RHS is a constant, 
8831     // otherwise call FoldPHIArgBinOpIntoPHI.
8832     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8833     if (ConstantOp == 0)
8834       return FoldPHIArgBinOpIntoPHI(PN);
8835   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8836     isVolatile = LI->isVolatile();
8837     // We can't sink the load if the loaded value could be modified between the
8838     // load and the PHI.
8839     if (LI->getParent() != PN.getIncomingBlock(0) ||
8840         !isSafeToSinkLoad(LI))
8841       return 0;
8842   } else if (isa<GetElementPtrInst>(FirstInst)) {
8843     if (FirstInst->getNumOperands() == 2)
8844       return FoldPHIArgBinOpIntoPHI(PN);
8845     // Can't handle general GEPs yet.
8846     return 0;
8847   } else {
8848     return 0;  // Cannot fold this operation.
8849   }
8850
8851   // Check to see if all arguments are the same operation.
8852   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8853     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8854     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8855     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8856       return 0;
8857     if (CastSrcTy) {
8858       if (I->getOperand(0)->getType() != CastSrcTy)
8859         return 0;  // Cast operation must match.
8860     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8861       // We can't sink the load if the loaded value could be modified between 
8862       // the load and the PHI.
8863       if (LI->isVolatile() != isVolatile ||
8864           LI->getParent() != PN.getIncomingBlock(i) ||
8865           !isSafeToSinkLoad(LI))
8866         return 0;
8867     } else if (I->getOperand(1) != ConstantOp) {
8868       return 0;
8869     }
8870   }
8871
8872   // Okay, they are all the same operation.  Create a new PHI node of the
8873   // correct type, and PHI together all of the LHS's of the instructions.
8874   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8875                                PN.getName()+".in");
8876   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8877
8878   Value *InVal = FirstInst->getOperand(0);
8879   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8880
8881   // Add all operands to the new PHI.
8882   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8883     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8884     if (NewInVal != InVal)
8885       InVal = 0;
8886     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8887   }
8888
8889   Value *PhiVal;
8890   if (InVal) {
8891     // The new PHI unions all of the same values together.  This is really
8892     // common, so we handle it intelligently here for compile-time speed.
8893     PhiVal = InVal;
8894     delete NewPN;
8895   } else {
8896     InsertNewInstBefore(NewPN, PN);
8897     PhiVal = NewPN;
8898   }
8899
8900   // Insert and return the new operation.
8901   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8902     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8903   else if (isa<LoadInst>(FirstInst))
8904     return new LoadInst(PhiVal, "", isVolatile);
8905   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8906     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8907   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8908     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8909                            PhiVal, ConstantOp);
8910   else
8911     assert(0 && "Unknown operation");
8912   return 0;
8913 }
8914
8915 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8916 /// that is dead.
8917 static bool DeadPHICycle(PHINode *PN,
8918                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8919   if (PN->use_empty()) return true;
8920   if (!PN->hasOneUse()) return false;
8921
8922   // Remember this node, and if we find the cycle, return.
8923   if (!PotentiallyDeadPHIs.insert(PN))
8924     return true;
8925   
8926   // Don't scan crazily complex things.
8927   if (PotentiallyDeadPHIs.size() == 16)
8928     return false;
8929
8930   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8931     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8932
8933   return false;
8934 }
8935
8936 /// PHIsEqualValue - Return true if this phi node is always equal to
8937 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
8938 ///   z = some value; x = phi (y, z); y = phi (x, z)
8939 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
8940                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8941   // See if we already saw this PHI node.
8942   if (!ValueEqualPHIs.insert(PN))
8943     return true;
8944   
8945   // Don't scan crazily complex things.
8946   if (ValueEqualPHIs.size() == 16)
8947     return false;
8948  
8949   // Scan the operands to see if they are either phi nodes or are equal to
8950   // the value.
8951   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8952     Value *Op = PN->getIncomingValue(i);
8953     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8954       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8955         return false;
8956     } else if (Op != NonPhiInVal)
8957       return false;
8958   }
8959   
8960   return true;
8961 }
8962
8963
8964 // PHINode simplification
8965 //
8966 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8967   // If LCSSA is around, don't mess with Phi nodes
8968   if (MustPreserveLCSSA) return 0;
8969   
8970   if (Value *V = PN.hasConstantValue())
8971     return ReplaceInstUsesWith(PN, V);
8972
8973   // If all PHI operands are the same operation, pull them through the PHI,
8974   // reducing code size.
8975   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8976       PN.getIncomingValue(0)->hasOneUse())
8977     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8978       return Result;
8979
8980   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8981   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8982   // PHI)... break the cycle.
8983   if (PN.hasOneUse()) {
8984     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8985     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8986       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8987       PotentiallyDeadPHIs.insert(&PN);
8988       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8989         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8990     }
8991    
8992     // If this phi has a single use, and if that use just computes a value for
8993     // the next iteration of a loop, delete the phi.  This occurs with unused
8994     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8995     // common case here is good because the only other things that catch this
8996     // are induction variable analysis (sometimes) and ADCE, which is only run
8997     // late.
8998     if (PHIUser->hasOneUse() &&
8999         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9000         PHIUser->use_back() == &PN) {
9001       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9002     }
9003   }
9004
9005   // We sometimes end up with phi cycles that non-obviously end up being the
9006   // same value, for example:
9007   //   z = some value; x = phi (y, z); y = phi (x, z)
9008   // where the phi nodes don't necessarily need to be in the same block.  Do a
9009   // quick check to see if the PHI node only contains a single non-phi value, if
9010   // so, scan to see if the phi cycle is actually equal to that value.
9011   {
9012     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9013     // Scan for the first non-phi operand.
9014     while (InValNo != NumOperandVals && 
9015            isa<PHINode>(PN.getIncomingValue(InValNo)))
9016       ++InValNo;
9017
9018     if (InValNo != NumOperandVals) {
9019       Value *NonPhiInVal = PN.getOperand(InValNo);
9020       
9021       // Scan the rest of the operands to see if there are any conflicts, if so
9022       // there is no need to recursively scan other phis.
9023       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9024         Value *OpVal = PN.getIncomingValue(InValNo);
9025         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9026           break;
9027       }
9028       
9029       // If we scanned over all operands, then we have one unique value plus
9030       // phi values.  Scan PHI nodes to see if they all merge in each other or
9031       // the value.
9032       if (InValNo == NumOperandVals) {
9033         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9034         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9035           return ReplaceInstUsesWith(PN, NonPhiInVal);
9036       }
9037     }
9038   }
9039   return 0;
9040 }
9041
9042 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9043                                    Instruction *InsertPoint,
9044                                    InstCombiner *IC) {
9045   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9046   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9047   // We must cast correctly to the pointer type. Ensure that we
9048   // sign extend the integer value if it is smaller as this is
9049   // used for address computation.
9050   Instruction::CastOps opcode = 
9051      (VTySize < PtrSize ? Instruction::SExt :
9052       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9053   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9054 }
9055
9056
9057 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9058   Value *PtrOp = GEP.getOperand(0);
9059   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9060   // If so, eliminate the noop.
9061   if (GEP.getNumOperands() == 1)
9062     return ReplaceInstUsesWith(GEP, PtrOp);
9063
9064   if (isa<UndefValue>(GEP.getOperand(0)))
9065     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9066
9067   bool HasZeroPointerIndex = false;
9068   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9069     HasZeroPointerIndex = C->isNullValue();
9070
9071   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9072     return ReplaceInstUsesWith(GEP, PtrOp);
9073
9074   // Eliminate unneeded casts for indices.
9075   bool MadeChange = false;
9076   
9077   gep_type_iterator GTI = gep_type_begin(GEP);
9078   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9079     if (isa<SequentialType>(*GTI)) {
9080       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9081         if (CI->getOpcode() == Instruction::ZExt ||
9082             CI->getOpcode() == Instruction::SExt) {
9083           const Type *SrcTy = CI->getOperand(0)->getType();
9084           // We can eliminate a cast from i32 to i64 iff the target 
9085           // is a 32-bit pointer target.
9086           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9087             MadeChange = true;
9088             GEP.setOperand(i, CI->getOperand(0));
9089           }
9090         }
9091       }
9092       // If we are using a wider index than needed for this platform, shrink it
9093       // to what we need.  If the incoming value needs a cast instruction,
9094       // insert it.  This explicit cast can make subsequent optimizations more
9095       // obvious.
9096       Value *Op = GEP.getOperand(i);
9097       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
9098         if (Constant *C = dyn_cast<Constant>(Op)) {
9099           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9100           MadeChange = true;
9101         } else {
9102           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9103                                 GEP);
9104           GEP.setOperand(i, Op);
9105           MadeChange = true;
9106         }
9107     }
9108   }
9109   if (MadeChange) return &GEP;
9110
9111   // If this GEP instruction doesn't move the pointer, and if the input operand
9112   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9113   // real input to the dest type.
9114   if (GEP.hasAllZeroIndices()) {
9115     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9116       // If the bitcast is of an allocation, and the allocation will be
9117       // converted to match the type of the cast, don't touch this.
9118       if (isa<AllocationInst>(BCI->getOperand(0))) {
9119         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9120         if (Instruction *I = visitBitCast(*BCI)) {
9121           if (I != BCI) {
9122             I->takeName(BCI);
9123             BCI->getParent()->getInstList().insert(BCI, I);
9124             ReplaceInstUsesWith(*BCI, I);
9125           }
9126           return &GEP;
9127         }
9128       }
9129       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9130     }
9131   }
9132   
9133   // Combine Indices - If the source pointer to this getelementptr instruction
9134   // is a getelementptr instruction, combine the indices of the two
9135   // getelementptr instructions into a single instruction.
9136   //
9137   SmallVector<Value*, 8> SrcGEPOperands;
9138   if (User *Src = dyn_castGetElementPtr(PtrOp))
9139     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9140
9141   if (!SrcGEPOperands.empty()) {
9142     // Note that if our source is a gep chain itself that we wait for that
9143     // chain to be resolved before we perform this transformation.  This
9144     // avoids us creating a TON of code in some cases.
9145     //
9146     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9147         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9148       return 0;   // Wait until our source is folded to completion.
9149
9150     SmallVector<Value*, 8> Indices;
9151
9152     // Find out whether the last index in the source GEP is a sequential idx.
9153     bool EndsWithSequential = false;
9154     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9155            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9156       EndsWithSequential = !isa<StructType>(*I);
9157
9158     // Can we combine the two pointer arithmetics offsets?
9159     if (EndsWithSequential) {
9160       // Replace: gep (gep %P, long B), long A, ...
9161       // With:    T = long A+B; gep %P, T, ...
9162       //
9163       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9164       if (SO1 == Constant::getNullValue(SO1->getType())) {
9165         Sum = GO1;
9166       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9167         Sum = SO1;
9168       } else {
9169         // If they aren't the same type, convert both to an integer of the
9170         // target's pointer size.
9171         if (SO1->getType() != GO1->getType()) {
9172           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9173             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9174           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9175             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9176           } else {
9177             unsigned PS = TD->getPointerSizeInBits();
9178             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9179               // Convert GO1 to SO1's type.
9180               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9181
9182             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9183               // Convert SO1 to GO1's type.
9184               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9185             } else {
9186               const Type *PT = TD->getIntPtrType();
9187               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9188               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9189             }
9190           }
9191         }
9192         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9193           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9194         else {
9195           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9196           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9197         }
9198       }
9199
9200       // Recycle the GEP we already have if possible.
9201       if (SrcGEPOperands.size() == 2) {
9202         GEP.setOperand(0, SrcGEPOperands[0]);
9203         GEP.setOperand(1, Sum);
9204         return &GEP;
9205       } else {
9206         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9207                        SrcGEPOperands.end()-1);
9208         Indices.push_back(Sum);
9209         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9210       }
9211     } else if (isa<Constant>(*GEP.idx_begin()) &&
9212                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9213                SrcGEPOperands.size() != 1) {
9214       // Otherwise we can do the fold if the first index of the GEP is a zero
9215       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9216                      SrcGEPOperands.end());
9217       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9218     }
9219
9220     if (!Indices.empty())
9221       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9222                                    Indices.end(), GEP.getName());
9223
9224   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9225     // GEP of global variable.  If all of the indices for this GEP are
9226     // constants, we can promote this to a constexpr instead of an instruction.
9227
9228     // Scan for nonconstants...
9229     SmallVector<Constant*, 8> Indices;
9230     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9231     for (; I != E && isa<Constant>(*I); ++I)
9232       Indices.push_back(cast<Constant>(*I));
9233
9234     if (I == E) {  // If they are all constants...
9235       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9236                                                     &Indices[0],Indices.size());
9237
9238       // Replace all uses of the GEP with the new constexpr...
9239       return ReplaceInstUsesWith(GEP, CE);
9240     }
9241   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9242     if (!isa<PointerType>(X->getType())) {
9243       // Not interesting.  Source pointer must be a cast from pointer.
9244     } else if (HasZeroPointerIndex) {
9245       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9246       // into     : GEP [10 x i8]* X, i32 0, ...
9247       //
9248       // This occurs when the program declares an array extern like "int X[];"
9249       //
9250       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9251       const PointerType *XTy = cast<PointerType>(X->getType());
9252       if (const ArrayType *XATy =
9253           dyn_cast<ArrayType>(XTy->getElementType()))
9254         if (const ArrayType *CATy =
9255             dyn_cast<ArrayType>(CPTy->getElementType()))
9256           if (CATy->getElementType() == XATy->getElementType()) {
9257             // At this point, we know that the cast source type is a pointer
9258             // to an array of the same type as the destination pointer
9259             // array.  Because the array type is never stepped over (there
9260             // is a leading zero) we can fold the cast into this GEP.
9261             GEP.setOperand(0, X);
9262             return &GEP;
9263           }
9264     } else if (GEP.getNumOperands() == 2) {
9265       // Transform things like:
9266       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9267       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9268       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9269       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9270       if (isa<ArrayType>(SrcElTy) &&
9271           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9272           TD->getABITypeSize(ResElTy)) {
9273         Value *Idx[2];
9274         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9275         Idx[1] = GEP.getOperand(1);
9276         Value *V = InsertNewInstBefore(
9277                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
9278         // V and GEP are both pointer types --> BitCast
9279         return new BitCastInst(V, GEP.getType());
9280       }
9281       
9282       // Transform things like:
9283       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9284       //   (where tmp = 8*tmp2) into:
9285       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9286       
9287       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9288         uint64_t ArrayEltSize =
9289             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9290         
9291         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9292         // allow either a mul, shift, or constant here.
9293         Value *NewIdx = 0;
9294         ConstantInt *Scale = 0;
9295         if (ArrayEltSize == 1) {
9296           NewIdx = GEP.getOperand(1);
9297           Scale = ConstantInt::get(NewIdx->getType(), 1);
9298         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9299           NewIdx = ConstantInt::get(CI->getType(), 1);
9300           Scale = CI;
9301         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9302           if (Inst->getOpcode() == Instruction::Shl &&
9303               isa<ConstantInt>(Inst->getOperand(1))) {
9304             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9305             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9306             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9307             NewIdx = Inst->getOperand(0);
9308           } else if (Inst->getOpcode() == Instruction::Mul &&
9309                      isa<ConstantInt>(Inst->getOperand(1))) {
9310             Scale = cast<ConstantInt>(Inst->getOperand(1));
9311             NewIdx = Inst->getOperand(0);
9312           }
9313         }
9314         
9315         // If the index will be to exactly the right offset with the scale taken
9316         // out, perform the transformation. Note, we don't know whether Scale is
9317         // signed or not. We'll use unsigned version of division/modulo
9318         // operation after making sure Scale doesn't have the sign bit set.
9319         if (Scale && Scale->getSExtValue() >= 0LL &&
9320             Scale->getZExtValue() % ArrayEltSize == 0) {
9321           Scale = ConstantInt::get(Scale->getType(),
9322                                    Scale->getZExtValue() / ArrayEltSize);
9323           if (Scale->getZExtValue() != 1) {
9324             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9325                                                        false /*ZExt*/);
9326             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9327             NewIdx = InsertNewInstBefore(Sc, GEP);
9328           }
9329
9330           // Insert the new GEP instruction.
9331           Value *Idx[2];
9332           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9333           Idx[1] = NewIdx;
9334           Instruction *NewGEP =
9335             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9336           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9337           // The NewGEP must be pointer typed, so must the old one -> BitCast
9338           return new BitCastInst(NewGEP, GEP.getType());
9339         }
9340       }
9341     }
9342   }
9343
9344   return 0;
9345 }
9346
9347 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9348   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9349   if (AI.isArrayAllocation())    // Check C != 1
9350     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9351       const Type *NewTy = 
9352         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9353       AllocationInst *New = 0;
9354
9355       // Create and insert the replacement instruction...
9356       if (isa<MallocInst>(AI))
9357         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9358       else {
9359         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9360         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9361       }
9362
9363       InsertNewInstBefore(New, AI);
9364
9365       // Scan to the end of the allocation instructions, to skip over a block of
9366       // allocas if possible...
9367       //
9368       BasicBlock::iterator It = New;
9369       while (isa<AllocationInst>(*It)) ++It;
9370
9371       // Now that I is pointing to the first non-allocation-inst in the block,
9372       // insert our getelementptr instruction...
9373       //
9374       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9375       Value *Idx[2];
9376       Idx[0] = NullIdx;
9377       Idx[1] = NullIdx;
9378       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9379                                        New->getName()+".sub", It);
9380
9381       // Now make everything use the getelementptr instead of the original
9382       // allocation.
9383       return ReplaceInstUsesWith(AI, V);
9384     } else if (isa<UndefValue>(AI.getArraySize())) {
9385       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9386     }
9387
9388   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9389   // Note that we only do this for alloca's, because malloc should allocate and
9390   // return a unique pointer, even for a zero byte allocation.
9391   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9392       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9393     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9394
9395   return 0;
9396 }
9397
9398 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9399   Value *Op = FI.getOperand(0);
9400
9401   // free undef -> unreachable.
9402   if (isa<UndefValue>(Op)) {
9403     // Insert a new store to null because we cannot modify the CFG here.
9404     new StoreInst(ConstantInt::getTrue(),
9405                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9406     return EraseInstFromFunction(FI);
9407   }
9408   
9409   // If we have 'free null' delete the instruction.  This can happen in stl code
9410   // when lots of inlining happens.
9411   if (isa<ConstantPointerNull>(Op))
9412     return EraseInstFromFunction(FI);
9413   
9414   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9415   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9416     FI.setOperand(0, CI->getOperand(0));
9417     return &FI;
9418   }
9419   
9420   // Change free (gep X, 0,0,0,0) into free(X)
9421   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9422     if (GEPI->hasAllZeroIndices()) {
9423       AddToWorkList(GEPI);
9424       FI.setOperand(0, GEPI->getOperand(0));
9425       return &FI;
9426     }
9427   }
9428   
9429   // Change free(malloc) into nothing, if the malloc has a single use.
9430   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9431     if (MI->hasOneUse()) {
9432       EraseInstFromFunction(FI);
9433       return EraseInstFromFunction(*MI);
9434     }
9435
9436   return 0;
9437 }
9438
9439
9440 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9441 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9442                                         const TargetData *TD) {
9443   User *CI = cast<User>(LI.getOperand(0));
9444   Value *CastOp = CI->getOperand(0);
9445
9446   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9447     // Instead of loading constant c string, use corresponding integer value
9448     // directly if string length is small enough.
9449     const std::string &Str = CE->getOperand(0)->getStringValue();
9450     if (!Str.empty()) {
9451       unsigned len = Str.length();
9452       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9453       unsigned numBits = Ty->getPrimitiveSizeInBits();
9454       // Replace LI with immediate integer store.
9455       if ((numBits >> 3) == len + 1) {
9456         APInt StrVal(numBits, 0);
9457         APInt SingleChar(numBits, 0);
9458         if (TD->isLittleEndian()) {
9459           for (signed i = len-1; i >= 0; i--) {
9460             SingleChar = (uint64_t) Str[i];
9461             StrVal = (StrVal << 8) | SingleChar;
9462           }
9463         } else {
9464           for (unsigned i = 0; i < len; i++) {
9465             SingleChar = (uint64_t) Str[i];
9466                 StrVal = (StrVal << 8) | SingleChar;
9467           }
9468           // Append NULL at the end.
9469           SingleChar = 0;
9470           StrVal = (StrVal << 8) | SingleChar;
9471         }
9472         Value *NL = ConstantInt::get(StrVal);
9473         return IC.ReplaceInstUsesWith(LI, NL);
9474       }
9475     }
9476   }
9477
9478   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9479   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9480     const Type *SrcPTy = SrcTy->getElementType();
9481
9482     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9483          isa<VectorType>(DestPTy)) {
9484       // If the source is an array, the code below will not succeed.  Check to
9485       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9486       // constants.
9487       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9488         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9489           if (ASrcTy->getNumElements() != 0) {
9490             Value *Idxs[2];
9491             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9492             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9493             SrcTy = cast<PointerType>(CastOp->getType());
9494             SrcPTy = SrcTy->getElementType();
9495           }
9496
9497       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9498             isa<VectorType>(SrcPTy)) &&
9499           // Do not allow turning this into a load of an integer, which is then
9500           // casted to a pointer, this pessimizes pointer analysis a lot.
9501           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9502           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9503                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9504
9505         // Okay, we are casting from one integer or pointer type to another of
9506         // the same size.  Instead of casting the pointer before the load, cast
9507         // the result of the loaded value.
9508         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9509                                                              CI->getName(),
9510                                                          LI.isVolatile()),LI);
9511         // Now cast the result of the load.
9512         return new BitCastInst(NewLoad, LI.getType());
9513       }
9514     }
9515   }
9516   return 0;
9517 }
9518
9519 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9520 /// from this value cannot trap.  If it is not obviously safe to load from the
9521 /// specified pointer, we do a quick local scan of the basic block containing
9522 /// ScanFrom, to determine if the address is already accessed.
9523 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9524   // If it is an alloca it is always safe to load from.
9525   if (isa<AllocaInst>(V)) return true;
9526
9527   // If it is a global variable it is mostly safe to load from.
9528   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9529     // Don't try to evaluate aliases.  External weak GV can be null.
9530     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9531
9532   // Otherwise, be a little bit agressive by scanning the local block where we
9533   // want to check to see if the pointer is already being loaded or stored
9534   // from/to.  If so, the previous load or store would have already trapped,
9535   // so there is no harm doing an extra load (also, CSE will later eliminate
9536   // the load entirely).
9537   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9538
9539   while (BBI != E) {
9540     --BBI;
9541
9542     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9543       if (LI->getOperand(0) == V) return true;
9544     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9545       if (SI->getOperand(1) == V) return true;
9546
9547   }
9548   return false;
9549 }
9550
9551 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9552 /// until we find the underlying object a pointer is referring to or something
9553 /// we don't understand.  Note that the returned pointer may be offset from the
9554 /// input, because we ignore GEP indices.
9555 static Value *GetUnderlyingObject(Value *Ptr) {
9556   while (1) {
9557     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9558       if (CE->getOpcode() == Instruction::BitCast ||
9559           CE->getOpcode() == Instruction::GetElementPtr)
9560         Ptr = CE->getOperand(0);
9561       else
9562         return Ptr;
9563     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9564       Ptr = BCI->getOperand(0);
9565     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9566       Ptr = GEP->getOperand(0);
9567     } else {
9568       return Ptr;
9569     }
9570   }
9571 }
9572
9573 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9574   Value *Op = LI.getOperand(0);
9575
9576   // Attempt to improve the alignment.
9577   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9578   if (KnownAlign > LI.getAlignment())
9579     LI.setAlignment(KnownAlign);
9580
9581   // load (cast X) --> cast (load X) iff safe
9582   if (isa<CastInst>(Op))
9583     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9584       return Res;
9585
9586   // None of the following transforms are legal for volatile loads.
9587   if (LI.isVolatile()) return 0;
9588   
9589   if (&LI.getParent()->front() != &LI) {
9590     BasicBlock::iterator BBI = &LI; --BBI;
9591     // If the instruction immediately before this is a store to the same
9592     // address, do a simple form of store->load forwarding.
9593     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9594       if (SI->getOperand(1) == LI.getOperand(0))
9595         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9596     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9597       if (LIB->getOperand(0) == LI.getOperand(0))
9598         return ReplaceInstUsesWith(LI, LIB);
9599   }
9600
9601   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9602     const Value *GEPI0 = GEPI->getOperand(0);
9603     // TODO: Consider a target hook for valid address spaces for this xform.
9604     if (isa<ConstantPointerNull>(GEPI0) &&
9605         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
9606       // Insert a new store to null instruction before the load to indicate
9607       // that this code is not reachable.  We do this instead of inserting
9608       // an unreachable instruction directly because we cannot modify the
9609       // CFG.
9610       new StoreInst(UndefValue::get(LI.getType()),
9611                     Constant::getNullValue(Op->getType()), &LI);
9612       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9613     }
9614   } 
9615
9616   if (Constant *C = dyn_cast<Constant>(Op)) {
9617     // load null/undef -> undef
9618     // TODO: Consider a target hook for valid address spaces for this xform.
9619     if (isa<UndefValue>(C) || (C->isNullValue() && 
9620         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
9621       // Insert a new store to null instruction before the load to indicate that
9622       // this code is not reachable.  We do this instead of inserting an
9623       // unreachable instruction directly because we cannot modify the CFG.
9624       new StoreInst(UndefValue::get(LI.getType()),
9625                     Constant::getNullValue(Op->getType()), &LI);
9626       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9627     }
9628
9629     // Instcombine load (constant global) into the value loaded.
9630     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9631       if (GV->isConstant() && !GV->isDeclaration())
9632         return ReplaceInstUsesWith(LI, GV->getInitializer());
9633
9634     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9635     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9636       if (CE->getOpcode() == Instruction::GetElementPtr) {
9637         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9638           if (GV->isConstant() && !GV->isDeclaration())
9639             if (Constant *V = 
9640                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9641               return ReplaceInstUsesWith(LI, V);
9642         if (CE->getOperand(0)->isNullValue()) {
9643           // Insert a new store to null instruction before the load to indicate
9644           // that this code is not reachable.  We do this instead of inserting
9645           // an unreachable instruction directly because we cannot modify the
9646           // CFG.
9647           new StoreInst(UndefValue::get(LI.getType()),
9648                         Constant::getNullValue(Op->getType()), &LI);
9649           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9650         }
9651
9652       } else if (CE->isCast()) {
9653         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9654           return Res;
9655       }
9656   }
9657     
9658   // If this load comes from anywhere in a constant global, and if the global
9659   // is all undef or zero, we know what it loads.
9660   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9661     if (GV->isConstant() && GV->hasInitializer()) {
9662       if (GV->getInitializer()->isNullValue())
9663         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9664       else if (isa<UndefValue>(GV->getInitializer()))
9665         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9666     }
9667   }
9668
9669   if (Op->hasOneUse()) {
9670     // Change select and PHI nodes to select values instead of addresses: this
9671     // helps alias analysis out a lot, allows many others simplifications, and
9672     // exposes redundancy in the code.
9673     //
9674     // Note that we cannot do the transformation unless we know that the
9675     // introduced loads cannot trap!  Something like this is valid as long as
9676     // the condition is always false: load (select bool %C, int* null, int* %G),
9677     // but it would not be valid if we transformed it to load from null
9678     // unconditionally.
9679     //
9680     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9681       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9682       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9683           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9684         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9685                                      SI->getOperand(1)->getName()+".val"), LI);
9686         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9687                                      SI->getOperand(2)->getName()+".val"), LI);
9688         return new SelectInst(SI->getCondition(), V1, V2);
9689       }
9690
9691       // load (select (cond, null, P)) -> load P
9692       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9693         if (C->isNullValue()) {
9694           LI.setOperand(0, SI->getOperand(2));
9695           return &LI;
9696         }
9697
9698       // load (select (cond, P, null)) -> load P
9699       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9700         if (C->isNullValue()) {
9701           LI.setOperand(0, SI->getOperand(1));
9702           return &LI;
9703         }
9704     }
9705   }
9706   return 0;
9707 }
9708
9709 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9710 /// when possible.
9711 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9712   User *CI = cast<User>(SI.getOperand(1));
9713   Value *CastOp = CI->getOperand(0);
9714
9715   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9716   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9717     const Type *SrcPTy = SrcTy->getElementType();
9718
9719     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9720       // If the source is an array, the code below will not succeed.  Check to
9721       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9722       // constants.
9723       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9724         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9725           if (ASrcTy->getNumElements() != 0) {
9726             Value* Idxs[2];
9727             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9728             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9729             SrcTy = cast<PointerType>(CastOp->getType());
9730             SrcPTy = SrcTy->getElementType();
9731           }
9732
9733       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9734           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9735                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9736
9737         // Okay, we are casting from one integer or pointer type to another of
9738         // the same size.  Instead of casting the pointer before 
9739         // the store, cast the value to be stored.
9740         Value *NewCast;
9741         Value *SIOp0 = SI.getOperand(0);
9742         Instruction::CastOps opcode = Instruction::BitCast;
9743         const Type* CastSrcTy = SIOp0->getType();
9744         const Type* CastDstTy = SrcPTy;
9745         if (isa<PointerType>(CastDstTy)) {
9746           if (CastSrcTy->isInteger())
9747             opcode = Instruction::IntToPtr;
9748         } else if (isa<IntegerType>(CastDstTy)) {
9749           if (isa<PointerType>(SIOp0->getType()))
9750             opcode = Instruction::PtrToInt;
9751         }
9752         if (Constant *C = dyn_cast<Constant>(SIOp0))
9753           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9754         else
9755           NewCast = IC.InsertNewInstBefore(
9756             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9757             SI);
9758         return new StoreInst(NewCast, CastOp);
9759       }
9760     }
9761   }
9762   return 0;
9763 }
9764
9765 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9766   Value *Val = SI.getOperand(0);
9767   Value *Ptr = SI.getOperand(1);
9768
9769   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9770     EraseInstFromFunction(SI);
9771     ++NumCombined;
9772     return 0;
9773   }
9774   
9775   // If the RHS is an alloca with a single use, zapify the store, making the
9776   // alloca dead.
9777   if (Ptr->hasOneUse()) {
9778     if (isa<AllocaInst>(Ptr)) {
9779       EraseInstFromFunction(SI);
9780       ++NumCombined;
9781       return 0;
9782     }
9783     
9784     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9785       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9786           GEP->getOperand(0)->hasOneUse()) {
9787         EraseInstFromFunction(SI);
9788         ++NumCombined;
9789         return 0;
9790       }
9791   }
9792
9793   // Attempt to improve the alignment.
9794   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9795   if (KnownAlign > SI.getAlignment())
9796     SI.setAlignment(KnownAlign);
9797
9798   // Do really simple DSE, to catch cases where there are several consequtive
9799   // stores to the same location, separated by a few arithmetic operations. This
9800   // situation often occurs with bitfield accesses.
9801   BasicBlock::iterator BBI = &SI;
9802   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9803        --ScanInsts) {
9804     --BBI;
9805     
9806     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9807       // Prev store isn't volatile, and stores to the same location?
9808       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9809         ++NumDeadStore;
9810         ++BBI;
9811         EraseInstFromFunction(*PrevSI);
9812         continue;
9813       }
9814       break;
9815     }
9816     
9817     // If this is a load, we have to stop.  However, if the loaded value is from
9818     // the pointer we're loading and is producing the pointer we're storing,
9819     // then *this* store is dead (X = load P; store X -> P).
9820     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9821       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
9822         EraseInstFromFunction(SI);
9823         ++NumCombined;
9824         return 0;
9825       }
9826       // Otherwise, this is a load from some other location.  Stores before it
9827       // may not be dead.
9828       break;
9829     }
9830     
9831     // Don't skip over loads or things that can modify memory.
9832     if (BBI->mayWriteToMemory())
9833       break;
9834   }
9835   
9836   
9837   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9838
9839   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9840   if (isa<ConstantPointerNull>(Ptr)) {
9841     if (!isa<UndefValue>(Val)) {
9842       SI.setOperand(0, UndefValue::get(Val->getType()));
9843       if (Instruction *U = dyn_cast<Instruction>(Val))
9844         AddToWorkList(U);  // Dropped a use.
9845       ++NumCombined;
9846     }
9847     return 0;  // Do not modify these!
9848   }
9849
9850   // store undef, Ptr -> noop
9851   if (isa<UndefValue>(Val)) {
9852     EraseInstFromFunction(SI);
9853     ++NumCombined;
9854     return 0;
9855   }
9856
9857   // If the pointer destination is a cast, see if we can fold the cast into the
9858   // source instead.
9859   if (isa<CastInst>(Ptr))
9860     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9861       return Res;
9862   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9863     if (CE->isCast())
9864       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9865         return Res;
9866
9867   
9868   // If this store is the last instruction in the basic block, and if the block
9869   // ends with an unconditional branch, try to move it to the successor block.
9870   BBI = &SI; ++BBI;
9871   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9872     if (BI->isUnconditional())
9873       if (SimplifyStoreAtEndOfBlock(SI))
9874         return 0;  // xform done!
9875   
9876   return 0;
9877 }
9878
9879 /// SimplifyStoreAtEndOfBlock - Turn things like:
9880 ///   if () { *P = v1; } else { *P = v2 }
9881 /// into a phi node with a store in the successor.
9882 ///
9883 /// Simplify things like:
9884 ///   *P = v1; if () { *P = v2; }
9885 /// into a phi node with a store in the successor.
9886 ///
9887 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9888   BasicBlock *StoreBB = SI.getParent();
9889   
9890   // Check to see if the successor block has exactly two incoming edges.  If
9891   // so, see if the other predecessor contains a store to the same location.
9892   // if so, insert a PHI node (if needed) and move the stores down.
9893   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9894   
9895   // Determine whether Dest has exactly two predecessors and, if so, compute
9896   // the other predecessor.
9897   pred_iterator PI = pred_begin(DestBB);
9898   BasicBlock *OtherBB = 0;
9899   if (*PI != StoreBB)
9900     OtherBB = *PI;
9901   ++PI;
9902   if (PI == pred_end(DestBB))
9903     return false;
9904   
9905   if (*PI != StoreBB) {
9906     if (OtherBB)
9907       return false;
9908     OtherBB = *PI;
9909   }
9910   if (++PI != pred_end(DestBB))
9911     return false;
9912   
9913   
9914   // Verify that the other block ends in a branch and is not otherwise empty.
9915   BasicBlock::iterator BBI = OtherBB->getTerminator();
9916   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9917   if (!OtherBr || BBI == OtherBB->begin())
9918     return false;
9919   
9920   // If the other block ends in an unconditional branch, check for the 'if then
9921   // else' case.  there is an instruction before the branch.
9922   StoreInst *OtherStore = 0;
9923   if (OtherBr->isUnconditional()) {
9924     // If this isn't a store, or isn't a store to the same location, bail out.
9925     --BBI;
9926     OtherStore = dyn_cast<StoreInst>(BBI);
9927     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9928       return false;
9929   } else {
9930     // Otherwise, the other block ended with a conditional branch. If one of the
9931     // destinations is StoreBB, then we have the if/then case.
9932     if (OtherBr->getSuccessor(0) != StoreBB && 
9933         OtherBr->getSuccessor(1) != StoreBB)
9934       return false;
9935     
9936     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9937     // if/then triangle.  See if there is a store to the same ptr as SI that
9938     // lives in OtherBB.
9939     for (;; --BBI) {
9940       // Check to see if we find the matching store.
9941       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9942         if (OtherStore->getOperand(1) != SI.getOperand(1))
9943           return false;
9944         break;
9945       }
9946       // If we find something that may be using the stored value, or if we run
9947       // out of instructions, we can't do the xform.
9948       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9949           BBI == OtherBB->begin())
9950         return false;
9951     }
9952     
9953     // In order to eliminate the store in OtherBr, we have to
9954     // make sure nothing reads the stored value in StoreBB.
9955     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9956       // FIXME: This should really be AA driven.
9957       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9958         return false;
9959     }
9960   }
9961   
9962   // Insert a PHI node now if we need it.
9963   Value *MergedVal = OtherStore->getOperand(0);
9964   if (MergedVal != SI.getOperand(0)) {
9965     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9966     PN->reserveOperandSpace(2);
9967     PN->addIncoming(SI.getOperand(0), SI.getParent());
9968     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9969     MergedVal = InsertNewInstBefore(PN, DestBB->front());
9970   }
9971   
9972   // Advance to a place where it is safe to insert the new store and
9973   // insert it.
9974   BBI = DestBB->begin();
9975   while (isa<PHINode>(BBI)) ++BBI;
9976   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9977                                     OtherStore->isVolatile()), *BBI);
9978   
9979   // Nuke the old stores.
9980   EraseInstFromFunction(SI);
9981   EraseInstFromFunction(*OtherStore);
9982   ++NumCombined;
9983   return true;
9984 }
9985
9986
9987 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9988   // Change br (not X), label True, label False to: br X, label False, True
9989   Value *X = 0;
9990   BasicBlock *TrueDest;
9991   BasicBlock *FalseDest;
9992   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9993       !isa<Constant>(X)) {
9994     // Swap Destinations and condition...
9995     BI.setCondition(X);
9996     BI.setSuccessor(0, FalseDest);
9997     BI.setSuccessor(1, TrueDest);
9998     return &BI;
9999   }
10000
10001   // Cannonicalize fcmp_one -> fcmp_oeq
10002   FCmpInst::Predicate FPred; Value *Y;
10003   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10004                              TrueDest, FalseDest)))
10005     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10006          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10007       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10008       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10009       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10010       NewSCC->takeName(I);
10011       // Swap Destinations and condition...
10012       BI.setCondition(NewSCC);
10013       BI.setSuccessor(0, FalseDest);
10014       BI.setSuccessor(1, TrueDest);
10015       RemoveFromWorkList(I);
10016       I->eraseFromParent();
10017       AddToWorkList(NewSCC);
10018       return &BI;
10019     }
10020
10021   // Cannonicalize icmp_ne -> icmp_eq
10022   ICmpInst::Predicate IPred;
10023   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10024                       TrueDest, FalseDest)))
10025     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10026          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10027          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10028       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10029       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10030       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10031       NewSCC->takeName(I);
10032       // Swap Destinations and condition...
10033       BI.setCondition(NewSCC);
10034       BI.setSuccessor(0, FalseDest);
10035       BI.setSuccessor(1, TrueDest);
10036       RemoveFromWorkList(I);
10037       I->eraseFromParent();;
10038       AddToWorkList(NewSCC);
10039       return &BI;
10040     }
10041
10042   return 0;
10043 }
10044
10045 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10046   Value *Cond = SI.getCondition();
10047   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10048     if (I->getOpcode() == Instruction::Add)
10049       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10050         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10051         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10052           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10053                                                 AddRHS));
10054         SI.setOperand(0, I->getOperand(0));
10055         AddToWorkList(I);
10056         return &SI;
10057       }
10058   }
10059   return 0;
10060 }
10061
10062 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10063 /// is to leave as a vector operation.
10064 static bool CheapToScalarize(Value *V, bool isConstant) {
10065   if (isa<ConstantAggregateZero>(V)) 
10066     return true;
10067   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10068     if (isConstant) return true;
10069     // If all elts are the same, we can extract.
10070     Constant *Op0 = C->getOperand(0);
10071     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10072       if (C->getOperand(i) != Op0)
10073         return false;
10074     return true;
10075   }
10076   Instruction *I = dyn_cast<Instruction>(V);
10077   if (!I) return false;
10078   
10079   // Insert element gets simplified to the inserted element or is deleted if
10080   // this is constant idx extract element and its a constant idx insertelt.
10081   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10082       isa<ConstantInt>(I->getOperand(2)))
10083     return true;
10084   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10085     return true;
10086   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10087     if (BO->hasOneUse() &&
10088         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10089          CheapToScalarize(BO->getOperand(1), isConstant)))
10090       return true;
10091   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10092     if (CI->hasOneUse() &&
10093         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10094          CheapToScalarize(CI->getOperand(1), isConstant)))
10095       return true;
10096   
10097   return false;
10098 }
10099
10100 /// Read and decode a shufflevector mask.
10101 ///
10102 /// It turns undef elements into values that are larger than the number of
10103 /// elements in the input.
10104 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10105   unsigned NElts = SVI->getType()->getNumElements();
10106   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10107     return std::vector<unsigned>(NElts, 0);
10108   if (isa<UndefValue>(SVI->getOperand(2)))
10109     return std::vector<unsigned>(NElts, 2*NElts);
10110
10111   std::vector<unsigned> Result;
10112   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10113   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10114     if (isa<UndefValue>(CP->getOperand(i)))
10115       Result.push_back(NElts*2);  // undef -> 8
10116     else
10117       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10118   return Result;
10119 }
10120
10121 /// FindScalarElement - Given a vector and an element number, see if the scalar
10122 /// value is already around as a register, for example if it were inserted then
10123 /// extracted from the vector.
10124 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10125   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10126   const VectorType *PTy = cast<VectorType>(V->getType());
10127   unsigned Width = PTy->getNumElements();
10128   if (EltNo >= Width)  // Out of range access.
10129     return UndefValue::get(PTy->getElementType());
10130   
10131   if (isa<UndefValue>(V))
10132     return UndefValue::get(PTy->getElementType());
10133   else if (isa<ConstantAggregateZero>(V))
10134     return Constant::getNullValue(PTy->getElementType());
10135   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10136     return CP->getOperand(EltNo);
10137   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10138     // If this is an insert to a variable element, we don't know what it is.
10139     if (!isa<ConstantInt>(III->getOperand(2))) 
10140       return 0;
10141     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10142     
10143     // If this is an insert to the element we are looking for, return the
10144     // inserted value.
10145     if (EltNo == IIElt) 
10146       return III->getOperand(1);
10147     
10148     // Otherwise, the insertelement doesn't modify the value, recurse on its
10149     // vector input.
10150     return FindScalarElement(III->getOperand(0), EltNo);
10151   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10152     unsigned InEl = getShuffleMask(SVI)[EltNo];
10153     if (InEl < Width)
10154       return FindScalarElement(SVI->getOperand(0), InEl);
10155     else if (InEl < Width*2)
10156       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10157     else
10158       return UndefValue::get(PTy->getElementType());
10159   }
10160   
10161   // Otherwise, we don't know.
10162   return 0;
10163 }
10164
10165 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10166
10167   // If vector val is undef, replace extract with scalar undef.
10168   if (isa<UndefValue>(EI.getOperand(0)))
10169     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10170
10171   // If vector val is constant 0, replace extract with scalar 0.
10172   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10173     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10174   
10175   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10176     // If vector val is constant with uniform operands, replace EI
10177     // with that operand
10178     Constant *op0 = C->getOperand(0);
10179     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10180       if (C->getOperand(i) != op0) {
10181         op0 = 0; 
10182         break;
10183       }
10184     if (op0)
10185       return ReplaceInstUsesWith(EI, op0);
10186   }
10187   
10188   // If extracting a specified index from the vector, see if we can recursively
10189   // find a previously computed scalar that was inserted into the vector.
10190   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10191     unsigned IndexVal = IdxC->getZExtValue();
10192     unsigned VectorWidth = 
10193       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10194       
10195     // If this is extracting an invalid index, turn this into undef, to avoid
10196     // crashing the code below.
10197     if (IndexVal >= VectorWidth)
10198       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10199     
10200     // This instruction only demands the single element from the input vector.
10201     // If the input vector has a single use, simplify it based on this use
10202     // property.
10203     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10204       uint64_t UndefElts;
10205       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10206                                                 1 << IndexVal,
10207                                                 UndefElts)) {
10208         EI.setOperand(0, V);
10209         return &EI;
10210       }
10211     }
10212     
10213     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10214       return ReplaceInstUsesWith(EI, Elt);
10215     
10216     // If the this extractelement is directly using a bitcast from a vector of
10217     // the same number of elements, see if we can find the source element from
10218     // it.  In this case, we will end up needing to bitcast the scalars.
10219     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10220       if (const VectorType *VT = 
10221               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10222         if (VT->getNumElements() == VectorWidth)
10223           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10224             return new BitCastInst(Elt, EI.getType());
10225     }
10226   }
10227   
10228   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10229     if (I->hasOneUse()) {
10230       // Push extractelement into predecessor operation if legal and
10231       // profitable to do so
10232       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10233         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10234         if (CheapToScalarize(BO, isConstantElt)) {
10235           ExtractElementInst *newEI0 = 
10236             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10237                                    EI.getName()+".lhs");
10238           ExtractElementInst *newEI1 =
10239             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10240                                    EI.getName()+".rhs");
10241           InsertNewInstBefore(newEI0, EI);
10242           InsertNewInstBefore(newEI1, EI);
10243           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10244         }
10245       } else if (isa<LoadInst>(I)) {
10246         unsigned AS = 
10247           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10248         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10249                                          PointerType::get(EI.getType(), AS),EI);
10250         GetElementPtrInst *GEP = 
10251           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10252         InsertNewInstBefore(GEP, EI);
10253         return new LoadInst(GEP);
10254       }
10255     }
10256     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10257       // Extracting the inserted element?
10258       if (IE->getOperand(2) == EI.getOperand(1))
10259         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10260       // If the inserted and extracted elements are constants, they must not
10261       // be the same value, extract from the pre-inserted value instead.
10262       if (isa<Constant>(IE->getOperand(2)) &&
10263           isa<Constant>(EI.getOperand(1))) {
10264         AddUsesToWorkList(EI);
10265         EI.setOperand(0, IE->getOperand(0));
10266         return &EI;
10267       }
10268     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10269       // If this is extracting an element from a shufflevector, figure out where
10270       // it came from and extract from the appropriate input element instead.
10271       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10272         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10273         Value *Src;
10274         if (SrcIdx < SVI->getType()->getNumElements())
10275           Src = SVI->getOperand(0);
10276         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10277           SrcIdx -= SVI->getType()->getNumElements();
10278           Src = SVI->getOperand(1);
10279         } else {
10280           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10281         }
10282         return new ExtractElementInst(Src, SrcIdx);
10283       }
10284     }
10285   }
10286   return 0;
10287 }
10288
10289 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10290 /// elements from either LHS or RHS, return the shuffle mask and true. 
10291 /// Otherwise, return false.
10292 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10293                                          std::vector<Constant*> &Mask) {
10294   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10295          "Invalid CollectSingleShuffleElements");
10296   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10297
10298   if (isa<UndefValue>(V)) {
10299     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10300     return true;
10301   } else if (V == LHS) {
10302     for (unsigned i = 0; i != NumElts; ++i)
10303       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10304     return true;
10305   } else if (V == RHS) {
10306     for (unsigned i = 0; i != NumElts; ++i)
10307       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10308     return true;
10309   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10310     // If this is an insert of an extract from some other vector, include it.
10311     Value *VecOp    = IEI->getOperand(0);
10312     Value *ScalarOp = IEI->getOperand(1);
10313     Value *IdxOp    = IEI->getOperand(2);
10314     
10315     if (!isa<ConstantInt>(IdxOp))
10316       return false;
10317     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10318     
10319     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10320       // Okay, we can handle this if the vector we are insertinting into is
10321       // transitively ok.
10322       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10323         // If so, update the mask to reflect the inserted undef.
10324         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10325         return true;
10326       }      
10327     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10328       if (isa<ConstantInt>(EI->getOperand(1)) &&
10329           EI->getOperand(0)->getType() == V->getType()) {
10330         unsigned ExtractedIdx =
10331           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10332         
10333         // This must be extracting from either LHS or RHS.
10334         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10335           // Okay, we can handle this if the vector we are insertinting into is
10336           // transitively ok.
10337           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10338             // If so, update the mask to reflect the inserted value.
10339             if (EI->getOperand(0) == LHS) {
10340               Mask[InsertedIdx & (NumElts-1)] = 
10341                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10342             } else {
10343               assert(EI->getOperand(0) == RHS);
10344               Mask[InsertedIdx & (NumElts-1)] = 
10345                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10346               
10347             }
10348             return true;
10349           }
10350         }
10351       }
10352     }
10353   }
10354   // TODO: Handle shufflevector here!
10355   
10356   return false;
10357 }
10358
10359 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10360 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10361 /// that computes V and the LHS value of the shuffle.
10362 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10363                                      Value *&RHS) {
10364   assert(isa<VectorType>(V->getType()) && 
10365          (RHS == 0 || V->getType() == RHS->getType()) &&
10366          "Invalid shuffle!");
10367   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10368
10369   if (isa<UndefValue>(V)) {
10370     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10371     return V;
10372   } else if (isa<ConstantAggregateZero>(V)) {
10373     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10374     return V;
10375   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10376     // If this is an insert of an extract from some other vector, include it.
10377     Value *VecOp    = IEI->getOperand(0);
10378     Value *ScalarOp = IEI->getOperand(1);
10379     Value *IdxOp    = IEI->getOperand(2);
10380     
10381     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10382       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10383           EI->getOperand(0)->getType() == V->getType()) {
10384         unsigned ExtractedIdx =
10385           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10386         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10387         
10388         // Either the extracted from or inserted into vector must be RHSVec,
10389         // otherwise we'd end up with a shuffle of three inputs.
10390         if (EI->getOperand(0) == RHS || RHS == 0) {
10391           RHS = EI->getOperand(0);
10392           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10393           Mask[InsertedIdx & (NumElts-1)] = 
10394             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10395           return V;
10396         }
10397         
10398         if (VecOp == RHS) {
10399           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10400           // Everything but the extracted element is replaced with the RHS.
10401           for (unsigned i = 0; i != NumElts; ++i) {
10402             if (i != InsertedIdx)
10403               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10404           }
10405           return V;
10406         }
10407         
10408         // If this insertelement is a chain that comes from exactly these two
10409         // vectors, return the vector and the effective shuffle.
10410         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10411           return EI->getOperand(0);
10412         
10413       }
10414     }
10415   }
10416   // TODO: Handle shufflevector here!
10417   
10418   // Otherwise, can't do anything fancy.  Return an identity vector.
10419   for (unsigned i = 0; i != NumElts; ++i)
10420     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10421   return V;
10422 }
10423
10424 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10425   Value *VecOp    = IE.getOperand(0);
10426   Value *ScalarOp = IE.getOperand(1);
10427   Value *IdxOp    = IE.getOperand(2);
10428   
10429   // Inserting an undef or into an undefined place, remove this.
10430   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10431     ReplaceInstUsesWith(IE, VecOp);
10432   
10433   // If the inserted element was extracted from some other vector, and if the 
10434   // indexes are constant, try to turn this into a shufflevector operation.
10435   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10436     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10437         EI->getOperand(0)->getType() == IE.getType()) {
10438       unsigned NumVectorElts = IE.getType()->getNumElements();
10439       unsigned ExtractedIdx =
10440         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10441       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10442       
10443       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10444         return ReplaceInstUsesWith(IE, VecOp);
10445       
10446       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10447         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10448       
10449       // If we are extracting a value from a vector, then inserting it right
10450       // back into the same place, just use the input vector.
10451       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10452         return ReplaceInstUsesWith(IE, VecOp);      
10453       
10454       // We could theoretically do this for ANY input.  However, doing so could
10455       // turn chains of insertelement instructions into a chain of shufflevector
10456       // instructions, and right now we do not merge shufflevectors.  As such,
10457       // only do this in a situation where it is clear that there is benefit.
10458       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10459         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10460         // the values of VecOp, except then one read from EIOp0.
10461         // Build a new shuffle mask.
10462         std::vector<Constant*> Mask;
10463         if (isa<UndefValue>(VecOp))
10464           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10465         else {
10466           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10467           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10468                                                        NumVectorElts));
10469         } 
10470         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10471         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10472                                      ConstantVector::get(Mask));
10473       }
10474       
10475       // If this insertelement isn't used by some other insertelement, turn it
10476       // (and any insertelements it points to), into one big shuffle.
10477       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10478         std::vector<Constant*> Mask;
10479         Value *RHS = 0;
10480         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10481         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10482         // We now have a shuffle of LHS, RHS, Mask.
10483         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10484       }
10485     }
10486   }
10487
10488   return 0;
10489 }
10490
10491
10492 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10493   Value *LHS = SVI.getOperand(0);
10494   Value *RHS = SVI.getOperand(1);
10495   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10496
10497   bool MadeChange = false;
10498   
10499   // Undefined shuffle mask -> undefined value.
10500   if (isa<UndefValue>(SVI.getOperand(2)))
10501     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10502   
10503   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10504   // the undef, change them to undefs.
10505   if (isa<UndefValue>(SVI.getOperand(1))) {
10506     // Scan to see if there are any references to the RHS.  If so, replace them
10507     // with undef element refs and set MadeChange to true.
10508     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10509       if (Mask[i] >= e && Mask[i] != 2*e) {
10510         Mask[i] = 2*e;
10511         MadeChange = true;
10512       }
10513     }
10514     
10515     if (MadeChange) {
10516       // Remap any references to RHS to use LHS.
10517       std::vector<Constant*> Elts;
10518       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10519         if (Mask[i] == 2*e)
10520           Elts.push_back(UndefValue::get(Type::Int32Ty));
10521         else
10522           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10523       }
10524       SVI.setOperand(2, ConstantVector::get(Elts));
10525     }
10526   }
10527   
10528   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10529   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10530   if (LHS == RHS || isa<UndefValue>(LHS)) {
10531     if (isa<UndefValue>(LHS) && LHS == RHS) {
10532       // shuffle(undef,undef,mask) -> undef.
10533       return ReplaceInstUsesWith(SVI, LHS);
10534     }
10535     
10536     // Remap any references to RHS to use LHS.
10537     std::vector<Constant*> Elts;
10538     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10539       if (Mask[i] >= 2*e)
10540         Elts.push_back(UndefValue::get(Type::Int32Ty));
10541       else {
10542         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10543             (Mask[i] <  e && isa<UndefValue>(LHS)))
10544           Mask[i] = 2*e;     // Turn into undef.
10545         else
10546           Mask[i] &= (e-1);  // Force to LHS.
10547         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10548       }
10549     }
10550     SVI.setOperand(0, SVI.getOperand(1));
10551     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10552     SVI.setOperand(2, ConstantVector::get(Elts));
10553     LHS = SVI.getOperand(0);
10554     RHS = SVI.getOperand(1);
10555     MadeChange = true;
10556   }
10557   
10558   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10559   bool isLHSID = true, isRHSID = true;
10560     
10561   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10562     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10563     // Is this an identity shuffle of the LHS value?
10564     isLHSID &= (Mask[i] == i);
10565       
10566     // Is this an identity shuffle of the RHS value?
10567     isRHSID &= (Mask[i]-e == i);
10568   }
10569
10570   // Eliminate identity shuffles.
10571   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10572   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10573   
10574   // If the LHS is a shufflevector itself, see if we can combine it with this
10575   // one without producing an unusual shuffle.  Here we are really conservative:
10576   // we are absolutely afraid of producing a shuffle mask not in the input
10577   // program, because the code gen may not be smart enough to turn a merged
10578   // shuffle into two specific shuffles: it may produce worse code.  As such,
10579   // we only merge two shuffles if the result is one of the two input shuffle
10580   // masks.  In this case, merging the shuffles just removes one instruction,
10581   // which we know is safe.  This is good for things like turning:
10582   // (splat(splat)) -> splat.
10583   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10584     if (isa<UndefValue>(RHS)) {
10585       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10586
10587       std::vector<unsigned> NewMask;
10588       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10589         if (Mask[i] >= 2*e)
10590           NewMask.push_back(2*e);
10591         else
10592           NewMask.push_back(LHSMask[Mask[i]]);
10593       
10594       // If the result mask is equal to the src shuffle or this shuffle mask, do
10595       // the replacement.
10596       if (NewMask == LHSMask || NewMask == Mask) {
10597         std::vector<Constant*> Elts;
10598         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10599           if (NewMask[i] >= e*2) {
10600             Elts.push_back(UndefValue::get(Type::Int32Ty));
10601           } else {
10602             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10603           }
10604         }
10605         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10606                                      LHSSVI->getOperand(1),
10607                                      ConstantVector::get(Elts));
10608       }
10609     }
10610   }
10611
10612   return MadeChange ? &SVI : 0;
10613 }
10614
10615
10616
10617
10618 /// TryToSinkInstruction - Try to move the specified instruction from its
10619 /// current block into the beginning of DestBlock, which can only happen if it's
10620 /// safe to move the instruction past all of the instructions between it and the
10621 /// end of its block.
10622 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10623   assert(I->hasOneUse() && "Invariants didn't hold!");
10624
10625   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10626   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10627
10628   // Do not sink alloca instructions out of the entry block.
10629   if (isa<AllocaInst>(I) && I->getParent() ==
10630         &DestBlock->getParent()->getEntryBlock())
10631     return false;
10632
10633   // We can only sink load instructions if there is nothing between the load and
10634   // the end of block that could change the value.
10635   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10636     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10637          Scan != E; ++Scan)
10638       if (Scan->mayWriteToMemory())
10639         return false;
10640   }
10641
10642   BasicBlock::iterator InsertPos = DestBlock->begin();
10643   while (isa<PHINode>(InsertPos)) ++InsertPos;
10644
10645   I->moveBefore(InsertPos);
10646   ++NumSunkInst;
10647   return true;
10648 }
10649
10650
10651 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10652 /// all reachable code to the worklist.
10653 ///
10654 /// This has a couple of tricks to make the code faster and more powerful.  In
10655 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10656 /// them to the worklist (this significantly speeds up instcombine on code where
10657 /// many instructions are dead or constant).  Additionally, if we find a branch
10658 /// whose condition is a known constant, we only visit the reachable successors.
10659 ///
10660 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10661                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10662                                        InstCombiner &IC,
10663                                        const TargetData *TD) {
10664   std::vector<BasicBlock*> Worklist;
10665   Worklist.push_back(BB);
10666
10667   while (!Worklist.empty()) {
10668     BB = Worklist.back();
10669     Worklist.pop_back();
10670     
10671     // We have now visited this block!  If we've already been here, ignore it.
10672     if (!Visited.insert(BB)) continue;
10673     
10674     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10675       Instruction *Inst = BBI++;
10676       
10677       // DCE instruction if trivially dead.
10678       if (isInstructionTriviallyDead(Inst)) {
10679         ++NumDeadInst;
10680         DOUT << "IC: DCE: " << *Inst;
10681         Inst->eraseFromParent();
10682         continue;
10683       }
10684       
10685       // ConstantProp instruction if trivially constant.
10686       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10687         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10688         Inst->replaceAllUsesWith(C);
10689         ++NumConstProp;
10690         Inst->eraseFromParent();
10691         continue;
10692       }
10693      
10694       IC.AddToWorkList(Inst);
10695     }
10696
10697     // Recursively visit successors.  If this is a branch or switch on a
10698     // constant, only visit the reachable successor.
10699     TerminatorInst *TI = BB->getTerminator();
10700     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10701       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10702         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10703         Worklist.push_back(BI->getSuccessor(!CondVal));
10704         continue;
10705       }
10706     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10707       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10708         // See if this is an explicit destination.
10709         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10710           if (SI->getCaseValue(i) == Cond) {
10711             Worklist.push_back(SI->getSuccessor(i));
10712             continue;
10713           }
10714         
10715         // Otherwise it is the default destination.
10716         Worklist.push_back(SI->getSuccessor(0));
10717         continue;
10718       }
10719     }
10720     
10721     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10722       Worklist.push_back(TI->getSuccessor(i));
10723   }
10724 }
10725
10726 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10727   bool Changed = false;
10728   TD = &getAnalysis<TargetData>();
10729   
10730   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10731              << F.getNameStr() << "\n");
10732
10733   {
10734     // Do a depth-first traversal of the function, populate the worklist with
10735     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10736     // track of which blocks we visit.
10737     SmallPtrSet<BasicBlock*, 64> Visited;
10738     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10739
10740     // Do a quick scan over the function.  If we find any blocks that are
10741     // unreachable, remove any instructions inside of them.  This prevents
10742     // the instcombine code from having to deal with some bad special cases.
10743     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10744       if (!Visited.count(BB)) {
10745         Instruction *Term = BB->getTerminator();
10746         while (Term != BB->begin()) {   // Remove instrs bottom-up
10747           BasicBlock::iterator I = Term; --I;
10748
10749           DOUT << "IC: DCE: " << *I;
10750           ++NumDeadInst;
10751
10752           if (!I->use_empty())
10753             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10754           I->eraseFromParent();
10755         }
10756       }
10757   }
10758
10759   while (!Worklist.empty()) {
10760     Instruction *I = RemoveOneFromWorkList();
10761     if (I == 0) continue;  // skip null values.
10762
10763     // Check to see if we can DCE the instruction.
10764     if (isInstructionTriviallyDead(I)) {
10765       // Add operands to the worklist.
10766       if (I->getNumOperands() < 4)
10767         AddUsesToWorkList(*I);
10768       ++NumDeadInst;
10769
10770       DOUT << "IC: DCE: " << *I;
10771
10772       I->eraseFromParent();
10773       RemoveFromWorkList(I);
10774       continue;
10775     }
10776
10777     // Instruction isn't dead, see if we can constant propagate it.
10778     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10779       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10780
10781       // Add operands to the worklist.
10782       AddUsesToWorkList(*I);
10783       ReplaceInstUsesWith(*I, C);
10784
10785       ++NumConstProp;
10786       I->eraseFromParent();
10787       RemoveFromWorkList(I);
10788       continue;
10789     }
10790
10791     // See if we can trivially sink this instruction to a successor basic block.
10792     if (I->hasOneUse()) {
10793       BasicBlock *BB = I->getParent();
10794       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10795       if (UserParent != BB) {
10796         bool UserIsSuccessor = false;
10797         // See if the user is one of our successors.
10798         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10799           if (*SI == UserParent) {
10800             UserIsSuccessor = true;
10801             break;
10802           }
10803
10804         // If the user is one of our immediate successors, and if that successor
10805         // only has us as a predecessors (we'd have to split the critical edge
10806         // otherwise), we can keep going.
10807         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10808             next(pred_begin(UserParent)) == pred_end(UserParent))
10809           // Okay, the CFG is simple enough, try to sink this instruction.
10810           Changed |= TryToSinkInstruction(I, UserParent);
10811       }
10812     }
10813
10814     // Now that we have an instruction, try combining it to simplify it...
10815 #ifndef NDEBUG
10816     std::string OrigI;
10817 #endif
10818     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10819     if (Instruction *Result = visit(*I)) {
10820       ++NumCombined;
10821       // Should we replace the old instruction with a new one?
10822       if (Result != I) {
10823         DOUT << "IC: Old = " << *I
10824              << "    New = " << *Result;
10825
10826         // Everything uses the new instruction now.
10827         I->replaceAllUsesWith(Result);
10828
10829         // Push the new instruction and any users onto the worklist.
10830         AddToWorkList(Result);
10831         AddUsersToWorkList(*Result);
10832
10833         // Move the name to the new instruction first.
10834         Result->takeName(I);
10835
10836         // Insert the new instruction into the basic block...
10837         BasicBlock *InstParent = I->getParent();
10838         BasicBlock::iterator InsertPos = I;
10839
10840         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10841           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10842             ++InsertPos;
10843
10844         InstParent->getInstList().insert(InsertPos, Result);
10845
10846         // Make sure that we reprocess all operands now that we reduced their
10847         // use counts.
10848         AddUsesToWorkList(*I);
10849
10850         // Instructions can end up on the worklist more than once.  Make sure
10851         // we do not process an instruction that has been deleted.
10852         RemoveFromWorkList(I);
10853
10854         // Erase the old instruction.
10855         InstParent->getInstList().erase(I);
10856       } else {
10857 #ifndef NDEBUG
10858         DOUT << "IC: Mod = " << OrigI
10859              << "    New = " << *I;
10860 #endif
10861
10862         // If the instruction was modified, it's possible that it is now dead.
10863         // if so, remove it.
10864         if (isInstructionTriviallyDead(I)) {
10865           // Make sure we process all operands now that we are reducing their
10866           // use counts.
10867           AddUsesToWorkList(*I);
10868
10869           // Instructions may end up in the worklist more than once.  Erase all
10870           // occurrences of this instruction.
10871           RemoveFromWorkList(I);
10872           I->eraseFromParent();
10873         } else {
10874           AddToWorkList(I);
10875           AddUsersToWorkList(*I);
10876         }
10877       }
10878       Changed = true;
10879     }
10880   }
10881
10882   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10883     
10884   // Do an explicit clear, this shrinks the map if needed.
10885   WorklistMap.clear();
10886   return Changed;
10887 }
10888
10889
10890 bool InstCombiner::runOnFunction(Function &F) {
10891   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10892   
10893   bool EverMadeChange = false;
10894
10895   // Iterate while there is work to do.
10896   unsigned Iteration = 0;
10897   while (DoOneIteration(F, Iteration++)) 
10898     EverMadeChange = true;
10899   return EverMadeChange;
10900 }
10901
10902 FunctionPass *llvm::createInstructionCombiningPass() {
10903   return new InstCombiner();
10904 }
10905