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