Reenable the transform, turning X/-10 < 1 into X > -10
[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 //    N. This list is incomplete
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Intrinsics.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Constants.h"
42 #include "llvm/DerivedTypes.h"
43 #include "llvm/GlobalVariable.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/ADT/Statistic.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 namespace {
59   Statistic<> NumCombined ("instcombine", "Number of insts combined");
60   Statistic<> NumConstProp("instcombine", "Number of constant folds");
61   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
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(BinaryOperator &I);
116     Instruction *visitShiftInst(ShiftInst &I);
117     Instruction *visitCastInst(CastInst &CI);
118     Instruction *visitSelectInst(SelectInst &CI);
119     Instruction *visitCallInst(CallInst &CI);
120     Instruction *visitInvokeInst(InvokeInst &II);
121     Instruction *visitPHINode(PHINode &PN);
122     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
123     Instruction *visitAllocationInst(AllocationInst &AI);
124     Instruction *visitFreeInst(FreeInst &FI);
125     Instruction *visitLoadInst(LoadInst &LI);
126     Instruction *visitBranchInst(BranchInst &BI);
127     Instruction *visitSwitchInst(SwitchInst &SI);
128
129     // visitInstruction - Specify what to return for unhandled instructions...
130     Instruction *visitInstruction(Instruction &I) { return 0; }
131
132   private:
133     Instruction *visitCallSite(CallSite CS);
134     bool transformConstExprCastCall(CallSite CS);
135
136   public:
137     // InsertNewInstBefore - insert an instruction New before instruction Old
138     // in the program.  Add the new instruction to the worklist.
139     //
140     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
141       assert(New && New->getParent() == 0 &&
142              "New instruction already inserted into a basic block!");
143       BasicBlock *BB = Old.getParent();
144       BB->getInstList().insert(&Old, New);  // Insert inst
145       WorkList.push_back(New);              // Add to worklist
146       return New;
147     }
148
149     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150     /// This also adds the cast to the worklist.  Finally, this returns the
151     /// cast.
152     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153       if (V->getType() == Ty) return V;
154       
155       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156       WorkList.push_back(C);
157       return C;
158     }
159
160     // ReplaceInstUsesWith - This method is to be used when an instruction is
161     // found to be dead, replacable with another preexisting expression.  Here
162     // we add all uses of I to the worklist, replace all uses of I with the new
163     // value, then return I, so that the inst combiner will know that I was
164     // modified.
165     //
166     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
167       AddUsersToWorkList(I);         // Add all modified instrs to worklist
168       if (&I != V) {
169         I.replaceAllUsesWith(V);
170         return &I;
171       } else {
172         // If we are replacing the instruction with itself, this must be in a
173         // segment of unreachable code, so just clobber the instruction.
174         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175         return &I;
176       }
177     }
178
179     // EraseInstFromFunction - When dealing with an instruction that has side
180     // effects or produces a void value, we can't rely on DCE to delete the
181     // instruction.  Instead, visit methods should return the value returned by
182     // this function.
183     Instruction *EraseInstFromFunction(Instruction &I) {
184       assert(I.use_empty() && "Cannot erase instruction that is used!");
185       AddUsesToWorkList(I);
186       removeFromWorkList(&I);
187       I.getParent()->getInstList().erase(&I);
188       return 0;  // Don't do anything with FI
189     }
190
191
192   private:
193     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
195     /// casts that are known to not do anything...
196     ///
197     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198                                    Instruction *InsertBefore);
199
200     // SimplifyCommutative - This performs a few simplifications for commutative
201     // operators.
202     bool SimplifyCommutative(BinaryOperator &I);
203
204
205     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
206     // PHI node as operand #0, see if we can fold the instruction into the PHI
207     // (which is only possible if all operands to the PHI are constants).
208     Instruction *FoldOpIntoPhi(Instruction &I);
209
210     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
211                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
212
213     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
214                                  bool Inside, Instruction &IB);
215   };
216
217   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
218 }
219
220 // getComplexity:  Assign a complexity or rank value to LLVM Values...
221 //   0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
222 static unsigned getComplexity(Value *V) {
223   if (isa<Instruction>(V)) {
224     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
225       return 2;
226     return 3;
227   }
228   if (isa<Argument>(V)) return 2;
229   return isa<Constant>(V) ? 0 : 1;
230 }
231
232 // isOnlyUse - Return true if this instruction will be deleted if we stop using
233 // it.
234 static bool isOnlyUse(Value *V) {
235   return V->hasOneUse() || isa<Constant>(V);
236 }
237
238 // getPromotedType - Return the specified type promoted as it would be to pass
239 // though a va_arg area...
240 static const Type *getPromotedType(const Type *Ty) {
241   switch (Ty->getTypeID()) {
242   case Type::SByteTyID:
243   case Type::ShortTyID:  return Type::IntTy;
244   case Type::UByteTyID:
245   case Type::UShortTyID: return Type::UIntTy;
246   case Type::FloatTyID:  return Type::DoubleTy;
247   default:               return Ty;
248   }
249 }
250
251 // SimplifyCommutative - This performs a few simplifications for commutative
252 // operators:
253 //
254 //  1. Order operands such that they are listed from right (least complex) to
255 //     left (most complex).  This puts constants before unary operators before
256 //     binary operators.
257 //
258 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
259 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
260 //
261 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
262   bool Changed = false;
263   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
264     Changed = !I.swapOperands();
265   
266   if (!I.isAssociative()) return Changed;
267   Instruction::BinaryOps Opcode = I.getOpcode();
268   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
269     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
270       if (isa<Constant>(I.getOperand(1))) {
271         Constant *Folded = ConstantExpr::get(I.getOpcode(),
272                                              cast<Constant>(I.getOperand(1)),
273                                              cast<Constant>(Op->getOperand(1)));
274         I.setOperand(0, Op->getOperand(0));
275         I.setOperand(1, Folded);
276         return true;
277       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
278         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
279             isOnlyUse(Op) && isOnlyUse(Op1)) {
280           Constant *C1 = cast<Constant>(Op->getOperand(1));
281           Constant *C2 = cast<Constant>(Op1->getOperand(1));
282
283           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
284           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
285           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
286                                                     Op1->getOperand(0),
287                                                     Op1->getName(), &I);
288           WorkList.push_back(New);
289           I.setOperand(0, New);
290           I.setOperand(1, Folded);
291           return true;
292         }      
293     }
294   return Changed;
295 }
296
297 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
298 // if the LHS is a constant zero (which is the 'negate' form).
299 //
300 static inline Value *dyn_castNegVal(Value *V) {
301   if (BinaryOperator::isNeg(V))
302     return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
303
304   // Constants can be considered to be negated values if they can be folded...
305   if (Constant *C = dyn_cast<Constant>(V))
306     return ConstantExpr::getNeg(C);
307   return 0;
308 }
309
310 static inline Value *dyn_castNotVal(Value *V) {
311   if (BinaryOperator::isNot(V))
312     return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
313
314   // Constants can be considered to be not'ed values...
315   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
316     return ConstantExpr::getNot(C);
317   return 0;
318 }
319
320 // dyn_castFoldableMul - If this value is a multiply that can be folded into
321 // other computations (because it has a constant operand), return the
322 // non-constant operand of the multiply.
323 //
324 static inline Value *dyn_castFoldableMul(Value *V) {
325   if (V->hasOneUse() && V->getType()->isInteger())
326     if (Instruction *I = dyn_cast<Instruction>(V))
327       if (I->getOpcode() == Instruction::Mul)
328         if (isa<Constant>(I->getOperand(1)))
329           return I->getOperand(0);
330   return 0;
331 }
332
333 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
334 // power of 2.
335 static unsigned Log2(uint64_t Val) {
336   assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
337   unsigned Count = 0;
338   while (Val != 1) {
339     if (Val & 1) return 0;    // Multiple bits set?
340     Val >>= 1;
341     ++Count;
342   }
343   return Count;
344 }
345
346 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
347 static ConstantInt *AddOne(ConstantInt *C) {
348   return cast<ConstantInt>(ConstantExpr::getAdd(C,
349                                          ConstantInt::get(C->getType(), 1)));
350 }
351 static ConstantInt *SubOne(ConstantInt *C) {
352   return cast<ConstantInt>(ConstantExpr::getSub(C,
353                                          ConstantInt::get(C->getType(), 1)));
354 }
355
356 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
357 // true when both operands are equal...
358 //
359 static bool isTrueWhenEqual(Instruction &I) {
360   return I.getOpcode() == Instruction::SetEQ ||
361          I.getOpcode() == Instruction::SetGE ||
362          I.getOpcode() == Instruction::SetLE;
363 }
364
365 /// AssociativeOpt - Perform an optimization on an associative operator.  This
366 /// function is designed to check a chain of associative operators for a
367 /// potential to apply a certain optimization.  Since the optimization may be
368 /// applicable if the expression was reassociated, this checks the chain, then
369 /// reassociates the expression as necessary to expose the optimization
370 /// opportunity.  This makes use of a special Functor, which must define
371 /// 'shouldApply' and 'apply' methods.
372 ///
373 template<typename Functor>
374 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
375   unsigned Opcode = Root.getOpcode();
376   Value *LHS = Root.getOperand(0);
377
378   // Quick check, see if the immediate LHS matches...
379   if (F.shouldApply(LHS))
380     return F.apply(Root);
381
382   // Otherwise, if the LHS is not of the same opcode as the root, return.
383   Instruction *LHSI = dyn_cast<Instruction>(LHS);
384   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
385     // Should we apply this transform to the RHS?
386     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
387
388     // If not to the RHS, check to see if we should apply to the LHS...
389     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
390       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
391       ShouldApply = true;
392     }
393
394     // If the functor wants to apply the optimization to the RHS of LHSI,
395     // reassociate the expression from ((? op A) op B) to (? op (A op B))
396     if (ShouldApply) {
397       BasicBlock *BB = Root.getParent();
398       
399       // Now all of the instructions are in the current basic block, go ahead
400       // and perform the reassociation.
401       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
402
403       // First move the selected RHS to the LHS of the root...
404       Root.setOperand(0, LHSI->getOperand(1));
405
406       // Make what used to be the LHS of the root be the user of the root...
407       Value *ExtraOperand = TmpLHSI->getOperand(1);
408       if (&Root == TmpLHSI) {
409         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
410         return 0;
411       }
412       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
413       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
414       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
415       BasicBlock::iterator ARI = &Root; ++ARI;
416       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
417       ARI = Root;
418
419       // Now propagate the ExtraOperand down the chain of instructions until we
420       // get to LHSI.
421       while (TmpLHSI != LHSI) {
422         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
423         // Move the instruction to immediately before the chain we are
424         // constructing to avoid breaking dominance properties.
425         NextLHSI->getParent()->getInstList().remove(NextLHSI);
426         BB->getInstList().insert(ARI, NextLHSI);
427         ARI = NextLHSI;
428
429         Value *NextOp = NextLHSI->getOperand(1);
430         NextLHSI->setOperand(1, ExtraOperand);
431         TmpLHSI = NextLHSI;
432         ExtraOperand = NextOp;
433       }
434       
435       // Now that the instructions are reassociated, have the functor perform
436       // the transformation...
437       return F.apply(Root);
438     }
439     
440     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
441   }
442   return 0;
443 }
444
445
446 // AddRHS - Implements: X + X --> X << 1
447 struct AddRHS {
448   Value *RHS;
449   AddRHS(Value *rhs) : RHS(rhs) {}
450   bool shouldApply(Value *LHS) const { return LHS == RHS; }
451   Instruction *apply(BinaryOperator &Add) const {
452     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
453                          ConstantInt::get(Type::UByteTy, 1));
454   }
455 };
456
457 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
458 //                 iff C1&C2 == 0
459 struct AddMaskingAnd {
460   Constant *C2;
461   AddMaskingAnd(Constant *c) : C2(c) {}
462   bool shouldApply(Value *LHS) const {
463     ConstantInt *C1;
464     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) && 
465            ConstantExpr::getAnd(C1, C2)->isNullValue();
466   }
467   Instruction *apply(BinaryOperator &Add) const {
468     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
469   }
470 };
471
472 static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
473                                              InstCombiner *IC) {
474   // Figure out if the constant is the left or the right argument.
475   bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
476   Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
477
478   if (Constant *SOC = dyn_cast<Constant>(SO)) {
479     if (ConstIsRHS)
480       return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
481     return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
482   }
483
484   Value *Op0 = SO, *Op1 = ConstOperand;
485   if (!ConstIsRHS)
486     std::swap(Op0, Op1);
487   Instruction *New;
488   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
489     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
490   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
491     New = new ShiftInst(SI->getOpcode(), Op0, Op1);
492   else {
493     assert(0 && "Unknown binary instruction type!");
494     abort();
495   }
496   return IC->InsertNewInstBefore(New, BI);
497 }
498
499
500 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
501 /// node as operand #0, see if we can fold the instruction into the PHI (which
502 /// is only possible if all operands to the PHI are constants).
503 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
504   PHINode *PN = cast<PHINode>(I.getOperand(0));
505   if (!PN->hasOneUse()) return 0;
506
507   // Check to see if all of the operands of the PHI are constants.  If not, we
508   // cannot do the transformation.
509   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510     if (!isa<Constant>(PN->getIncomingValue(i)))
511       return 0;
512
513   // Okay, we can do the transformation: create the new PHI node.
514   PHINode *NewPN = new PHINode(I.getType(), I.getName());
515   I.setName("");
516   NewPN->op_reserve(PN->getNumOperands());
517   InsertNewInstBefore(NewPN, *PN);
518
519   // Next, add all of the operands to the PHI.
520   if (I.getNumOperands() == 2) {
521     Constant *C = cast<Constant>(I.getOperand(1));
522     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
523       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
524       NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
525                          PN->getIncomingBlock(i));
526     }
527   } else {
528     assert(isa<CastInst>(I) && "Unary op should be a cast!");
529     const Type *RetTy = I.getType();
530     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
531       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
532       NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
533                          PN->getIncomingBlock(i));
534     }
535   }
536   return ReplaceInstUsesWith(I, NewPN);
537 }
538
539 // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
540 // constant as the other operand, try to fold the binary operator into the
541 // select arguments.
542 static Instruction *FoldBinOpIntoSelect(Instruction &BI, 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     Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
551     Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
552
553     return new SelectInst(SI->getCondition(), SelectTrueVal,
554                           SelectFalseVal);
555   }
556   return 0;
557 }
558
559 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
560   bool Changed = SimplifyCommutative(I);
561   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
562
563   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
564     // X + 0 --> X
565     if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
566         RHSC->isNullValue())
567       return ReplaceInstUsesWith(I, LHS);
568     
569     // X + (signbit) --> X ^ signbit
570     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
571       unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
572       uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
573       if (Val == (1ULL << NumBits-1))
574         return BinaryOperator::createXor(LHS, RHS);
575     }
576
577     if (isa<PHINode>(LHS))
578       if (Instruction *NV = FoldOpIntoPhi(I))
579         return NV;
580   }
581
582   // X + X --> X << 1
583   if (I.getType()->isInteger()) {
584     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
585   }
586
587   // -A + B  -->  B - A
588   if (Value *V = dyn_castNegVal(LHS))
589     return BinaryOperator::createSub(RHS, V);
590
591   // A + -B  -->  A - B
592   if (!isa<Constant>(RHS))
593     if (Value *V = dyn_castNegVal(RHS))
594       return BinaryOperator::createSub(LHS, V);
595
596   // X*C + X --> X * (C+1)
597   if (dyn_castFoldableMul(LHS) == RHS) {
598     Constant *CP1 =
599       ConstantExpr::getAdd(
600                         cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
601                         ConstantInt::get(I.getType(), 1));
602     return BinaryOperator::createMul(RHS, CP1);
603   }
604
605   // X + X*C --> X * (C+1)
606   if (dyn_castFoldableMul(RHS) == LHS) {
607     Constant *CP1 =
608       ConstantExpr::getAdd(
609                         cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
610                         ConstantInt::get(I.getType(), 1));
611     return BinaryOperator::createMul(LHS, CP1);
612   }
613
614   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
615   ConstantInt *C2;
616   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
617     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
618
619   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
620     Value *X;
621     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
622       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
623       return BinaryOperator::createSub(C, X);
624     }
625
626     // (X & FF00) + xx00  -> (X+xx00) & FF00
627     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
628       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
629       if (Anded == CRHS) {
630         // See if all bits from the first bit set in the Add RHS up are included
631         // in the mask.  First, get the rightmost bit.
632         uint64_t AddRHSV = CRHS->getRawValue();
633
634         // Form a mask of all bits from the lowest bit added through the top.
635         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
636         AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
637
638         // See if the and mask includes all of these bits.
639         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
640         
641         if (AddRHSHighBits == AddRHSHighBitsAnd) {
642           // Okay, the xform is safe.  Insert the new add pronto.
643           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
644                                                             LHS->getName()), I);
645           return BinaryOperator::createAnd(NewAdd, C2);
646         }
647       }
648     }
649
650
651     // Try to fold constant add into select arguments.
652     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
653       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
654         return R;
655   }
656
657   return Changed ? &I : 0;
658 }
659
660 // isSignBit - Return true if the value represented by the constant only has the
661 // highest order bit set.
662 static bool isSignBit(ConstantInt *CI) {
663   unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
664   return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
665 }
666
667 static unsigned getTypeSizeInBits(const Type *Ty) {
668   return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
669 }
670
671 /// RemoveNoopCast - Strip off nonconverting casts from the value.
672 ///
673 static Value *RemoveNoopCast(Value *V) {
674   if (CastInst *CI = dyn_cast<CastInst>(V)) {
675     const Type *CTy = CI->getType();
676     const Type *OpTy = CI->getOperand(0)->getType();
677     if (CTy->isInteger() && OpTy->isInteger()) {
678       if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
679         return RemoveNoopCast(CI->getOperand(0));
680     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
681       return RemoveNoopCast(CI->getOperand(0));
682   }
683   return V;
684 }
685
686 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
687   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
688
689   if (Op0 == Op1)         // sub X, X  -> 0
690     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
691
692   // If this is a 'B = x-(-A)', change to B = x+A...
693   if (Value *V = dyn_castNegVal(Op1))
694     return BinaryOperator::createAdd(Op0, V);
695
696   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
697     // Replace (-1 - A) with (~A)...
698     if (C->isAllOnesValue())
699       return BinaryOperator::createNot(Op1);
700
701     // C - ~X == X + (1+C)
702     Value *X;
703     if (match(Op1, m_Not(m_Value(X))))
704       return BinaryOperator::createAdd(X,
705                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
706     // -((uint)X >> 31) -> ((int)X >> 31)
707     // -((int)X >> 31) -> ((uint)X >> 31)
708     if (C->isNullValue()) {
709       Value *NoopCastedRHS = RemoveNoopCast(Op1);
710       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
711         if (SI->getOpcode() == Instruction::Shr)
712           if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
713             const Type *NewTy;
714             if (SI->getType()->isSigned())
715               NewTy = SI->getType()->getUnsignedVersion();
716             else
717               NewTy = SI->getType()->getSignedVersion();
718             // Check to see if we are shifting out everything but the sign bit.
719             if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
720               // Ok, the transformation is safe.  Insert a cast of the incoming
721               // value, then the new shift, then the new cast.
722               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
723                                                  SI->getOperand(0)->getName());
724               Value *InV = InsertNewInstBefore(FirstCast, I);
725               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
726                                                     CU, SI->getName());
727               if (NewShift->getType() == I.getType())
728                 return NewShift;
729               else {
730                 InV = InsertNewInstBefore(NewShift, I);
731                 return new CastInst(NewShift, I.getType());
732               }
733             }
734           }
735     }
736
737     // Try to fold constant sub into select arguments.
738     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
739       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
740         return R;
741
742     if (isa<PHINode>(Op0))
743       if (Instruction *NV = FoldOpIntoPhi(I))
744         return NV;
745   }
746
747   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
748     if (Op1I->hasOneUse()) {
749       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
750       // is not used by anyone else...
751       //
752       if (Op1I->getOpcode() == Instruction::Sub &&
753           !Op1I->getType()->isFloatingPoint()) {
754         // Swap the two operands of the subexpr...
755         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
756         Op1I->setOperand(0, IIOp1);
757         Op1I->setOperand(1, IIOp0);
758         
759         // Create the new top level add instruction...
760         return BinaryOperator::createAdd(Op0, Op1);
761       }
762
763       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
764       //
765       if (Op1I->getOpcode() == Instruction::And &&
766           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
767         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
768
769         Value *NewNot =
770           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
771         return BinaryOperator::createAnd(Op0, NewNot);
772       }
773
774       // -(X sdiv C)  -> (X sdiv -C)
775       if (Op1I->getOpcode() == Instruction::Div)
776         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
777           if (CSI->getValue() == 0)
778             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
779               return BinaryOperator::createDiv(Op1I->getOperand(0), 
780                                                ConstantExpr::getNeg(DivRHS));
781
782       // X - X*C --> X * (1-C)
783       if (dyn_castFoldableMul(Op1I) == Op0) {
784         Constant *CP1 =
785           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
786                          cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
787         assert(CP1 && "Couldn't constant fold 1-C?");
788         return BinaryOperator::createMul(Op0, CP1);
789       }
790     }
791
792   // X*C - X --> X * (C-1)
793   if (dyn_castFoldableMul(Op0) == Op1) {
794     Constant *CP1 =
795      ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
796                         ConstantInt::get(I.getType(), 1));
797     assert(CP1 && "Couldn't constant fold C - 1?");
798     return BinaryOperator::createMul(Op1, CP1);
799   }
800
801   return 0;
802 }
803
804 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
805 /// really just returns true if the most significant (sign) bit is set.
806 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
807   if (RHS->getType()->isSigned()) {
808     // True if source is LHS < 0 or LHS <= -1
809     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
810            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
811   } else {
812     ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
813     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
814     // the size of the integer type.
815     if (Opcode == Instruction::SetGE)
816       return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
817     if (Opcode == Instruction::SetGT)
818       return RHSC->getValue() ==
819         (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
820   }
821   return false;
822 }
823
824 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
825   bool Changed = SimplifyCommutative(I);
826   Value *Op0 = I.getOperand(0);
827
828   // Simplify mul instructions with a constant RHS...
829   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
830     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
831
832       // ((X << C1)*C2) == (X * (C2 << C1))
833       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
834         if (SI->getOpcode() == Instruction::Shl)
835           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
836             return BinaryOperator::createMul(SI->getOperand(0),
837                                              ConstantExpr::getShl(CI, ShOp));
838       
839       if (CI->isNullValue())
840         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
841       if (CI->equalsInt(1))                  // X * 1  == X
842         return ReplaceInstUsesWith(I, Op0);
843       if (CI->isAllOnesValue())              // X * -1 == 0 - X
844         return BinaryOperator::createNeg(Op0, I.getName());
845
846       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
847       if (uint64_t C = Log2(Val))            // Replace X*(2^C) with X << C
848         return new ShiftInst(Instruction::Shl, Op0,
849                              ConstantUInt::get(Type::UByteTy, C));
850     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
851       if (Op1F->isNullValue())
852         return ReplaceInstUsesWith(I, Op1);
853
854       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
855       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
856       if (Op1F->getValue() == 1.0)
857         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
858     }
859
860     // Try to fold constant mul into select arguments.
861     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
862       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
863         return R;
864
865     if (isa<PHINode>(Op0))
866       if (Instruction *NV = FoldOpIntoPhi(I))
867         return NV;
868   }
869
870   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
871     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
872       return BinaryOperator::createMul(Op0v, Op1v);
873
874   // If one of the operands of the multiply is a cast from a boolean value, then
875   // we know the bool is either zero or one, so this is a 'masking' multiply.
876   // See if we can simplify things based on how the boolean was originally
877   // formed.
878   CastInst *BoolCast = 0;
879   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
880     if (CI->getOperand(0)->getType() == Type::BoolTy)
881       BoolCast = CI;
882   if (!BoolCast)
883     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
884       if (CI->getOperand(0)->getType() == Type::BoolTy)
885         BoolCast = CI;
886   if (BoolCast) {
887     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
888       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
889       const Type *SCOpTy = SCIOp0->getType();
890
891       // If the setcc is true iff the sign bit of X is set, then convert this
892       // multiply into a shift/and combination.
893       if (isa<ConstantInt>(SCIOp1) &&
894           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
895         // Shift the X value right to turn it into "all signbits".
896         Constant *Amt = ConstantUInt::get(Type::UByteTy,
897                                           SCOpTy->getPrimitiveSize()*8-1);
898         if (SCIOp0->getType()->isUnsigned()) {
899           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
900           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
901                                                     SCIOp0->getName()), I);
902         }
903
904         Value *V =
905           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
906                                             BoolCast->getOperand(0)->getName()+
907                                             ".mask"), I);
908
909         // If the multiply type is not the same as the source type, sign extend
910         // or truncate to the multiply type.
911         if (I.getType() != V->getType())
912           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
913         
914         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
915         return BinaryOperator::createAnd(V, OtherOp);
916       }
917     }
918   }
919
920   return Changed ? &I : 0;
921 }
922
923 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
924   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
925     // div X, 1 == X
926     if (RHS->equalsInt(1))
927       return ReplaceInstUsesWith(I, I.getOperand(0));
928
929     // div X, -1 == -X
930     if (RHS->isAllOnesValue())
931       return BinaryOperator::createNeg(I.getOperand(0));
932
933     if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
934       if (LHS->getOpcode() == Instruction::Div)
935         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
936           // (X / C1) / C2  -> X / (C1*C2)
937           return BinaryOperator::createDiv(LHS->getOperand(0),
938                                            ConstantExpr::getMul(RHS, LHSRHS));
939         }
940
941     // Check to see if this is an unsigned division with an exact power of 2,
942     // if so, convert to a right shift.
943     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
944       if (uint64_t Val = C->getValue())    // Don't break X / 0
945         if (uint64_t C = Log2(Val))
946           return new ShiftInst(Instruction::Shr, I.getOperand(0),
947                                ConstantUInt::get(Type::UByteTy, C));
948
949     // -X/C -> X/-C
950     if (RHS->getType()->isSigned())
951       if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
952         return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
953
954     if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
955       if (Instruction *NV = FoldOpIntoPhi(I))
956         return NV;
957   }
958
959   // 0 / X == 0, we don't need to preserve faults!
960   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
961     if (LHS->equalsInt(0))
962       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
963
964   return 0;
965 }
966
967
968 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
969   if (I.getType()->isSigned())
970     if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
971       if (!isa<ConstantSInt>(RHSNeg) ||
972           cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
973         // X % -Y -> X % Y
974         AddUsesToWorkList(I);
975         I.setOperand(1, RHSNeg);
976         return &I;
977       }
978
979   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
980     if (RHS->equalsInt(1))  // X % 1 == 0
981       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
982
983     // Check to see if this is an unsigned remainder with an exact power of 2,
984     // if so, convert to a bitwise and.
985     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
986       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
987         if (!(Val & (Val-1)))              // Power of 2
988           return BinaryOperator::createAnd(I.getOperand(0),
989                                         ConstantUInt::get(I.getType(), Val-1));
990     if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
991       if (Instruction *NV = FoldOpIntoPhi(I))
992         return NV;
993   }
994
995   // 0 % X == 0, we don't need to preserve faults!
996   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
997     if (LHS->equalsInt(0))
998       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
999
1000   return 0;
1001 }
1002
1003 // isMaxValueMinusOne - return true if this is Max-1
1004 static bool isMaxValueMinusOne(const ConstantInt *C) {
1005   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1006     // Calculate -1 casted to the right type...
1007     unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1008     uint64_t Val = ~0ULL;                // All ones
1009     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1010     return CU->getValue() == Val-1;
1011   }
1012
1013   const ConstantSInt *CS = cast<ConstantSInt>(C);
1014   
1015   // Calculate 0111111111..11111
1016   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1017   int64_t Val = INT64_MAX;             // All ones
1018   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1019   return CS->getValue() == Val-1;
1020 }
1021
1022 // isMinValuePlusOne - return true if this is Min+1
1023 static bool isMinValuePlusOne(const ConstantInt *C) {
1024   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1025     return CU->getValue() == 1;
1026
1027   const ConstantSInt *CS = cast<ConstantSInt>(C);
1028   
1029   // Calculate 1111111111000000000000 
1030   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1031   int64_t Val = -1;                    // All ones
1032   Val <<= TypeBits-1;                  // Shift over to the right spot
1033   return CS->getValue() == Val+1;
1034 }
1035
1036 // isOneBitSet - Return true if there is exactly one bit set in the specified
1037 // constant.
1038 static bool isOneBitSet(const ConstantInt *CI) {
1039   uint64_t V = CI->getRawValue();
1040   return V && (V & (V-1)) == 0;
1041 }
1042
1043 #if 0   // Currently unused
1044 // isLowOnes - Return true if the constant is of the form 0+1+.
1045 static bool isLowOnes(const ConstantInt *CI) {
1046   uint64_t V = CI->getRawValue();
1047
1048   // There won't be bits set in parts that the type doesn't contain.
1049   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1050
1051   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1052   return U && V && (U & V) == 0;
1053 }
1054 #endif
1055
1056 // isHighOnes - Return true if the constant is of the form 1+0+.
1057 // This is the same as lowones(~X).
1058 static bool isHighOnes(const ConstantInt *CI) {
1059   uint64_t V = ~CI->getRawValue();
1060
1061   // There won't be bits set in parts that the type doesn't contain.
1062   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1063
1064   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1065   return U && V && (U & V) == 0;
1066 }
1067
1068
1069 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
1070 /// are carefully arranged to allow folding of expressions such as:
1071 ///
1072 ///      (A < B) | (A > B) --> (A != B)
1073 ///
1074 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1075 /// represents that the comparison is true if A == B, and bit value '1' is true
1076 /// if A < B.
1077 ///
1078 static unsigned getSetCondCode(const SetCondInst *SCI) {
1079   switch (SCI->getOpcode()) {
1080     // False -> 0
1081   case Instruction::SetGT: return 1;
1082   case Instruction::SetEQ: return 2;
1083   case Instruction::SetGE: return 3;
1084   case Instruction::SetLT: return 4;
1085   case Instruction::SetNE: return 5;
1086   case Instruction::SetLE: return 6;
1087     // True -> 7
1088   default:
1089     assert(0 && "Invalid SetCC opcode!");
1090     return 0;
1091   }
1092 }
1093
1094 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1095 /// opcode and two operands into either a constant true or false, or a brand new
1096 /// SetCC instruction.
1097 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1098   switch (Opcode) {
1099   case 0: return ConstantBool::False;
1100   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1101   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1102   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1103   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1104   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1105   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1106   case 7: return ConstantBool::True;
1107   default: assert(0 && "Illegal SetCCCode!"); return 0;
1108   }
1109 }
1110
1111 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1112 struct FoldSetCCLogical {
1113   InstCombiner &IC;
1114   Value *LHS, *RHS;
1115   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1116     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1117   bool shouldApply(Value *V) const {
1118     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1119       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1120               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1121     return false;
1122   }
1123   Instruction *apply(BinaryOperator &Log) const {
1124     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1125     if (SCI->getOperand(0) != LHS) {
1126       assert(SCI->getOperand(1) == LHS);
1127       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
1128     }
1129
1130     unsigned LHSCode = getSetCondCode(SCI);
1131     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1132     unsigned Code;
1133     switch (Log.getOpcode()) {
1134     case Instruction::And: Code = LHSCode & RHSCode; break;
1135     case Instruction::Or:  Code = LHSCode | RHSCode; break;
1136     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1137     default: assert(0 && "Illegal logical opcode!"); return 0;
1138     }
1139
1140     Value *RV = getSetCCValue(Code, LHS, RHS);
1141     if (Instruction *I = dyn_cast<Instruction>(RV))
1142       return I;
1143     // Otherwise, it's a constant boolean value...
1144     return IC.ReplaceInstUsesWith(Log, RV);
1145   }
1146 };
1147
1148
1149 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
1150 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
1151 // guaranteed to be either a shift instruction or a binary operator.
1152 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1153                                     ConstantIntegral *OpRHS,
1154                                     ConstantIntegral *AndRHS,
1155                                     BinaryOperator &TheAnd) {
1156   Value *X = Op->getOperand(0);
1157   Constant *Together = 0;
1158   if (!isa<ShiftInst>(Op))
1159     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1160
1161   switch (Op->getOpcode()) {
1162   case Instruction::Xor:
1163     if (Together->isNullValue()) {
1164       // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
1165       return BinaryOperator::createAnd(X, AndRHS);
1166     } else if (Op->hasOneUse()) {
1167       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1168       std::string OpName = Op->getName(); Op->setName("");
1169       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1170       InsertNewInstBefore(And, TheAnd);
1171       return BinaryOperator::createXor(And, Together);
1172     }
1173     break;
1174   case Instruction::Or:
1175     // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
1176     if (Together->isNullValue())
1177       return BinaryOperator::createAnd(X, AndRHS);
1178     else {
1179       if (Together == AndRHS) // (X | C) & C --> C
1180         return ReplaceInstUsesWith(TheAnd, AndRHS);
1181       
1182       if (Op->hasOneUse() && Together != OpRHS) {
1183         // (X | C1) & C2 --> (X | (C1&C2)) & C2
1184         std::string Op0Name = Op->getName(); Op->setName("");
1185         Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1186         InsertNewInstBefore(Or, TheAnd);
1187         return BinaryOperator::createAnd(Or, AndRHS);
1188       }
1189     }
1190     break;
1191   case Instruction::Add:
1192     if (Op->hasOneUse()) {
1193       // Adding a one to a single bit bit-field should be turned into an XOR
1194       // of the bit.  First thing to check is to see if this AND is with a
1195       // single bit constant.
1196       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1197
1198       // Clear bits that are not part of the constant.
1199       AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1200
1201       // If there is only one bit set...
1202       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1203         // Ok, at this point, we know that we are masking the result of the
1204         // ADD down to exactly one bit.  If the constant we are adding has
1205         // no bits set below this bit, then we can eliminate the ADD.
1206         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1207             
1208         // Check to see if any bits below the one bit set in AndRHSV are set.
1209         if ((AddRHS & (AndRHSV-1)) == 0) {
1210           // If not, the only thing that can effect the output of the AND is
1211           // the bit specified by AndRHSV.  If that bit is set, the effect of
1212           // the XOR is to toggle the bit.  If it is clear, then the ADD has
1213           // no effect.
1214           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1215             TheAnd.setOperand(0, X);
1216             return &TheAnd;
1217           } else {
1218             std::string Name = Op->getName(); Op->setName("");
1219             // Pull the XOR out of the AND.
1220             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1221             InsertNewInstBefore(NewAnd, TheAnd);
1222             return BinaryOperator::createXor(NewAnd, AndRHS);
1223           }
1224         }
1225       }
1226     }
1227     break;
1228
1229   case Instruction::Shl: {
1230     // We know that the AND will not produce any of the bits shifted in, so if
1231     // the anded constant includes them, clear them now!
1232     //
1233     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1234     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1235     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1236                                         
1237     if (CI == ShlMask) {   // Masking out bits that the shift already masks
1238       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
1239     } else if (CI != AndRHS) {                  // Reducing bits set in and.
1240       TheAnd.setOperand(1, CI);
1241       return &TheAnd;
1242     }
1243     break;
1244   } 
1245   case Instruction::Shr:
1246     // We know that the AND will not produce any of the bits shifted in, so if
1247     // the anded constant includes them, clear them now!  This only applies to
1248     // unsigned shifts, because a signed shr may bring in set bits!
1249     //
1250     if (AndRHS->getType()->isUnsigned()) {
1251       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1252       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1253       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1254
1255       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
1256         return ReplaceInstUsesWith(TheAnd, Op);
1257       } else if (CI != AndRHS) {
1258         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
1259         return &TheAnd;
1260       }
1261     } else {   // Signed shr.
1262       // See if this is shifting in some sign extension, then masking it out
1263       // with an and.
1264       if (Op->hasOneUse()) {
1265         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1266         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1267         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1268         if (CI == ShrMask) {          // Masking out bits shifted in.
1269           // Make the argument unsigned.
1270           Value *ShVal = Op->getOperand(0);
1271           ShVal = InsertCastBefore(ShVal,
1272                                    ShVal->getType()->getUnsignedVersion(),
1273                                    TheAnd);
1274           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1275                                                     OpRHS, Op->getName()),
1276                                       TheAnd);
1277           return new CastInst(ShVal, Op->getType());
1278         }
1279       }
1280     }
1281     break;
1282   }
1283   return 0;
1284 }
1285
1286
1287 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1288 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
1289 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
1290 /// insert new instructions.
1291 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1292                                            bool Inside, Instruction &IB) {
1293   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1294          "Lo is not <= Hi in range emission code!");
1295   if (Inside) {
1296     if (Lo == Hi)  // Trivially false.
1297       return new SetCondInst(Instruction::SetNE, V, V);
1298     if (cast<ConstantIntegral>(Lo)->isMinValue())
1299       return new SetCondInst(Instruction::SetLT, V, Hi);
1300     
1301     Constant *AddCST = ConstantExpr::getNeg(Lo);
1302     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1303     InsertNewInstBefore(Add, IB);
1304     // Convert to unsigned for the comparison.
1305     const Type *UnsType = Add->getType()->getUnsignedVersion();
1306     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1307     AddCST = ConstantExpr::getAdd(AddCST, Hi);
1308     AddCST = ConstantExpr::getCast(AddCST, UnsType);
1309     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1310   }
1311
1312   if (Lo == Hi)  // Trivially true.
1313     return new SetCondInst(Instruction::SetEQ, V, V);
1314
1315   Hi = SubOne(cast<ConstantInt>(Hi));
1316   if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1317     return new SetCondInst(Instruction::SetGT, V, Hi);
1318
1319   // Emit X-Lo > Hi-Lo-1
1320   Constant *AddCST = ConstantExpr::getNeg(Lo);
1321   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1322   InsertNewInstBefore(Add, IB);
1323   // Convert to unsigned for the comparison.
1324   const Type *UnsType = Add->getType()->getUnsignedVersion();
1325   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1326   AddCST = ConstantExpr::getAdd(AddCST, Hi);
1327   AddCST = ConstantExpr::getCast(AddCST, UnsType);
1328   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1329 }
1330
1331
1332 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1333   bool Changed = SimplifyCommutative(I);
1334   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1335
1336   // and X, X = X   and X, 0 == 0
1337   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1338     return ReplaceInstUsesWith(I, Op1);
1339
1340   // and X, -1 == X
1341   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1342     if (RHS->isAllOnesValue())
1343       return ReplaceInstUsesWith(I, Op0);
1344
1345     // Optimize a variety of ((val OP C1) & C2) combinations...
1346     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1347       Instruction *Op0I = cast<Instruction>(Op0);
1348       Value *X = Op0I->getOperand(0);
1349       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1350         if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1351           return Res;
1352     }
1353
1354     // Try to fold constant and into select arguments.
1355     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1356       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1357         return R;
1358     if (isa<PHINode>(Op0))
1359       if (Instruction *NV = FoldOpIntoPhi(I))
1360         return NV;
1361   }
1362
1363   Value *Op0NotVal = dyn_castNotVal(Op0);
1364   Value *Op1NotVal = dyn_castNotVal(Op1);
1365
1366   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
1367     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1368
1369   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1370   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1371     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1372                                                I.getName()+".demorgan");
1373     InsertNewInstBefore(Or, I);
1374     return BinaryOperator::createNot(Or);
1375   }
1376
1377   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1378     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1379     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1380       return R;
1381
1382     Value *LHSVal, *RHSVal;
1383     ConstantInt *LHSCst, *RHSCst;
1384     Instruction::BinaryOps LHSCC, RHSCC;
1385     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1386       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1387         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
1388             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1389             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && 
1390             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1391           // Ensure that the larger constant is on the RHS.
1392           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1393           SetCondInst *LHS = cast<SetCondInst>(Op0);
1394           if (cast<ConstantBool>(Cmp)->getValue()) {
1395             std::swap(LHS, RHS);
1396             std::swap(LHSCst, RHSCst);
1397             std::swap(LHSCC, RHSCC);
1398           }
1399
1400           // At this point, we know we have have two setcc instructions
1401           // comparing a value against two constants and and'ing the result
1402           // together.  Because of the above check, we know that we only have
1403           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
1404           // FoldSetCCLogical check above), that the two constants are not
1405           // equal.
1406           assert(LHSCst != RHSCst && "Compares not folded above?");
1407
1408           switch (LHSCC) {
1409           default: assert(0 && "Unknown integer condition code!");
1410           case Instruction::SetEQ:
1411             switch (RHSCC) {
1412             default: assert(0 && "Unknown integer condition code!");
1413             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
1414             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
1415               return ReplaceInstUsesWith(I, ConstantBool::False);
1416             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
1417             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
1418               return ReplaceInstUsesWith(I, LHS);
1419             }
1420           case Instruction::SetNE:
1421             switch (RHSCC) {
1422             default: assert(0 && "Unknown integer condition code!");
1423             case Instruction::SetLT:
1424               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1425                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1426               break;                        // (X != 13 & X < 15) -> no change
1427             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
1428             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
1429               return ReplaceInstUsesWith(I, RHS);
1430             case Instruction::SetNE:
1431               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1432                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1433                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1434                                                       LHSVal->getName()+".off");
1435                 InsertNewInstBefore(Add, I);
1436                 const Type *UnsType = Add->getType()->getUnsignedVersion();
1437                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1438                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1439                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1440                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1441               }
1442               break;                        // (X != 13 & X != 15) -> no change
1443             }
1444             break;
1445           case Instruction::SetLT:
1446             switch (RHSCC) {
1447             default: assert(0 && "Unknown integer condition code!");
1448             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
1449             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
1450               return ReplaceInstUsesWith(I, ConstantBool::False);
1451             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
1452             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
1453               return ReplaceInstUsesWith(I, LHS);
1454             }
1455           case Instruction::SetGT:
1456             switch (RHSCC) {
1457             default: assert(0 && "Unknown integer condition code!");
1458             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
1459               return ReplaceInstUsesWith(I, LHS);
1460             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
1461               return ReplaceInstUsesWith(I, RHS);
1462             case Instruction::SetNE:
1463               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1464                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1465               break;                        // (X > 13 & X != 15) -> no change
1466             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
1467               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
1468             }
1469           }
1470         }
1471   }
1472
1473   return Changed ? &I : 0;
1474 }
1475
1476 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1477   bool Changed = SimplifyCommutative(I);
1478   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1479
1480   // or X, X = X   or X, 0 == X
1481   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1482     return ReplaceInstUsesWith(I, Op0);
1483
1484   // or X, -1 == -1
1485   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1486     if (RHS->isAllOnesValue())
1487       return ReplaceInstUsesWith(I, Op1);
1488
1489     ConstantInt *C1; Value *X;
1490     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1491     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1492       std::string Op0Name = Op0->getName(); Op0->setName("");
1493       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1494       InsertNewInstBefore(Or, I);
1495       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1496     }
1497
1498     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1499     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1500       std::string Op0Name = Op0->getName(); Op0->setName("");
1501       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1502       InsertNewInstBefore(Or, I);
1503       return BinaryOperator::createXor(Or,
1504                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
1505     }
1506
1507     // Try to fold constant and into select arguments.
1508     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1509       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1510         return R;
1511     if (isa<PHINode>(Op0))
1512       if (Instruction *NV = FoldOpIntoPhi(I))
1513         return NV;
1514   }
1515
1516   // (A & C1)|(A & C2) == A & (C1|C2)
1517   Value *A, *B; ConstantInt *C1, *C2;
1518   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1519       match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1520     return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1521
1522   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
1523     if (A == Op1)   // ~A | A == -1
1524       return ReplaceInstUsesWith(I, 
1525                                 ConstantIntegral::getAllOnesValue(I.getType()));
1526   } else {
1527     A = 0;
1528   }
1529
1530   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
1531     if (Op0 == B)
1532       return ReplaceInstUsesWith(I, 
1533                                 ConstantIntegral::getAllOnesValue(I.getType()));
1534
1535     // (~A | ~B) == (~(A & B)) - De Morgan's Law
1536     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1537       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1538                                               I.getName()+".demorgan"), I);
1539       return BinaryOperator::createNot(And);
1540     }
1541   }
1542
1543   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1544   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
1545     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1546       return R;
1547
1548     Value *LHSVal, *RHSVal;
1549     ConstantInt *LHSCst, *RHSCst;
1550     Instruction::BinaryOps LHSCC, RHSCC;
1551     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1552       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1553         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
1554             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1555             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && 
1556             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1557           // Ensure that the larger constant is on the RHS.
1558           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1559           SetCondInst *LHS = cast<SetCondInst>(Op0);
1560           if (cast<ConstantBool>(Cmp)->getValue()) {
1561             std::swap(LHS, RHS);
1562             std::swap(LHSCst, RHSCst);
1563             std::swap(LHSCC, RHSCC);
1564           }
1565
1566           // At this point, we know we have have two setcc instructions
1567           // comparing a value against two constants and or'ing the result
1568           // together.  Because of the above check, we know that we only have
1569           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
1570           // FoldSetCCLogical check above), that the two constants are not
1571           // equal.
1572           assert(LHSCst != RHSCst && "Compares not folded above?");
1573
1574           switch (LHSCC) {
1575           default: assert(0 && "Unknown integer condition code!");
1576           case Instruction::SetEQ:
1577             switch (RHSCC) {
1578             default: assert(0 && "Unknown integer condition code!");
1579             case Instruction::SetEQ:
1580               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1581                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1582                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1583                                                       LHSVal->getName()+".off");
1584                 InsertNewInstBefore(Add, I);
1585                 const Type *UnsType = Add->getType()->getUnsignedVersion();
1586                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1587                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1588                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1589                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1590               }
1591               break;                  // (X == 13 | X == 15) -> no change
1592
1593             case Instruction::SetGT:
1594               if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1595                 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1596               break;                        // (X == 13 | X > 15) -> no change
1597             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
1598             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
1599               return ReplaceInstUsesWith(I, RHS);
1600             }
1601             break;
1602           case Instruction::SetNE:
1603             switch (RHSCC) {
1604             default: assert(0 && "Unknown integer condition code!");
1605             case Instruction::SetLT:        // (X != 13 | X < 15) -> X < 15
1606               return ReplaceInstUsesWith(I, RHS);
1607             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
1608             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
1609               return ReplaceInstUsesWith(I, LHS);
1610             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
1611               return ReplaceInstUsesWith(I, ConstantBool::True);
1612             }
1613             break;
1614           case Instruction::SetLT:
1615             switch (RHSCC) {
1616             default: assert(0 && "Unknown integer condition code!");
1617             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
1618               break;
1619             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
1620               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
1621             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
1622             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
1623               return ReplaceInstUsesWith(I, RHS);
1624             }
1625             break;
1626           case Instruction::SetGT:
1627             switch (RHSCC) {
1628             default: assert(0 && "Unknown integer condition code!");
1629             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
1630             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
1631               return ReplaceInstUsesWith(I, LHS);
1632             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
1633             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
1634               return ReplaceInstUsesWith(I, ConstantBool::True);
1635             }
1636           }
1637         }
1638   }
1639   return Changed ? &I : 0;
1640 }
1641
1642 // XorSelf - Implements: X ^ X --> 0
1643 struct XorSelf {
1644   Value *RHS;
1645   XorSelf(Value *rhs) : RHS(rhs) {}
1646   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1647   Instruction *apply(BinaryOperator &Xor) const {
1648     return &Xor;
1649   }
1650 };
1651
1652
1653 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1654   bool Changed = SimplifyCommutative(I);
1655   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1656
1657   // xor X, X = 0, even if X is nested in a sequence of Xor's.
1658   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1659     assert(Result == &I && "AssociativeOpt didn't work?");
1660     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1661   }
1662
1663   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1664     // xor X, 0 == X
1665     if (RHS->isNullValue())
1666       return ReplaceInstUsesWith(I, Op0);
1667
1668     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1669       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
1670       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
1671         if (RHS == ConstantBool::True && SCI->hasOneUse())
1672           return new SetCondInst(SCI->getInverseCondition(),
1673                                  SCI->getOperand(0), SCI->getOperand(1));
1674
1675       // ~(c-X) == X-c-1 == X+(-c-1)
1676       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1677         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1678           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1679           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1680                                               ConstantInt::get(I.getType(), 1));
1681           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
1682         }
1683
1684       // ~(~X & Y) --> (X | ~Y)
1685       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1686         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1687         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1688           Instruction *NotY =
1689             BinaryOperator::createNot(Op0I->getOperand(1), 
1690                                       Op0I->getOperand(1)->getName()+".not");
1691           InsertNewInstBefore(NotY, I);
1692           return BinaryOperator::createOr(Op0NotVal, NotY);
1693         }
1694       }
1695           
1696       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1697         switch (Op0I->getOpcode()) {
1698         case Instruction::Add:
1699           // ~(X-c) --> (-c-1)-X
1700           if (RHS->isAllOnesValue()) {
1701             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1702             return BinaryOperator::createSub(
1703                            ConstantExpr::getSub(NegOp0CI,
1704                                              ConstantInt::get(I.getType(), 1)),
1705                                           Op0I->getOperand(0));
1706           }
1707           break;
1708         case Instruction::And:
1709           // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1710           if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1711             return BinaryOperator::createOr(Op0, RHS);
1712           break;
1713         case Instruction::Or:
1714           // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1715           if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
1716             return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
1717           break;
1718         default: break;
1719         }
1720     }
1721
1722     // Try to fold constant and into select arguments.
1723     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1724       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1725         return R;
1726     if (isa<PHINode>(Op0))
1727       if (Instruction *NV = FoldOpIntoPhi(I))
1728         return NV;
1729   }
1730
1731   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
1732     if (X == Op1)
1733       return ReplaceInstUsesWith(I,
1734                                 ConstantIntegral::getAllOnesValue(I.getType()));
1735
1736   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
1737     if (X == Op0)
1738       return ReplaceInstUsesWith(I,
1739                                 ConstantIntegral::getAllOnesValue(I.getType()));
1740
1741   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1742     if (Op1I->getOpcode() == Instruction::Or) {
1743       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
1744         cast<BinaryOperator>(Op1I)->swapOperands();
1745         I.swapOperands();
1746         std::swap(Op0, Op1);
1747       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
1748         I.swapOperands();
1749         std::swap(Op0, Op1);
1750       }      
1751     } else if (Op1I->getOpcode() == Instruction::Xor) {
1752       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
1753         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1754       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
1755         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1756     }
1757
1758   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1759     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1760       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
1761         cast<BinaryOperator>(Op0I)->swapOperands();
1762       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
1763         Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1764                                                      Op1->getName()+".not"), I);
1765         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
1766       }
1767     } else if (Op0I->getOpcode() == Instruction::Xor) {
1768       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
1769         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1770       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
1771         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1772     }
1773
1774   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1775   Value *A, *B; ConstantInt *C1, *C2;
1776   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1777       match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
1778       ConstantExpr::getAnd(C1, C2)->isNullValue())
1779     return BinaryOperator::createOr(Op0, Op1);
1780
1781   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1782   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1783     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1784       return R;
1785
1786   return Changed ? &I : 0;
1787 }
1788
1789 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1790 /// overflowed for this type.
1791 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1792                             ConstantInt *In2) {
1793   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1794   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1795 }
1796
1797 static bool isPositive(ConstantInt *C) {
1798   return cast<ConstantSInt>(C)->getValue() >= 0;
1799 }
1800
1801 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1802 /// overflowed for this type.
1803 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1804                             ConstantInt *In2) {
1805   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1806
1807   if (In1->getType()->isUnsigned())
1808     return cast<ConstantUInt>(Result)->getValue() <
1809            cast<ConstantUInt>(In1)->getValue();
1810   if (isPositive(In1) != isPositive(In2))
1811     return false;
1812   if (isPositive(In1))
1813     return cast<ConstantSInt>(Result)->getValue() <
1814            cast<ConstantSInt>(In1)->getValue();
1815   return cast<ConstantSInt>(Result)->getValue() >
1816          cast<ConstantSInt>(In1)->getValue();
1817 }
1818
1819 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1820   bool Changed = SimplifyCommutative(I);
1821   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1822   const Type *Ty = Op0->getType();
1823
1824   // setcc X, X
1825   if (Op0 == Op1)
1826     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1827
1828   // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1829   if (isa<ConstantPointerNull>(Op1) && 
1830       (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1831     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1832
1833
1834   // setcc's with boolean values can always be turned into bitwise operations
1835   if (Ty == Type::BoolTy) {
1836     switch (I.getOpcode()) {
1837     default: assert(0 && "Invalid setcc instruction!");
1838     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
1839       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
1840       InsertNewInstBefore(Xor, I);
1841       return BinaryOperator::createNot(Xor);
1842     }
1843     case Instruction::SetNE:
1844       return BinaryOperator::createXor(Op0, Op1);
1845
1846     case Instruction::SetGT:
1847       std::swap(Op0, Op1);                   // Change setgt -> setlt
1848       // FALL THROUGH
1849     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
1850       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1851       InsertNewInstBefore(Not, I);
1852       return BinaryOperator::createAnd(Not, Op1);
1853     }
1854     case Instruction::SetGE:
1855       std::swap(Op0, Op1);                   // Change setge -> setle
1856       // FALL THROUGH
1857     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
1858       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1859       InsertNewInstBefore(Not, I);
1860       return BinaryOperator::createOr(Not, Op1);
1861     }
1862     }
1863   }
1864
1865   // See if we are doing a comparison between a constant and an instruction that
1866   // can be folded into the comparison.
1867   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1868     // Check to see if we are comparing against the minimum or maximum value...
1869     if (CI->isMinValue()) {
1870       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
1871         return ReplaceInstUsesWith(I, ConstantBool::False);
1872       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
1873         return ReplaceInstUsesWith(I, ConstantBool::True);
1874       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
1875         return BinaryOperator::createSetEQ(Op0, Op1);
1876       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
1877         return BinaryOperator::createSetNE(Op0, Op1);
1878
1879     } else if (CI->isMaxValue()) {
1880       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
1881         return ReplaceInstUsesWith(I, ConstantBool::False);
1882       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
1883         return ReplaceInstUsesWith(I, ConstantBool::True);
1884       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
1885         return BinaryOperator::createSetEQ(Op0, Op1);
1886       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
1887         return BinaryOperator::createSetNE(Op0, Op1);
1888
1889       // Comparing against a value really close to min or max?
1890     } else if (isMinValuePlusOne(CI)) {
1891       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
1892         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1893       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
1894         return BinaryOperator::createSetNE(Op0, SubOne(CI));
1895
1896     } else if (isMaxValueMinusOne(CI)) {
1897       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
1898         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1899       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
1900         return BinaryOperator::createSetNE(Op0, AddOne(CI));
1901     }
1902
1903     // If we still have a setle or setge instruction, turn it into the
1904     // appropriate setlt or setgt instruction.  Since the border cases have
1905     // already been handled above, this requires little checking.
1906     //
1907     if (I.getOpcode() == Instruction::SetLE)
1908       return BinaryOperator::createSetLT(Op0, AddOne(CI));
1909     if (I.getOpcode() == Instruction::SetGE)
1910       return BinaryOperator::createSetGT(Op0, SubOne(CI));
1911
1912     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1913       switch (LHSI->getOpcode()) {
1914       case Instruction::PHI:
1915         if (Instruction *NV = FoldOpIntoPhi(I))
1916           return NV;
1917         break;
1918       case Instruction::And:
1919         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1920             LHSI->getOperand(0)->hasOneUse()) {
1921           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1922           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1923           // happens a LOT in code produced by the C front-end, for bitfield
1924           // access.
1925           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1926           ConstantUInt *ShAmt;
1927           ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1928           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1929           const Type *Ty = LHSI->getType();
1930           
1931           // We can fold this as long as we can't shift unknown bits
1932           // into the mask.  This can only happen with signed shift
1933           // rights, as they sign-extend.
1934           if (ShAmt) {
1935             bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1936                            Shift->getType()->isUnsigned();
1937             if (!CanFold) {
1938               // To test for the bad case of the signed shr, see if any
1939               // of the bits shifted in could be tested after the mask.
1940               Constant *OShAmt = ConstantUInt::get(Type::UByteTy, 
1941                                    Ty->getPrimitiveSize()*8-ShAmt->getValue());
1942               Constant *ShVal = 
1943                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1944               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1945                 CanFold = true;
1946             }
1947             
1948             if (CanFold) {
1949               Constant *NewCst;
1950               if (Shift->getOpcode() == Instruction::Shl)
1951                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1952               else
1953                 NewCst = ConstantExpr::getShl(CI, ShAmt);
1954
1955               // Check to see if we are shifting out any of the bits being
1956               // compared.
1957               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1958                 // If we shifted bits out, the fold is not going to work out.
1959                 // As a special case, check to see if this means that the
1960                 // result is always true or false now.
1961                 if (I.getOpcode() == Instruction::SetEQ)
1962                   return ReplaceInstUsesWith(I, ConstantBool::False);
1963                 if (I.getOpcode() == Instruction::SetNE)
1964                   return ReplaceInstUsesWith(I, ConstantBool::True);
1965               } else {
1966                 I.setOperand(1, NewCst);
1967                 Constant *NewAndCST;
1968                 if (Shift->getOpcode() == Instruction::Shl)
1969                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1970                 else
1971                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1972                 LHSI->setOperand(1, NewAndCST);
1973                 LHSI->setOperand(0, Shift->getOperand(0));
1974                 WorkList.push_back(Shift); // Shift is dead.
1975                 AddUsesToWorkList(I);
1976                 return &I;
1977               }
1978             }
1979           }
1980         }
1981         break;
1982
1983       case Instruction::Cast: {       // (setcc (cast X to larger), CI)
1984         const Type *SrcTy = LHSI->getOperand(0)->getType();
1985         if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
1986           unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
1987           if (SrcTy == Type::BoolTy) SrcBits = 1;
1988           unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
1989           if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1990           if (SrcBits < DestBits) {
1991             // Check to see if the comparison is always true or false.
1992             Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1993             if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1994               Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1995               Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1996               Min = ConstantExpr::getCast(Min, LHSI->getType());
1997               Max = ConstantExpr::getCast(Max, LHSI->getType());
1998               switch (I.getOpcode()) {
1999               default: assert(0 && "unknown integer comparison");
2000               case Instruction::SetEQ:
2001                 return ReplaceInstUsesWith(I, ConstantBool::False);
2002               case Instruction::SetNE:
2003                 return ReplaceInstUsesWith(I, ConstantBool::True);
2004               case Instruction::SetLT:
2005                 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2006               case Instruction::SetGT:
2007                 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2008               }
2009             }
2010
2011             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2012                                    ConstantExpr::getCast(CI, SrcTy));
2013           }
2014         }
2015         break;
2016       }
2017       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
2018         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2019           switch (I.getOpcode()) {
2020           default: break;
2021           case Instruction::SetEQ:
2022           case Instruction::SetNE: {
2023             // If we are comparing against bits always shifted out, the
2024             // comparison cannot succeed.
2025             Constant *Comp = 
2026               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2027             if (Comp != CI) {// Comparing against a bit that we know is zero.
2028               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2029               Constant *Cst = ConstantBool::get(IsSetNE);
2030               return ReplaceInstUsesWith(I, Cst);
2031             }
2032
2033             if (LHSI->hasOneUse()) {
2034               // Otherwise strength reduce the shift into an and.
2035               unsigned ShAmtVal = ShAmt->getValue();
2036               unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2037               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2038
2039               Constant *Mask;
2040               if (CI->getType()->isUnsigned()) {
2041                 Mask = ConstantUInt::get(CI->getType(), Val);
2042               } else if (ShAmtVal != 0) {
2043                 Mask = ConstantSInt::get(CI->getType(), Val);
2044               } else {
2045                 Mask = ConstantInt::getAllOnesValue(CI->getType());
2046               }
2047               
2048               Instruction *AndI =
2049                 BinaryOperator::createAnd(LHSI->getOperand(0),
2050                                           Mask, LHSI->getName()+".mask");
2051               Value *And = InsertNewInstBefore(AndI, I);
2052               return new SetCondInst(I.getOpcode(), And,
2053                                      ConstantExpr::getUShr(CI, ShAmt));
2054             }
2055           }
2056           }
2057         }
2058         break;
2059
2060       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
2061         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2062           switch (I.getOpcode()) {
2063           default: break;
2064           case Instruction::SetEQ:
2065           case Instruction::SetNE: {
2066             // If we are comparing against bits always shifted out, the
2067             // comparison cannot succeed.
2068             Constant *Comp = 
2069               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2070             
2071             if (Comp != CI) {// Comparing against a bit that we know is zero.
2072               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2073               Constant *Cst = ConstantBool::get(IsSetNE);
2074               return ReplaceInstUsesWith(I, Cst);
2075             }
2076               
2077             if (LHSI->hasOneUse() || CI->isNullValue()) {
2078               unsigned ShAmtVal = ShAmt->getValue();
2079
2080               // Otherwise strength reduce the shift into an and.
2081               uint64_t Val = ~0ULL;          // All ones.
2082               Val <<= ShAmtVal;              // Shift over to the right spot.
2083
2084               Constant *Mask;
2085               if (CI->getType()->isUnsigned()) {
2086                 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2087                 Val &= (1ULL << TypeBits)-1;
2088                 Mask = ConstantUInt::get(CI->getType(), Val);
2089               } else {
2090                 Mask = ConstantSInt::get(CI->getType(), Val);
2091               }
2092               
2093               Instruction *AndI =
2094                 BinaryOperator::createAnd(LHSI->getOperand(0),
2095                                           Mask, LHSI->getName()+".mask");
2096               Value *And = InsertNewInstBefore(AndI, I);
2097               return new SetCondInst(I.getOpcode(), And,
2098                                      ConstantExpr::getShl(CI, ShAmt));
2099             }
2100             break;
2101           }
2102           }
2103         }
2104         break;
2105
2106       case Instruction::Div:
2107         // Fold: (div X, C1) op C2 -> range check
2108         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2109           // Fold this div into the comparison, producing a range check.
2110           // Determine, based on the divide type, what the range is being
2111           // checked.  If there is an overflow on the low or high side, remember
2112           // it, otherwise compute the range [low, hi) bounding the new value.
2113           bool LoOverflow = false, HiOverflow = 0;
2114           ConstantInt *LoBound = 0, *HiBound = 0;
2115
2116           ConstantInt *Prod;
2117           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2118
2119           Instruction::BinaryOps Opcode = I.getOpcode();
2120
2121           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
2122           } else if (LHSI->getType()->isUnsigned()) {  // udiv
2123             LoBound = Prod;
2124             LoOverflow = ProdOV;
2125             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2126           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
2127             if (CI->isNullValue()) {       // (X / pos) op 0
2128               // Can't overflow.
2129               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2130               HiBound = DivRHS;
2131             } else if (isPositive(CI)) {   // (X / pos) op pos
2132               LoBound = Prod;
2133               LoOverflow = ProdOV;
2134               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2135             } else {                       // (X / pos) op neg
2136               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2137               LoOverflow = AddWithOverflow(LoBound, Prod,
2138                                            cast<ConstantInt>(DivRHSH));
2139               HiBound = Prod;
2140               HiOverflow = ProdOV;
2141             }
2142           } else {                                     // Divisor is < 0.
2143             if (CI->isNullValue()) {       // (X / neg) op 0
2144               LoBound = AddOne(DivRHS);
2145               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2146             } else if (isPositive(CI)) {   // (X / neg) op pos
2147               HiOverflow = LoOverflow = ProdOV;
2148               if (!LoOverflow)
2149                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2150               HiBound = AddOne(Prod);
2151             } else {                       // (X / neg) op neg
2152               LoBound = Prod;
2153               LoOverflow = HiOverflow = ProdOV;
2154               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2155             }
2156
2157             // Dividing by a negate swaps the condition.
2158             Opcode = SetCondInst::getSwappedCondition(Opcode);
2159           }
2160
2161           if (LoBound) {
2162             Value *X = LHSI->getOperand(0);
2163             switch (Opcode) {
2164             default: assert(0 && "Unhandled setcc opcode!");
2165             case Instruction::SetEQ:
2166               if (LoOverflow && HiOverflow)
2167                 return ReplaceInstUsesWith(I, ConstantBool::False);
2168               else if (HiOverflow)
2169                 return new SetCondInst(Instruction::SetGE, X, LoBound);
2170               else if (LoOverflow)
2171                 return new SetCondInst(Instruction::SetLT, X, HiBound);
2172               else
2173                 return InsertRangeTest(X, LoBound, HiBound, true, I);
2174             case Instruction::SetNE:
2175               if (LoOverflow && HiOverflow)
2176                 return ReplaceInstUsesWith(I, ConstantBool::True);
2177               else if (HiOverflow)
2178                 return new SetCondInst(Instruction::SetLT, X, LoBound);
2179               else if (LoOverflow)
2180                 return new SetCondInst(Instruction::SetGE, X, HiBound);
2181               else
2182                 return InsertRangeTest(X, LoBound, HiBound, false, I);
2183             case Instruction::SetLT:
2184               if (LoOverflow)
2185                 return ReplaceInstUsesWith(I, ConstantBool::False);
2186               return new SetCondInst(Instruction::SetLT, X, LoBound);
2187             case Instruction::SetGT:
2188               if (HiOverflow)
2189                 return ReplaceInstUsesWith(I, ConstantBool::False);
2190               return new SetCondInst(Instruction::SetGE, X, HiBound);
2191             }
2192           }
2193         }
2194         break;
2195       case Instruction::Select:
2196         // If either operand of the select is a constant, we can fold the
2197         // comparison into the select arms, which will cause one to be
2198         // constant folded and the select turned into a bitwise or.
2199         Value *Op1 = 0, *Op2 = 0;
2200         if (LHSI->hasOneUse()) {
2201           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2202             // Fold the known value into the constant operand.
2203             Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2204             // Insert a new SetCC of the other select operand.
2205             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2206                                                       LHSI->getOperand(2), CI,
2207                                                       I.getName()), I);
2208           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2209             // Fold the known value into the constant operand.
2210             Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2211             // Insert a new SetCC of the other select operand.
2212             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2213                                                       LHSI->getOperand(1), CI,
2214                                                       I.getName()), I);
2215           }
2216         }
2217         
2218         if (Op1)
2219           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2220         break;
2221       }
2222     
2223     // Simplify seteq and setne instructions...
2224     if (I.getOpcode() == Instruction::SetEQ ||
2225         I.getOpcode() == Instruction::SetNE) {
2226       bool isSetNE = I.getOpcode() == Instruction::SetNE;
2227
2228       // If the first operand is (and|or|xor) with a constant, and the second
2229       // operand is a constant, simplify a bit.
2230       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2231         switch (BO->getOpcode()) {
2232         case Instruction::Rem:
2233           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2234           if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2235               BO->hasOneUse() &&
2236               cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2237             if (unsigned L2 =
2238                 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2239               const Type *UTy = BO->getType()->getUnsignedVersion();
2240               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2241                                                              UTy, "tmp"), I);
2242               Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2243               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2244                                                     RHSCst, BO->getName()), I);
2245               return BinaryOperator::create(I.getOpcode(), NewRem,
2246                                             Constant::getNullValue(UTy));
2247             }
2248           break;          
2249
2250         case Instruction::Add:
2251           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2252           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2253             if (BO->hasOneUse())
2254               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2255                                      ConstantExpr::getSub(CI, BOp1C));
2256           } else if (CI->isNullValue()) {
2257             // Replace ((add A, B) != 0) with (A != -B) if A or B is
2258             // efficiently invertible, or if the add has just this one use.
2259             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2260             
2261             if (Value *NegVal = dyn_castNegVal(BOp1))
2262               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2263             else if (Value *NegVal = dyn_castNegVal(BOp0))
2264               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
2265             else if (BO->hasOneUse()) {
2266               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2267               BO->setName("");
2268               InsertNewInstBefore(Neg, I);
2269               return new SetCondInst(I.getOpcode(), BOp0, Neg);
2270             }
2271           }
2272           break;
2273         case Instruction::Xor:
2274           // For the xor case, we can xor two constants together, eliminating
2275           // the explicit xor.
2276           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2277             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
2278                                   ConstantExpr::getXor(CI, BOC));
2279
2280           // FALLTHROUGH
2281         case Instruction::Sub:
2282           // Replace (([sub|xor] A, B) != 0) with (A != B)
2283           if (CI->isNullValue())
2284             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2285                                    BO->getOperand(1));
2286           break;
2287
2288         case Instruction::Or:
2289           // If bits are being or'd in that are not present in the constant we
2290           // are comparing against, then the comparison could never succeed!
2291           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2292             Constant *NotCI = ConstantExpr::getNot(CI);
2293             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2294               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2295           }
2296           break;
2297
2298         case Instruction::And:
2299           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2300             // If bits are being compared against that are and'd out, then the
2301             // comparison can never succeed!
2302             if (!ConstantExpr::getAnd(CI,
2303                                       ConstantExpr::getNot(BOC))->isNullValue())
2304               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2305
2306             // If we have ((X & C) == C), turn it into ((X & C) != 0).
2307             if (CI == BOC && isOneBitSet(CI))
2308               return new SetCondInst(isSetNE ? Instruction::SetEQ :
2309                                      Instruction::SetNE, Op0,
2310                                      Constant::getNullValue(CI->getType()));
2311
2312             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2313             // to be a signed value as appropriate.
2314             if (isSignBit(BOC)) {
2315               Value *X = BO->getOperand(0);
2316               // If 'X' is not signed, insert a cast now...
2317               if (!BOC->getType()->isSigned()) {
2318                 const Type *DestTy = BOC->getType()->getSignedVersion();
2319                 X = InsertCastBefore(X, DestTy, I);
2320               }
2321               return new SetCondInst(isSetNE ? Instruction::SetLT :
2322                                          Instruction::SetGE, X,
2323                                      Constant::getNullValue(X->getType()));
2324             }
2325             
2326             // ((X & ~7) == 0) --> X < 8
2327             if (CI->isNullValue() && isHighOnes(BOC)) {
2328               Value *X = BO->getOperand(0);
2329               Constant *NegX = ConstantExpr::getNeg(BOC);
2330
2331               // If 'X' is signed, insert a cast now.
2332               if (NegX->getType()->isSigned()) {
2333                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2334                 X = InsertCastBefore(X, DestTy, I);
2335                 NegX = ConstantExpr::getCast(NegX, DestTy);
2336               }
2337
2338               return new SetCondInst(isSetNE ? Instruction::SetGE :
2339                                      Instruction::SetLT, X, NegX);
2340             }
2341
2342           }
2343         default: break;
2344         }
2345       }
2346     } else {  // Not a SetEQ/SetNE
2347       // If the LHS is a cast from an integral value of the same size, 
2348       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2349         Value *CastOp = Cast->getOperand(0);
2350         const Type *SrcTy = CastOp->getType();
2351         unsigned SrcTySize = SrcTy->getPrimitiveSize();
2352         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2353             SrcTySize == Cast->getType()->getPrimitiveSize()) {
2354           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) && 
2355                  "Source and destination signednesses should differ!");
2356           if (Cast->getType()->isSigned()) {
2357             // If this is a signed comparison, check for comparisons in the
2358             // vicinity of zero.
2359             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2360               // X < 0  => x > 127
2361               return BinaryOperator::createSetGT(CastOp,
2362                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2363             else if (I.getOpcode() == Instruction::SetGT &&
2364                      cast<ConstantSInt>(CI)->getValue() == -1)
2365               // X > -1  => x < 128
2366               return BinaryOperator::createSetLT(CastOp,
2367                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2368           } else {
2369             ConstantUInt *CUI = cast<ConstantUInt>(CI);
2370             if (I.getOpcode() == Instruction::SetLT &&
2371                 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2372               // X < 128 => X > -1
2373               return BinaryOperator::createSetGT(CastOp,
2374                                                  ConstantSInt::get(SrcTy, -1));
2375             else if (I.getOpcode() == Instruction::SetGT &&
2376                      CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2377               // X > 127 => X < 0
2378               return BinaryOperator::createSetLT(CastOp,
2379                                                  Constant::getNullValue(SrcTy));
2380           }
2381         }
2382       }
2383     }
2384   }
2385
2386   // Test to see if the operands of the setcc are casted versions of other
2387   // values.  If the cast can be stripped off both arguments, we do so now.
2388   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2389     Value *CastOp0 = CI->getOperand(0);
2390     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
2391         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
2392         (I.getOpcode() == Instruction::SetEQ ||
2393          I.getOpcode() == Instruction::SetNE)) {
2394       // We keep moving the cast from the left operand over to the right
2395       // operand, where it can often be eliminated completely.
2396       Op0 = CastOp0;
2397       
2398       // If operand #1 is a cast instruction, see if we can eliminate it as
2399       // well.
2400       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2401         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
2402                                                                Op0->getType()))
2403           Op1 = CI2->getOperand(0);
2404       
2405       // If Op1 is a constant, we can fold the cast into the constant.
2406       if (Op1->getType() != Op0->getType())
2407         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2408           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2409         } else {
2410           // Otherwise, cast the RHS right before the setcc
2411           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2412           InsertNewInstBefore(cast<Instruction>(Op1), I);
2413         }
2414       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2415     }
2416
2417     // Handle the special case of: setcc (cast bool to X), <cst>
2418     // This comes up when you have code like
2419     //   int X = A < B;
2420     //   if (X) ...
2421     // For generality, we handle any zero-extension of any operand comparison
2422     // with a constant.
2423     if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2424       const Type *SrcTy = CastOp0->getType();
2425       const Type *DestTy = Op0->getType();
2426       if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2427           (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2428         // Ok, we have an expansion of operand 0 into a new type.  Get the
2429         // constant value, masink off bits which are not set in the RHS.  These
2430         // could be set if the destination value is signed.
2431         uint64_t ConstVal = ConstantRHS->getRawValue();
2432         ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2433
2434         // If the constant we are comparing it with has high bits set, which
2435         // don't exist in the original value, the values could never be equal,
2436         // because the source would be zero extended.
2437         unsigned SrcBits =
2438           SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
2439         bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2440         if (ConstVal & ~((1ULL << SrcBits)-1)) {
2441           switch (I.getOpcode()) {
2442           default: assert(0 && "Unknown comparison type!");
2443           case Instruction::SetEQ:
2444             return ReplaceInstUsesWith(I, ConstantBool::False);
2445           case Instruction::SetNE:
2446             return ReplaceInstUsesWith(I, ConstantBool::True);
2447           case Instruction::SetLT:
2448           case Instruction::SetLE:
2449             if (DestTy->isSigned() && HasSignBit)
2450               return ReplaceInstUsesWith(I, ConstantBool::False);
2451             return ReplaceInstUsesWith(I, ConstantBool::True);
2452           case Instruction::SetGT:
2453           case Instruction::SetGE:
2454             if (DestTy->isSigned() && HasSignBit)
2455               return ReplaceInstUsesWith(I, ConstantBool::True);
2456             return ReplaceInstUsesWith(I, ConstantBool::False);
2457           }
2458         }
2459         
2460         // Otherwise, we can replace the setcc with a setcc of the smaller
2461         // operand value.
2462         Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2463         return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2464       }
2465     }
2466   }
2467   return Changed ? &I : 0;
2468 }
2469
2470
2471
2472 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
2473   assert(I.getOperand(1)->getType() == Type::UByteTy);
2474   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2475   bool isLeftShift = I.getOpcode() == Instruction::Shl;
2476
2477   // shl X, 0 == X and shr X, 0 == X
2478   // shl 0, X == 0 and shr 0, X == 0
2479   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
2480       Op0 == Constant::getNullValue(Op0->getType()))
2481     return ReplaceInstUsesWith(I, Op0);
2482
2483   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
2484   if (!isLeftShift)
2485     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2486       if (CSI->isAllOnesValue())
2487         return ReplaceInstUsesWith(I, CSI);
2488
2489   // Try to fold constant and into select arguments.
2490   if (isa<Constant>(Op0))
2491     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2492       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2493         return R;
2494
2495   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
2496     // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2497     // of a signed value.
2498     //
2499     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
2500     if (CUI->getValue() >= TypeBits) {
2501       if (!Op0->getType()->isSigned() || isLeftShift)
2502         return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2503       else {
2504         I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2505         return &I;
2506       }
2507     }
2508
2509     // ((X*C1) << C2) == (X * (C1 << C2))
2510     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2511       if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2512         if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
2513           return BinaryOperator::createMul(BO->getOperand(0),
2514                                            ConstantExpr::getShl(BOOp, CUI));
2515     
2516     // Try to fold constant and into select arguments.
2517     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2518       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2519         return R;
2520     if (isa<PHINode>(Op0))
2521       if (Instruction *NV = FoldOpIntoPhi(I))
2522         return NV;
2523
2524     // If the operand is an bitwise operator with a constant RHS, and the
2525     // shift is the only use, we can pull it out of the shift.
2526     if (Op0->hasOneUse())
2527       if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2528         if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2529           bool isValid = true;     // Valid only for And, Or, Xor
2530           bool highBitSet = false; // Transform if high bit of constant set?
2531
2532           switch (Op0BO->getOpcode()) {
2533           default: isValid = false; break;   // Do not perform transform!
2534           case Instruction::Add:
2535             isValid = isLeftShift;
2536             break;
2537           case Instruction::Or:
2538           case Instruction::Xor:
2539             highBitSet = false;
2540             break;
2541           case Instruction::And:
2542             highBitSet = true;
2543             break;
2544           }
2545
2546           // If this is a signed shift right, and the high bit is modified
2547           // by the logical operation, do not perform the transformation.
2548           // The highBitSet boolean indicates the value of the high bit of
2549           // the constant which would cause it to be modified for this
2550           // operation.
2551           //
2552           if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2553             uint64_t Val = Op0C->getRawValue();
2554             isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2555           }
2556
2557           if (isValid) {
2558             Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
2559
2560             Instruction *NewShift =
2561               new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2562                             Op0BO->getName());
2563             Op0BO->setName("");
2564             InsertNewInstBefore(NewShift, I);
2565
2566             return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2567                                           NewRHS);
2568           }
2569         }
2570
2571     // If this is a shift of a shift, see if we can fold the two together...
2572     if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
2573       if (ConstantUInt *ShiftAmt1C =
2574                                  dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
2575         unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2576         unsigned ShiftAmt2 = CUI->getValue();
2577         
2578         // Check for (A << c1) << c2   and   (A >> c1) >> c2
2579         if (I.getOpcode() == Op0SI->getOpcode()) {
2580           unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
2581           if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2582             Amt = Op0->getType()->getPrimitiveSize()*8;
2583           return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2584                                ConstantUInt::get(Type::UByteTy, Amt));
2585         }
2586         
2587         // Check for (A << c1) >> c2 or visaversa.  If we are dealing with
2588         // signed types, we can only support the (A >> c1) << c2 configuration,
2589         // because it can not turn an arbitrary bit of A into a sign bit.
2590         if (I.getType()->isUnsigned() || isLeftShift) {
2591           // Calculate bitmask for what gets shifted off the edge...
2592           Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
2593           if (isLeftShift)
2594             C = ConstantExpr::getShl(C, ShiftAmt1C);
2595           else
2596             C = ConstantExpr::getShr(C, ShiftAmt1C);
2597           
2598           Instruction *Mask =
2599             BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2600                                       Op0SI->getOperand(0)->getName()+".mask");
2601           InsertNewInstBefore(Mask, I);
2602           
2603           // Figure out what flavor of shift we should use...
2604           if (ShiftAmt1 == ShiftAmt2)
2605             return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
2606           else if (ShiftAmt1 < ShiftAmt2) {
2607             return new ShiftInst(I.getOpcode(), Mask,
2608                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2609           } else {
2610             return new ShiftInst(Op0SI->getOpcode(), Mask,
2611                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2612           }
2613         }
2614       }
2615   }
2616
2617   return 0;
2618 }
2619
2620 enum CastType {
2621   Noop     = 0,
2622   Truncate = 1,
2623   Signext  = 2,
2624   Zeroext  = 3
2625 };
2626
2627 /// getCastType - In the future, we will split the cast instruction into these
2628 /// various types.  Until then, we have to do the analysis here.
2629 static CastType getCastType(const Type *Src, const Type *Dest) {
2630   assert(Src->isIntegral() && Dest->isIntegral() &&
2631          "Only works on integral types!");
2632   unsigned SrcSize = Src->getPrimitiveSize()*8;
2633   if (Src == Type::BoolTy) SrcSize = 1;
2634   unsigned DestSize = Dest->getPrimitiveSize()*8;
2635   if (Dest == Type::BoolTy) DestSize = 1;
2636
2637   if (SrcSize == DestSize) return Noop;
2638   if (SrcSize > DestSize)  return Truncate;
2639   if (Src->isSigned()) return Signext;
2640   return Zeroext;
2641 }
2642
2643
2644 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2645 // instruction.
2646 //
2647 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
2648                                           const Type *DstTy, TargetData *TD) {
2649
2650   // It is legal to eliminate the instruction if casting A->B->A if the sizes
2651   // are identical and the bits don't get reinterpreted (for example 
2652   // int->float->int would not be allowed).
2653   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
2654     return true;
2655
2656   // If we are casting between pointer and integer types, treat pointers as
2657   // integers of the appropriate size for the code below.
2658   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2659   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2660   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
2661
2662   // Allow free casting and conversion of sizes as long as the sign doesn't
2663   // change...
2664   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
2665     CastType FirstCast = getCastType(SrcTy, MidTy);
2666     CastType SecondCast = getCastType(MidTy, DstTy);
2667
2668     // Capture the effect of these two casts.  If the result is a legal cast,
2669     // the CastType is stored here, otherwise a special code is used.
2670     static const unsigned CastResult[] = {
2671       // First cast is noop
2672       0, 1, 2, 3,
2673       // First cast is a truncate
2674       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
2675       // First cast is a sign ext
2676       2, 5, 2, 4,         // signext->zeroext never ok
2677       // First cast is a zero ext
2678       3, 5, 3, 3,
2679     };
2680
2681     unsigned Result = CastResult[FirstCast*4+SecondCast];
2682     switch (Result) {
2683     default: assert(0 && "Illegal table value!");
2684     case 0:
2685     case 1:
2686     case 2:
2687     case 3:
2688       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2689       // truncates, we could eliminate more casts.
2690       return (unsigned)getCastType(SrcTy, DstTy) == Result;
2691     case 4:
2692       return false;  // Not possible to eliminate this here.
2693     case 5:
2694       // Sign or zero extend followed by truncate is always ok if the result
2695       // is a truncate or noop.
2696       CastType ResultCast = getCastType(SrcTy, DstTy);
2697       if (ResultCast == Noop || ResultCast == Truncate)
2698         return true;
2699       // Otherwise we are still growing the value, we are only safe if the 
2700       // result will match the sign/zeroextendness of the result.
2701       return ResultCast == FirstCast;
2702     }
2703   }
2704   return false;
2705 }
2706
2707 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
2708   if (V->getType() == Ty || isa<Constant>(V)) return false;
2709   if (const CastInst *CI = dyn_cast<CastInst>(V))
2710     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2711                                TD))
2712       return false;
2713   return true;
2714 }
2715
2716 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2717 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
2718 /// casts that are known to not do anything...
2719 ///
2720 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2721                                              Instruction *InsertBefore) {
2722   if (V->getType() == DestTy) return V;
2723   if (Constant *C = dyn_cast<Constant>(V))
2724     return ConstantExpr::getCast(C, DestTy);
2725
2726   CastInst *CI = new CastInst(V, DestTy, V->getName());
2727   InsertNewInstBefore(CI, *InsertBefore);
2728   return CI;
2729 }
2730
2731 // CastInst simplification
2732 //
2733 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
2734   Value *Src = CI.getOperand(0);
2735
2736   // If the user is casting a value to the same type, eliminate this cast
2737   // instruction...
2738   if (CI.getType() == Src->getType())
2739     return ReplaceInstUsesWith(CI, Src);
2740
2741   // If casting the result of another cast instruction, try to eliminate this
2742   // one!
2743   //
2744   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
2745     if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2746                                CSrc->getType(), CI.getType(), TD)) {
2747       // This instruction now refers directly to the cast's src operand.  This
2748       // has a good chance of making CSrc dead.
2749       CI.setOperand(0, CSrc->getOperand(0));
2750       return &CI;
2751     }
2752
2753     // If this is an A->B->A cast, and we are dealing with integral types, try
2754     // to convert this into a logical 'and' instruction.
2755     //
2756     if (CSrc->getOperand(0)->getType() == CI.getType() &&
2757         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
2758         CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2759         CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2760       assert(CSrc->getType() != Type::ULongTy &&
2761              "Cannot have type bigger than ulong!");
2762       uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
2763       Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
2764       return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
2765     }
2766   }
2767
2768   // If this is a cast to bool, turn it into the appropriate setne instruction.
2769   if (CI.getType() == Type::BoolTy)
2770     return BinaryOperator::createSetNE(CI.getOperand(0),
2771                        Constant::getNullValue(CI.getOperand(0)->getType()));
2772
2773   // If casting the result of a getelementptr instruction with no offset, turn
2774   // this into a cast of the original pointer!
2775   //
2776   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2777     bool AllZeroOperands = true;
2778     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2779       if (!isa<Constant>(GEP->getOperand(i)) ||
2780           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2781         AllZeroOperands = false;
2782         break;
2783       }
2784     if (AllZeroOperands) {
2785       CI.setOperand(0, GEP->getOperand(0));
2786       return &CI;
2787     }
2788   }
2789
2790   // If we are casting a malloc or alloca to a pointer to a type of the same
2791   // size, rewrite the allocation instruction to allocate the "right" type.
2792   //
2793   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
2794     if (AI->hasOneUse() && !AI->isArrayAllocation())
2795       if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2796         // Get the type really allocated and the type casted to...
2797         const Type *AllocElTy = AI->getAllocatedType();
2798         const Type *CastElTy = PTy->getElementType();
2799         if (AllocElTy->isSized() && CastElTy->isSized()) {
2800           unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2801           unsigned CastElTySize = TD->getTypeSize(CastElTy);
2802
2803           // If the allocation is for an even multiple of the cast type size
2804           if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2805             Value *Amt = ConstantUInt::get(Type::UIntTy, 
2806                                          AllocElTySize/CastElTySize);
2807             std::string Name = AI->getName(); AI->setName("");
2808             AllocationInst *New;
2809             if (isa<MallocInst>(AI))
2810               New = new MallocInst(CastElTy, Amt, Name);
2811             else
2812               New = new AllocaInst(CastElTy, Amt, Name);
2813             InsertNewInstBefore(New, *AI);
2814             return ReplaceInstUsesWith(CI, New);
2815           }
2816         }
2817       }
2818
2819   if (isa<PHINode>(Src))
2820     if (Instruction *NV = FoldOpIntoPhi(CI))
2821       return NV;
2822
2823   // If the source value is an instruction with only this use, we can attempt to
2824   // propagate the cast into the instruction.  Also, only handle integral types
2825   // for now.
2826   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
2827     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
2828         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
2829       const Type *DestTy = CI.getType();
2830       unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2831       unsigned DestBitSize = getTypeSizeInBits(DestTy);
2832
2833       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2834       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2835
2836       switch (SrcI->getOpcode()) {
2837       case Instruction::Add:
2838       case Instruction::Mul:
2839       case Instruction::And:
2840       case Instruction::Or:
2841       case Instruction::Xor:
2842         // If we are discarding information, or just changing the sign, rewrite.
2843         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2844           // Don't insert two casts if they cannot be eliminated.  We allow two
2845           // casts to be inserted if the sizes are the same.  This could only be
2846           // converting signedness, which is a noop.
2847           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2848               !ValueRequiresCast(Op0, DestTy, TD)) {
2849             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2850             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2851             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2852                              ->getOpcode(), Op0c, Op1c);
2853           }
2854         }
2855         break;
2856       case Instruction::Shl:
2857         // Allow changing the sign of the source operand.  Do not allow changing
2858         // the size of the shift, UNLESS the shift amount is a constant.  We
2859         // mush not change variable sized shifts to a smaller size, because it
2860         // is undefined to shift more bits out than exist in the value.
2861         if (DestBitSize == SrcBitSize ||
2862             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2863           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2864           return new ShiftInst(Instruction::Shl, Op0c, Op1);
2865         }
2866         break;
2867       }
2868     }
2869   
2870   return 0;
2871 }
2872
2873 /// GetSelectFoldableOperands - We want to turn code that looks like this:
2874 ///   %C = or %A, %B
2875 ///   %D = select %cond, %C, %A
2876 /// into:
2877 ///   %C = select %cond, %B, 0
2878 ///   %D = or %A, %C
2879 ///
2880 /// Assuming that the specified instruction is an operand to the select, return
2881 /// a bitmask indicating which operands of this instruction are foldable if they
2882 /// equal the other incoming value of the select.
2883 ///
2884 static unsigned GetSelectFoldableOperands(Instruction *I) {
2885   switch (I->getOpcode()) {
2886   case Instruction::Add:
2887   case Instruction::Mul:
2888   case Instruction::And:
2889   case Instruction::Or:
2890   case Instruction::Xor:
2891     return 3;              // Can fold through either operand.
2892   case Instruction::Sub:   // Can only fold on the amount subtracted.
2893   case Instruction::Shl:   // Can only fold on the shift amount.
2894   case Instruction::Shr:
2895     return 1;           
2896   default:
2897     return 0;              // Cannot fold
2898   }
2899 }
2900
2901 /// GetSelectFoldableConstant - For the same transformation as the previous
2902 /// function, return the identity constant that goes into the select.
2903 static Constant *GetSelectFoldableConstant(Instruction *I) {
2904   switch (I->getOpcode()) {
2905   default: assert(0 && "This cannot happen!"); abort();
2906   case Instruction::Add:
2907   case Instruction::Sub:
2908   case Instruction::Or:
2909   case Instruction::Xor:
2910     return Constant::getNullValue(I->getType());
2911   case Instruction::Shl:
2912   case Instruction::Shr:
2913     return Constant::getNullValue(Type::UByteTy);
2914   case Instruction::And:
2915     return ConstantInt::getAllOnesValue(I->getType());
2916   case Instruction::Mul:
2917     return ConstantInt::get(I->getType(), 1);
2918   }
2919 }
2920
2921 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2922   Value *CondVal = SI.getCondition();
2923   Value *TrueVal = SI.getTrueValue();
2924   Value *FalseVal = SI.getFalseValue();
2925
2926   // select true, X, Y  -> X
2927   // select false, X, Y -> Y
2928   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
2929     if (C == ConstantBool::True)
2930       return ReplaceInstUsesWith(SI, TrueVal);
2931     else {
2932       assert(C == ConstantBool::False);
2933       return ReplaceInstUsesWith(SI, FalseVal);
2934     }
2935
2936   // select C, X, X -> X
2937   if (TrueVal == FalseVal)
2938     return ReplaceInstUsesWith(SI, TrueVal);
2939
2940   if (SI.getType() == Type::BoolTy)
2941     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2942       if (C == ConstantBool::True) {
2943         // Change: A = select B, true, C --> A = or B, C
2944         return BinaryOperator::createOr(CondVal, FalseVal);
2945       } else {
2946         // Change: A = select B, false, C --> A = and !B, C
2947         Value *NotCond =
2948           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2949                                              "not."+CondVal->getName()), SI);
2950         return BinaryOperator::createAnd(NotCond, FalseVal);
2951       }
2952     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2953       if (C == ConstantBool::False) {
2954         // Change: A = select B, C, false --> A = and B, C
2955         return BinaryOperator::createAnd(CondVal, TrueVal);
2956       } else {
2957         // Change: A = select B, C, true --> A = or !B, C
2958         Value *NotCond =
2959           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2960                                              "not."+CondVal->getName()), SI);
2961         return BinaryOperator::createOr(NotCond, TrueVal);
2962       }
2963     }
2964
2965   // Selecting between two integer constants?
2966   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2967     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2968       // select C, 1, 0 -> cast C to int
2969       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2970         return new CastInst(CondVal, SI.getType());
2971       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2972         // select C, 0, 1 -> cast !C to int
2973         Value *NotCond =
2974           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2975                                                "not."+CondVal->getName()), SI);
2976         return new CastInst(NotCond, SI.getType());
2977       }
2978
2979       // If one of the constants is zero (we know they can't both be) and we
2980       // have a setcc instruction with zero, and we have an 'and' with the
2981       // non-constant value, eliminate this whole mess.  This corresponds to
2982       // cases like this: ((X & 27) ? 27 : 0)
2983       if (TrueValC->isNullValue() || FalseValC->isNullValue())
2984         if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2985           if ((IC->getOpcode() == Instruction::SetEQ ||
2986                IC->getOpcode() == Instruction::SetNE) &&
2987               isa<ConstantInt>(IC->getOperand(1)) &&
2988               cast<Constant>(IC->getOperand(1))->isNullValue())
2989             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2990               if (ICA->getOpcode() == Instruction::And &&
2991                   isa<ConstantInt>(ICA->getOperand(1)) && 
2992                   (ICA->getOperand(1) == TrueValC || 
2993                    ICA->getOperand(1) == FalseValC) && 
2994                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2995                 // Okay, now we know that everything is set up, we just don't
2996                 // know whether we have a setne or seteq and whether the true or
2997                 // false val is the zero.
2998                 bool ShouldNotVal = !TrueValC->isNullValue();
2999                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3000                 Value *V = ICA;
3001                 if (ShouldNotVal)
3002                   V = InsertNewInstBefore(BinaryOperator::create(
3003                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
3004                 return ReplaceInstUsesWith(SI, V);
3005               }
3006     }
3007
3008   // See if we are selecting two values based on a comparison of the two values.
3009   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3010     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3011       // Transform (X == Y) ? X : Y  -> Y
3012       if (SCI->getOpcode() == Instruction::SetEQ)
3013         return ReplaceInstUsesWith(SI, FalseVal);
3014       // Transform (X != Y) ? X : Y  -> X
3015       if (SCI->getOpcode() == Instruction::SetNE)
3016         return ReplaceInstUsesWith(SI, TrueVal);
3017       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3018
3019     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3020       // Transform (X == Y) ? Y : X  -> X
3021       if (SCI->getOpcode() == Instruction::SetEQ)
3022         return ReplaceInstUsesWith(SI, FalseVal);
3023       // Transform (X != Y) ? Y : X  -> Y
3024       if (SCI->getOpcode() == Instruction::SetNE)
3025         return ReplaceInstUsesWith(SI, TrueVal);
3026       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3027     }
3028   }
3029   
3030   // See if we can fold the select into one of our operands.
3031   if (SI.getType()->isInteger()) {
3032     // See the comment above GetSelectFoldableOperands for a description of the
3033     // transformation we are doing here.
3034     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3035       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3036           !isa<Constant>(FalseVal))
3037         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3038           unsigned OpToFold = 0;
3039           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3040             OpToFold = 1;
3041           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3042             OpToFold = 2;
3043           }
3044
3045           if (OpToFold) {
3046             Constant *C = GetSelectFoldableConstant(TVI);
3047             std::string Name = TVI->getName(); TVI->setName("");
3048             Instruction *NewSel =
3049               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3050                              Name);
3051             InsertNewInstBefore(NewSel, SI);
3052             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3053               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3054             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3055               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3056             else {
3057               assert(0 && "Unknown instruction!!");
3058             }
3059           }
3060         }
3061
3062     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3063       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3064           !isa<Constant>(TrueVal))
3065         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3066           unsigned OpToFold = 0;
3067           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3068             OpToFold = 1;
3069           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3070             OpToFold = 2;
3071           }
3072
3073           if (OpToFold) {
3074             Constant *C = GetSelectFoldableConstant(FVI);
3075             std::string Name = FVI->getName(); FVI->setName("");
3076             Instruction *NewSel =
3077               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3078                              Name);
3079             InsertNewInstBefore(NewSel, SI);
3080             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3081               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3082             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3083               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3084             else {
3085               assert(0 && "Unknown instruction!!");
3086             }
3087           }
3088         }
3089   }
3090   return 0;
3091 }
3092
3093
3094 // CallInst simplification
3095 //
3096 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
3097   // Intrinsics cannot occur in an invoke, so handle them here instead of in
3098   // visitCallSite.
3099   if (Function *F = CI.getCalledFunction())
3100     switch (F->getIntrinsicID()) {
3101     case Intrinsic::memmove:
3102     case Intrinsic::memcpy:
3103     case Intrinsic::memset:
3104       // memmove/cpy/set of zero bytes is a noop.
3105       if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3106         if (NumBytes->isNullValue())
3107           return EraseInstFromFunction(CI);
3108       }
3109       break;
3110     default:
3111       break;
3112     }
3113
3114   return visitCallSite(&CI);
3115 }
3116
3117 // InvokeInst simplification
3118 //
3119 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3120   return visitCallSite(&II);
3121 }
3122
3123 // visitCallSite - Improvements for call and invoke instructions.
3124 //
3125 Instruction *InstCombiner::visitCallSite(CallSite CS) {
3126   bool Changed = false;
3127
3128   // If the callee is a constexpr cast of a function, attempt to move the cast
3129   // to the arguments of the call/invoke.
3130   if (transformConstExprCastCall(CS)) return 0;
3131
3132   Value *Callee = CS.getCalledValue();
3133   const PointerType *PTy = cast<PointerType>(Callee->getType());
3134   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3135   if (FTy->isVarArg()) {
3136     // See if we can optimize any arguments passed through the varargs area of
3137     // the call.
3138     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3139            E = CS.arg_end(); I != E; ++I)
3140       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3141         // If this cast does not effect the value passed through the varargs
3142         // area, we can eliminate the use of the cast.
3143         Value *Op = CI->getOperand(0);
3144         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3145           *I = Op;
3146           Changed = true;
3147         }
3148       }
3149   }
3150   
3151   return Changed ? CS.getInstruction() : 0;
3152 }
3153
3154 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
3155 // attempt to move the cast to the arguments of the call/invoke.
3156 //
3157 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3158   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3159   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
3160   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
3161     return false;
3162   Function *Callee = cast<Function>(CE->getOperand(0));
3163   Instruction *Caller = CS.getInstruction();
3164
3165   // Okay, this is a cast from a function to a different type.  Unless doing so
3166   // would cause a type conversion of one of our arguments, change this call to
3167   // be a direct call with arguments casted to the appropriate types.
3168   //
3169   const FunctionType *FT = Callee->getFunctionType();
3170   const Type *OldRetTy = Caller->getType();
3171
3172   // Check to see if we are changing the return type...
3173   if (OldRetTy != FT->getReturnType()) {
3174     if (Callee->isExternal() &&
3175         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3176         !Caller->use_empty())
3177       return false;   // Cannot transform this return value...
3178
3179     // If the callsite is an invoke instruction, and the return value is used by
3180     // a PHI node in a successor, we cannot change the return type of the call
3181     // because there is no place to put the cast instruction (without breaking
3182     // the critical edge).  Bail out in this case.
3183     if (!Caller->use_empty())
3184       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3185         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3186              UI != E; ++UI)
3187           if (PHINode *PN = dyn_cast<PHINode>(*UI))
3188             if (PN->getParent() == II->getNormalDest() ||
3189                 PN->getParent() == II->getUnwindDest())
3190               return false;
3191   }
3192
3193   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3194   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3195                                     
3196   CallSite::arg_iterator AI = CS.arg_begin();
3197   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3198     const Type *ParamTy = FT->getParamType(i);
3199     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3200     if (Callee->isExternal() && !isConvertible) return false;    
3201   }
3202
3203   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3204       Callee->isExternal())
3205     return false;   // Do not delete arguments unless we have a function body...
3206
3207   // Okay, we decided that this is a safe thing to do: go ahead and start
3208   // inserting cast instructions as necessary...
3209   std::vector<Value*> Args;
3210   Args.reserve(NumActualArgs);
3211
3212   AI = CS.arg_begin();
3213   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3214     const Type *ParamTy = FT->getParamType(i);
3215     if ((*AI)->getType() == ParamTy) {
3216       Args.push_back(*AI);
3217     } else {
3218       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3219                                          *Caller));
3220     }
3221   }
3222
3223   // If the function takes more arguments than the call was taking, add them
3224   // now...
3225   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3226     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3227
3228   // If we are removing arguments to the function, emit an obnoxious warning...
3229   if (FT->getNumParams() < NumActualArgs)
3230     if (!FT->isVarArg()) {
3231       std::cerr << "WARNING: While resolving call to function '"
3232                 << Callee->getName() << "' arguments were dropped!\n";
3233     } else {
3234       // Add all of the arguments in their promoted form to the arg list...
3235       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3236         const Type *PTy = getPromotedType((*AI)->getType());
3237         if (PTy != (*AI)->getType()) {
3238           // Must promote to pass through va_arg area!
3239           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3240           InsertNewInstBefore(Cast, *Caller);
3241           Args.push_back(Cast);
3242         } else {
3243           Args.push_back(*AI);
3244         }
3245       }
3246     }
3247
3248   if (FT->getReturnType() == Type::VoidTy)
3249     Caller->setName("");   // Void type should not have a name...
3250
3251   Instruction *NC;
3252   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3253     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
3254                         Args, Caller->getName(), Caller);
3255   } else {
3256     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3257   }
3258
3259   // Insert a cast of the return type as necessary...
3260   Value *NV = NC;
3261   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3262     if (NV->getType() != Type::VoidTy) {
3263       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
3264
3265       // If this is an invoke instruction, we should insert it after the first
3266       // non-phi, instruction in the normal successor block.
3267       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3268         BasicBlock::iterator I = II->getNormalDest()->begin();
3269         while (isa<PHINode>(I)) ++I;
3270         InsertNewInstBefore(NC, *I);
3271       } else {
3272         // Otherwise, it's a call, just insert cast right after the call instr
3273         InsertNewInstBefore(NC, *Caller);
3274       }
3275       AddUsersToWorkList(*Caller);
3276     } else {
3277       NV = Constant::getNullValue(Caller->getType());
3278     }
3279   }
3280
3281   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3282     Caller->replaceAllUsesWith(NV);
3283   Caller->getParent()->getInstList().erase(Caller);
3284   removeFromWorkList(Caller);
3285   return true;
3286 }
3287
3288
3289
3290 // PHINode simplification
3291 //
3292 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
3293   if (Value *V = hasConstantValue(&PN))
3294     return ReplaceInstUsesWith(PN, V);
3295
3296   // If the only user of this instruction is a cast instruction, and all of the
3297   // incoming values are constants, change this PHI to merge together the casted
3298   // constants.
3299   if (PN.hasOneUse())
3300     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3301       if (CI->getType() != PN.getType()) {  // noop casts will be folded
3302         bool AllConstant = true;
3303         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3304           if (!isa<Constant>(PN.getIncomingValue(i))) {
3305             AllConstant = false;
3306             break;
3307           }
3308         if (AllConstant) {
3309           // Make a new PHI with all casted values.
3310           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3311           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3312             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3313             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3314                              PN.getIncomingBlock(i));
3315           }
3316
3317           // Update the cast instruction.
3318           CI->setOperand(0, New);
3319           WorkList.push_back(CI);    // revisit the cast instruction to fold.
3320           WorkList.push_back(New);   // Make sure to revisit the new Phi
3321           return &PN;                // PN is now dead!
3322         }
3323       }
3324   return 0;
3325 }
3326
3327 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3328                                       Instruction *InsertPoint,
3329                                       InstCombiner *IC) {
3330   unsigned PS = IC->getTargetData().getPointerSize();
3331   const Type *VTy = V->getType();
3332   Instruction *Cast;
3333   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3334     // We must insert a cast to ensure we sign-extend.
3335     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3336                                              V->getName()), *InsertPoint);
3337   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3338                                  *InsertPoint);
3339 }
3340
3341
3342 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3343   Value *PtrOp = GEP.getOperand(0);
3344   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
3345   // If so, eliminate the noop.
3346   if (GEP.getNumOperands() == 1)
3347     return ReplaceInstUsesWith(GEP, PtrOp);
3348
3349   bool HasZeroPointerIndex = false;
3350   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3351     HasZeroPointerIndex = C->isNullValue();
3352
3353   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
3354     return ReplaceInstUsesWith(GEP, PtrOp);
3355
3356   // Eliminate unneeded casts for indices.
3357   bool MadeChange = false;
3358   gep_type_iterator GTI = gep_type_begin(GEP);
3359   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3360     if (isa<SequentialType>(*GTI)) {
3361       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3362         Value *Src = CI->getOperand(0);
3363         const Type *SrcTy = Src->getType();
3364         const Type *DestTy = CI->getType();
3365         if (Src->getType()->isInteger()) {
3366           if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3367             // We can always eliminate a cast from ulong or long to the other.
3368             // We can always eliminate a cast from uint to int or the other on
3369             // 32-bit pointer platforms.
3370             if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3371               MadeChange = true;
3372               GEP.setOperand(i, Src);
3373             }
3374           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3375                      SrcTy->getPrimitiveSize() == 4) {
3376             // We can always eliminate a cast from int to [u]long.  We can
3377             // eliminate a cast from uint to [u]long iff the target is a 32-bit
3378             // pointer target.
3379             if (SrcTy->isSigned() || 
3380                 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3381               MadeChange = true;
3382               GEP.setOperand(i, Src);
3383             }
3384           }
3385         }
3386       }
3387       // If we are using a wider index than needed for this platform, shrink it
3388       // to what we need.  If the incoming value needs a cast instruction,
3389       // insert it.  This explicit cast can make subsequent optimizations more
3390       // obvious.
3391       Value *Op = GEP.getOperand(i);
3392       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
3393         if (Constant *C = dyn_cast<Constant>(Op)) {
3394           GEP.setOperand(i, ConstantExpr::getCast(C,
3395                                      TD->getIntPtrType()->getSignedVersion()));
3396           MadeChange = true;
3397         } else {
3398           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3399                                                 Op->getName()), GEP);
3400           GEP.setOperand(i, Op);
3401           MadeChange = true;
3402         }
3403
3404       // If this is a constant idx, make sure to canonicalize it to be a signed
3405       // operand, otherwise CSE and other optimizations are pessimized.
3406       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3407         GEP.setOperand(i, ConstantExpr::getCast(CUI,
3408                                           CUI->getType()->getSignedVersion()));
3409         MadeChange = true;
3410       }
3411     }
3412   if (MadeChange) return &GEP;
3413
3414   // Combine Indices - If the source pointer to this getelementptr instruction
3415   // is a getelementptr instruction, combine the indices of the two
3416   // getelementptr instructions into a single instruction.
3417   //
3418   std::vector<Value*> SrcGEPOperands;
3419   if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
3420     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
3421   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3422     if (CE->getOpcode() == Instruction::GetElementPtr)
3423       SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3424   }
3425
3426   if (!SrcGEPOperands.empty()) {
3427     // Note that if our source is a gep chain itself that we wait for that
3428     // chain to be resolved before we perform this transformation.  This
3429     // avoids us creating a TON of code in some cases.
3430     //
3431     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3432         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3433       return 0;   // Wait until our source is folded to completion.
3434
3435     std::vector<Value *> Indices;
3436
3437     // Find out whether the last index in the source GEP is a sequential idx.
3438     bool EndsWithSequential = false;
3439     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3440            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
3441       EndsWithSequential = !isa<StructType>(*I);
3442   
3443     // Can we combine the two pointer arithmetics offsets?
3444     if (EndsWithSequential) {
3445       // Replace: gep (gep %P, long B), long A, ...
3446       // With:    T = long A+B; gep %P, T, ...
3447       //
3448       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
3449       if (SO1 == Constant::getNullValue(SO1->getType())) {
3450         Sum = GO1;
3451       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3452         Sum = SO1;
3453       } else {
3454         // If they aren't the same type, convert both to an integer of the
3455         // target's pointer size.
3456         if (SO1->getType() != GO1->getType()) {
3457           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3458             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3459           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3460             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3461           } else {
3462             unsigned PS = TD->getPointerSize();
3463             Instruction *Cast;
3464             if (SO1->getType()->getPrimitiveSize() == PS) {
3465               // Convert GO1 to SO1's type.
3466               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3467
3468             } else if (GO1->getType()->getPrimitiveSize() == PS) {
3469               // Convert SO1 to GO1's type.
3470               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3471             } else {
3472               const Type *PT = TD->getIntPtrType();
3473               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3474               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3475             }
3476           }
3477         }
3478         if (isa<Constant>(SO1) && isa<Constant>(GO1))
3479           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3480         else {
3481           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3482           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
3483         }
3484       }
3485
3486       // Recycle the GEP we already have if possible.
3487       if (SrcGEPOperands.size() == 2) {
3488         GEP.setOperand(0, SrcGEPOperands[0]);
3489         GEP.setOperand(1, Sum);
3490         return &GEP;
3491       } else {
3492         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3493                        SrcGEPOperands.end()-1);
3494         Indices.push_back(Sum);
3495         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3496       }
3497     } else if (isa<Constant>(*GEP.idx_begin()) && 
3498                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
3499                SrcGEPOperands.size() != 1) { 
3500       // Otherwise we can do the fold if the first index of the GEP is a zero
3501       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3502                      SrcGEPOperands.end());
3503       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3504     }
3505
3506     if (!Indices.empty())
3507       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
3508
3509   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
3510     // GEP of global variable.  If all of the indices for this GEP are
3511     // constants, we can promote this to a constexpr instead of an instruction.
3512
3513     // Scan for nonconstants...
3514     std::vector<Constant*> Indices;
3515     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3516     for (; I != E && isa<Constant>(*I); ++I)
3517       Indices.push_back(cast<Constant>(*I));
3518
3519     if (I == E) {  // If they are all constants...
3520       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
3521
3522       // Replace all uses of the GEP with the new constexpr...
3523       return ReplaceInstUsesWith(GEP, CE);
3524     }
3525   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3526     if (CE->getOpcode() == Instruction::Cast) {
3527       if (HasZeroPointerIndex) {
3528         // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3529         // into     : GEP [10 x ubyte]* X, long 0, ...
3530         //
3531         // This occurs when the program declares an array extern like "int X[];"
3532         //
3533         Constant *X = CE->getOperand(0);
3534         const PointerType *CPTy = cast<PointerType>(CE->getType());
3535         if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3536           if (const ArrayType *XATy =
3537               dyn_cast<ArrayType>(XTy->getElementType()))
3538             if (const ArrayType *CATy =
3539                 dyn_cast<ArrayType>(CPTy->getElementType()))
3540               if (CATy->getElementType() == XATy->getElementType()) {
3541                 // At this point, we know that the cast source type is a pointer
3542                 // to an array of the same type as the destination pointer
3543                 // array.  Because the array type is never stepped over (there
3544                 // is a leading zero) we can fold the cast into this GEP.
3545                 GEP.setOperand(0, X);
3546                 return &GEP;
3547               }
3548       }
3549     }
3550   }
3551
3552   return 0;
3553 }
3554
3555 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3556   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3557   if (AI.isArrayAllocation())    // Check C != 1
3558     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3559       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
3560       AllocationInst *New = 0;
3561
3562       // Create and insert the replacement instruction...
3563       if (isa<MallocInst>(AI))
3564         New = new MallocInst(NewTy, 0, AI.getName());
3565       else {
3566         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
3567         New = new AllocaInst(NewTy, 0, AI.getName());
3568       }
3569
3570       InsertNewInstBefore(New, AI);
3571       
3572       // Scan to the end of the allocation instructions, to skip over a block of
3573       // allocas if possible...
3574       //
3575       BasicBlock::iterator It = New;
3576       while (isa<AllocationInst>(*It)) ++It;
3577
3578       // Now that I is pointing to the first non-allocation-inst in the block,
3579       // insert our getelementptr instruction...
3580       //
3581       std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
3582       Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3583
3584       // Now make everything use the getelementptr instead of the original
3585       // allocation.
3586       return ReplaceInstUsesWith(AI, V);
3587     }
3588
3589   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3590   // Note that we only do this for alloca's, because malloc should allocate and
3591   // return a unique pointer, even for a zero byte allocation.
3592   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() && 
3593       TD->getTypeSize(AI.getAllocatedType()) == 0)
3594     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3595
3596   return 0;
3597 }
3598
3599 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3600   Value *Op = FI.getOperand(0);
3601
3602   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3603   if (CastInst *CI = dyn_cast<CastInst>(Op))
3604     if (isa<PointerType>(CI->getOperand(0)->getType())) {
3605       FI.setOperand(0, CI->getOperand(0));
3606       return &FI;
3607     }
3608
3609   // If we have 'free null' delete the instruction.  This can happen in stl code
3610   // when lots of inlining happens.
3611   if (isa<ConstantPointerNull>(Op))
3612     return EraseInstFromFunction(FI);
3613
3614   return 0;
3615 }
3616
3617
3618 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3619 /// constantexpr, return the constant value being addressed by the constant
3620 /// expression, or null if something is funny.
3621 ///
3622 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
3623   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
3624     return 0;  // Do not allow stepping over the value!
3625
3626   // Loop over all of the operands, tracking down which value we are
3627   // addressing...
3628   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3629   for (++I; I != E; ++I)
3630     if (const StructType *STy = dyn_cast<StructType>(*I)) {
3631       ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3632       assert(CU->getValue() < STy->getNumElements() &&
3633              "Struct index out of range!");
3634       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
3635         C = CS->getOperand(CU->getValue());
3636       } else if (isa<ConstantAggregateZero>(C)) {
3637         C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3638       } else {
3639         return 0;
3640       }
3641     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3642       const ArrayType *ATy = cast<ArrayType>(*I);
3643       if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3644       if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
3645         C = CA->getOperand(CI->getRawValue());
3646       else if (isa<ConstantAggregateZero>(C))
3647         C = Constant::getNullValue(ATy->getElementType());
3648       else
3649         return 0;
3650     } else {
3651       return 0;
3652     }
3653   return C;
3654 }
3655
3656 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3657   User *CI = cast<User>(LI.getOperand(0));
3658
3659   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3660   if (const PointerType *SrcTy =
3661       dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3662     const Type *SrcPTy = SrcTy->getElementType();
3663     if (SrcPTy->isSized() && DestPTy->isSized() &&
3664         IC.getTargetData().getTypeSize(SrcPTy) == 
3665             IC.getTargetData().getTypeSize(DestPTy) &&
3666         (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3667         (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3668       // Okay, we are casting from one integer or pointer type to another of
3669       // the same size.  Instead of casting the pointer before the load, cast
3670       // the result of the loaded value.
3671       Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
3672                                                            CI->getName(),
3673                                                            LI.isVolatile()),LI);
3674       // Now cast the result of the load.
3675       return new CastInst(NewLoad, LI.getType());
3676     }
3677   }
3678   return 0;
3679 }
3680
3681 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
3682 /// from this value cannot trap.  If it is not obviously safe to load from the
3683 /// specified pointer, we do a quick local scan of the basic block containing
3684 /// ScanFrom, to determine if the address is already accessed.
3685 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3686   // If it is an alloca or global variable, it is always safe to load from.
3687   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3688
3689   // Otherwise, be a little bit agressive by scanning the local block where we
3690   // want to check to see if the pointer is already being loaded or stored
3691   // from/to.  If so, the previous load or store would have already trapped,
3692   // so there is no harm doing an extra load (also, CSE will later eliminate
3693   // the load entirely).
3694   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3695
3696   while (BBI != E) {
3697     --BBI;
3698
3699     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3700       if (LI->getOperand(0) == V) return true;
3701     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3702       if (SI->getOperand(1) == V) return true;
3703     
3704   }
3705   return false;
3706 }
3707
3708 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3709   Value *Op = LI.getOperand(0);
3710
3711   if (Constant *C = dyn_cast<Constant>(Op))
3712     if (C->isNullValue() && !LI.isVolatile())  // load null -> 0
3713       return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
3714
3715   // Instcombine load (constant global) into the value loaded...
3716   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3717     if (GV->isConstant() && !GV->isExternal())
3718       return ReplaceInstUsesWith(LI, GV->getInitializer());
3719
3720   // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3721   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3722     if (CE->getOpcode() == Instruction::GetElementPtr) {
3723       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3724         if (GV->isConstant() && !GV->isExternal())
3725           if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3726             return ReplaceInstUsesWith(LI, V);
3727     } else if (CE->getOpcode() == Instruction::Cast) {
3728       if (Instruction *Res = InstCombineLoadCast(*this, LI))
3729         return Res;
3730     }
3731
3732   // load (cast X) --> cast (load X) iff safe
3733   if (CastInst *CI = dyn_cast<CastInst>(Op))
3734     if (Instruction *Res = InstCombineLoadCast(*this, LI))
3735       return Res;
3736
3737   if (!LI.isVolatile() && Op->hasOneUse()) {
3738     // Change select and PHI nodes to select values instead of addresses: this
3739     // helps alias analysis out a lot, allows many others simplifications, and
3740     // exposes redundancy in the code.
3741     //
3742     // Note that we cannot do the transformation unless we know that the
3743     // introduced loads cannot trap!  Something like this is valid as long as
3744     // the condition is always false: load (select bool %C, int* null, int* %G),
3745     // but it would not be valid if we transformed it to load from null
3746     // unconditionally.
3747     //
3748     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3749       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
3750       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3751           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
3752         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
3753                                      SI->getOperand(1)->getName()+".val"), LI);
3754         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
3755                                      SI->getOperand(2)->getName()+".val"), LI);
3756         return new SelectInst(SI->getCondition(), V1, V2);
3757       }
3758
3759       // load (select (cond, null, P)) -> load P
3760       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3761         if (C->isNullValue()) {
3762           LI.setOperand(0, SI->getOperand(2));
3763           return &LI;
3764         }
3765
3766       // load (select (cond, P, null)) -> load P
3767       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3768         if (C->isNullValue()) {
3769           LI.setOperand(0, SI->getOperand(1));
3770           return &LI;
3771         }
3772
3773     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3774       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
3775       bool Safe = PN->getParent() == LI.getParent();
3776
3777       // Scan all of the instructions between the PHI and the load to make
3778       // sure there are no instructions that might possibly alter the value
3779       // loaded from the PHI.
3780       if (Safe) {
3781         BasicBlock::iterator I = &LI;
3782         for (--I; !isa<PHINode>(I); --I)
3783           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3784             Safe = false;
3785             break;
3786           }
3787       }
3788
3789       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
3790         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
3791                                     PN->getIncomingBlock(i)->getTerminator()))
3792           Safe = false;
3793
3794       if (Safe) {
3795         // Create the PHI.
3796         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3797         InsertNewInstBefore(NewPN, *PN);
3798         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
3799
3800         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3801           BasicBlock *BB = PN->getIncomingBlock(i);
3802           Value *&TheLoad = LoadMap[BB];
3803           if (TheLoad == 0) {
3804             Value *InVal = PN->getIncomingValue(i);
3805             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3806                                                        InVal->getName()+".val"),
3807                                           *BB->getTerminator());
3808           }
3809           NewPN->addIncoming(TheLoad, BB);
3810         }
3811         return ReplaceInstUsesWith(LI, NewPN);
3812       }
3813     }
3814   }
3815   return 0;
3816 }
3817
3818
3819 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3820   // Change br (not X), label True, label False to: br X, label False, True
3821   Value *X;
3822   BasicBlock *TrueDest;
3823   BasicBlock *FalseDest;
3824   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3825       !isa<Constant>(X)) {
3826     // Swap Destinations and condition...
3827     BI.setCondition(X);
3828     BI.setSuccessor(0, FalseDest);
3829     BI.setSuccessor(1, TrueDest);
3830     return &BI;
3831   }
3832
3833   // Cannonicalize setne -> seteq
3834   Instruction::BinaryOps Op; Value *Y;
3835   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3836                       TrueDest, FalseDest)))
3837     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3838          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3839       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3840       std::string Name = I->getName(); I->setName("");
3841       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3842       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
3843       // Swap Destinations and condition...
3844       BI.setCondition(NewSCC);
3845       BI.setSuccessor(0, FalseDest);
3846       BI.setSuccessor(1, TrueDest);
3847       removeFromWorkList(I);
3848       I->getParent()->getInstList().erase(I);
3849       WorkList.push_back(cast<Instruction>(NewSCC));
3850       return &BI;
3851     }
3852   
3853   return 0;
3854 }
3855
3856 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3857   Value *Cond = SI.getCondition();
3858   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3859     if (I->getOpcode() == Instruction::Add)
3860       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3861         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3862         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3863           SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3864                                                 AddRHS));
3865         SI.setOperand(0, I->getOperand(0));
3866         WorkList.push_back(I);
3867         return &SI;
3868       }
3869   }
3870   return 0;
3871 }
3872
3873
3874 void InstCombiner::removeFromWorkList(Instruction *I) {
3875   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3876                  WorkList.end());
3877 }
3878
3879 bool InstCombiner::runOnFunction(Function &F) {
3880   bool Changed = false;
3881   TD = &getAnalysis<TargetData>();
3882
3883   for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3884     WorkList.push_back(&*i);
3885
3886
3887   while (!WorkList.empty()) {
3888     Instruction *I = WorkList.back();  // Get an instruction from the worklist
3889     WorkList.pop_back();
3890
3891     // Check to see if we can DCE or ConstantPropagate the instruction...
3892     // Check to see if we can DIE the instruction...
3893     if (isInstructionTriviallyDead(I)) {
3894       // Add operands to the worklist...
3895       if (I->getNumOperands() < 4)
3896         AddUsesToWorkList(*I);
3897       ++NumDeadInst;
3898
3899       I->getParent()->getInstList().erase(I);
3900       removeFromWorkList(I);
3901       continue;
3902     }
3903
3904     // Instruction isn't dead, see if we can constant propagate it...
3905     if (Constant *C = ConstantFoldInstruction(I)) {
3906       // Add operands to the worklist...
3907       AddUsesToWorkList(*I);
3908       ReplaceInstUsesWith(*I, C);
3909
3910       ++NumConstProp;
3911       I->getParent()->getInstList().erase(I);
3912       removeFromWorkList(I);
3913       continue;
3914     }
3915
3916     // Now that we have an instruction, try combining it to simplify it...
3917     if (Instruction *Result = visit(*I)) {
3918       ++NumCombined;
3919       // Should we replace the old instruction with a new one?
3920       if (Result != I) {
3921         DEBUG(std::cerr << "IC: Old = " << *I
3922                         << "    New = " << *Result);
3923
3924         // Everything uses the new instruction now.
3925         I->replaceAllUsesWith(Result);
3926
3927         // Push the new instruction and any users onto the worklist.
3928         WorkList.push_back(Result);
3929         AddUsersToWorkList(*Result);
3930
3931         // Move the name to the new instruction first...
3932         std::string OldName = I->getName(); I->setName("");
3933         Result->setName(OldName);
3934
3935         // Insert the new instruction into the basic block...
3936         BasicBlock *InstParent = I->getParent();
3937         InstParent->getInstList().insert(I, Result);
3938
3939         // Make sure that we reprocess all operands now that we reduced their
3940         // use counts.
3941         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3942           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3943             WorkList.push_back(OpI);
3944
3945         // Instructions can end up on the worklist more than once.  Make sure
3946         // we do not process an instruction that has been deleted.
3947         removeFromWorkList(I);
3948
3949         // Erase the old instruction.
3950         InstParent->getInstList().erase(I);
3951       } else {
3952         DEBUG(std::cerr << "IC: MOD = " << *I);
3953
3954         // If the instruction was modified, it's possible that it is now dead.
3955         // if so, remove it.
3956         if (isInstructionTriviallyDead(I)) {
3957           // Make sure we process all operands now that we are reducing their
3958           // use counts.
3959           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3960             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3961               WorkList.push_back(OpI);
3962           
3963           // Instructions may end up in the worklist more than once.  Erase all
3964           // occurrances of this instruction.
3965           removeFromWorkList(I);
3966           I->getParent()->getInstList().erase(I);
3967         } else {
3968           WorkList.push_back(Result);
3969           AddUsersToWorkList(*Result);
3970         }
3971       }
3972       Changed = true;
3973     }
3974   }
3975
3976   return Changed;
3977 }
3978
3979 FunctionPass *llvm::createInstructionCombiningPass() {
3980   return new InstCombiner();
3981 }
3982