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