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