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