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