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