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