blob: 4d96cbfcceab6124937b0d80c16ea38233cc2e87 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Chris Lattner2cd91962003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 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.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner221d6882002-02-12 21:07:25 +000048#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000056
Chris Lattnerdd841ae2002-04-18 17:39:14 +000057namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000058 Statistic<> NumCombined ("instcombine", "Number of insts combined");
59 Statistic<> NumConstProp("instcombine", "Number of constant folds");
60 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000061 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000062
Chris Lattnerf57b8452002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068
Chris Lattner7bcc0e72004-02-28 05:22:00 +000069 /// 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) {
Chris Lattner7e708292002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner7bcc0e72004-02-28 05:22:00 +000079 /// 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
Chris Lattner62b14df2002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090 public:
Chris Lattner7e708292002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092
Chris Lattner97e52e42002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000096 }
97
Chris Lattner28977af2004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000106 //
Chris Lattner7e708292002-06-25 16:13:24 +0000107 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);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000115 Instruction *visitSetCondInst(SetCondInst &I);
116 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
117
Chris Lattner574da9b2005-01-13 20:14:25 +0000118 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
119 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000120 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000121 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000122 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
123 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000124 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000125 Instruction *visitCallInst(CallInst &CI);
126 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000127 Instruction *visitPHINode(PHINode &PN);
128 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000129 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000130 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000131 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000132 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000133 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000134 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000135
136 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000137 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000138
Chris Lattner9fe38862003-06-19 17:00:31 +0000139 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000140 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000141 bool transformConstExprCastCall(CallSite CS);
142
Chris Lattner28977af2004-04-05 01:30:19 +0000143 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000144 // InsertNewInstBefore - insert an instruction New before instruction Old
145 // in the program. Add the new instruction to the worklist.
146 //
Chris Lattner955f3312004-09-28 21:48:02 +0000147 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000148 assert(New && New->getParent() == 0 &&
149 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000150 BasicBlock *BB = Old.getParent();
151 BB->getInstList().insert(&Old, New); // Insert inst
152 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000153 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000154 }
155
Chris Lattner0c967662004-09-24 15:21:34 +0000156 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
157 /// This also adds the cast to the worklist. Finally, this returns the
158 /// cast.
159 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
160 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000161
Chris Lattner0c967662004-09-24 15:21:34 +0000162 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
163 WorkList.push_back(C);
164 return C;
165 }
166
Chris Lattner8b170942002-08-09 23:47:40 +0000167 // ReplaceInstUsesWith - This method is to be used when an instruction is
168 // found to be dead, replacable with another preexisting expression. Here
169 // we add all uses of I to the worklist, replace all uses of I with the new
170 // value, then return I, so that the inst combiner will know that I was
171 // modified.
172 //
173 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000174 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000175 if (&I != V) {
176 I.replaceAllUsesWith(V);
177 return &I;
178 } else {
179 // If we are replacing the instruction with itself, this must be in a
180 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000181 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000182 return &I;
183 }
Chris Lattner8b170942002-08-09 23:47:40 +0000184 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000185
186 // EraseInstFromFunction - When dealing with an instruction that has side
187 // effects or produces a void value, we can't rely on DCE to delete the
188 // instruction. Instead, visit methods should return the value returned by
189 // this function.
190 Instruction *EraseInstFromFunction(Instruction &I) {
191 assert(I.use_empty() && "Cannot erase instruction that is used!");
192 AddUsesToWorkList(I);
193 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000194 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000195 return 0; // Don't do anything with FI
196 }
197
198
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000199 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000200 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
201 /// InsertBefore instruction. This is specialized a bit to avoid inserting
202 /// casts that are known to not do anything...
203 ///
204 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
205 Instruction *InsertBefore);
206
Chris Lattnerc8802d22003-03-11 00:12:48 +0000207 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000208 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000209 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000210
Chris Lattner4e998b22004-09-29 05:07:12 +0000211
212 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
213 // PHI node as operand #0, see if we can fold the instruction into the PHI
214 // (which is only possible if all operands to the PHI are constants).
215 Instruction *FoldOpIntoPhi(Instruction &I);
216
Chris Lattnerbac32862004-11-14 19:13:23 +0000217 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
218 // operator and they all are only used by the PHI, PHI together their
219 // inputs, and do the operation once, to the result of the PHI.
220 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
221
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000222 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
223 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnera96879a2004-09-29 17:40:11 +0000224
225 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
226 bool Inside, Instruction &IB);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000227 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000228
Chris Lattnera6275cc2002-07-26 21:12:46 +0000229 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000230}
231
Chris Lattner4f98c562003-03-10 21:43:22 +0000232// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000233// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000234static unsigned getComplexity(Value *V) {
235 if (isa<Instruction>(V)) {
236 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000237 return 3;
238 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000239 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000240 if (isa<Argument>(V)) return 3;
241 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000242}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000243
Chris Lattnerc8802d22003-03-11 00:12:48 +0000244// isOnlyUse - Return true if this instruction will be deleted if we stop using
245// it.
246static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000247 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000248}
249
Chris Lattner4cb170c2004-02-23 06:38:22 +0000250// getPromotedType - Return the specified type promoted as it would be to pass
251// though a va_arg area...
252static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000253 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000254 case Type::SByteTyID:
255 case Type::ShortTyID: return Type::IntTy;
256 case Type::UByteTyID:
257 case Type::UShortTyID: return Type::UIntTy;
258 case Type::FloatTyID: return Type::DoubleTy;
259 default: return Ty;
260 }
261}
262
Chris Lattner4f98c562003-03-10 21:43:22 +0000263// SimplifyCommutative - This performs a few simplifications for commutative
264// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000265//
Chris Lattner4f98c562003-03-10 21:43:22 +0000266// 1. Order operands such that they are listed from right (least complex) to
267// left (most complex). This puts constants before unary operators before
268// binary operators.
269//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000270// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
271// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000272//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000273bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000274 bool Changed = false;
275 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
276 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000277
Chris Lattner4f98c562003-03-10 21:43:22 +0000278 if (!I.isAssociative()) return Changed;
279 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000280 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
281 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
282 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000283 Constant *Folded = ConstantExpr::get(I.getOpcode(),
284 cast<Constant>(I.getOperand(1)),
285 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000286 I.setOperand(0, Op->getOperand(0));
287 I.setOperand(1, Folded);
288 return true;
289 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
290 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
291 isOnlyUse(Op) && isOnlyUse(Op1)) {
292 Constant *C1 = cast<Constant>(Op->getOperand(1));
293 Constant *C2 = cast<Constant>(Op1->getOperand(1));
294
295 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000296 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000297 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
298 Op1->getOperand(0),
299 Op1->getName(), &I);
300 WorkList.push_back(New);
301 I.setOperand(0, New);
302 I.setOperand(1, Folded);
303 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000304 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000305 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000306 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000307}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000308
Chris Lattner8d969642003-03-10 23:06:50 +0000309// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
310// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000311//
Chris Lattner8d969642003-03-10 23:06:50 +0000312static inline Value *dyn_castNegVal(Value *V) {
313 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000314 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000315
Chris Lattner0ce85802004-12-14 20:08:06 +0000316 // Constants can be considered to be negated values if they can be folded.
317 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
318 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000319 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000320}
321
Chris Lattner8d969642003-03-10 23:06:50 +0000322static inline Value *dyn_castNotVal(Value *V) {
323 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000324 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000325
326 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000327 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000328 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000329 return 0;
330}
331
Chris Lattnerc8802d22003-03-11 00:12:48 +0000332// dyn_castFoldableMul - If this value is a multiply that can be folded into
333// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000334// non-constant operand of the multiply, and set CST to point to the multiplier.
335// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000336//
Chris Lattner50af16a2004-11-13 19:50:12 +0000337static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000338 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000339 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000340 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000341 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000342 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000343 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000344 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000345 // The multiplier is really 1 << CST.
346 Constant *One = ConstantInt::get(V->getType(), 1);
347 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
348 return I->getOperand(0);
349 }
350 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000351 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000352}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000353
Chris Lattner574da9b2005-01-13 20:14:25 +0000354/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
355/// expression, return it.
356static User *dyn_castGetElementPtr(Value *V) {
357 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
358 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
359 if (CE->getOpcode() == Instruction::GetElementPtr)
360 return cast<User>(V);
361 return false;
362}
363
Chris Lattnera2881962003-02-18 19:28:33 +0000364// Log2 - Calculate the log base 2 for the specified value if it is exactly a
365// power of 2.
366static unsigned Log2(uint64_t Val) {
367 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
368 unsigned Count = 0;
369 while (Val != 1) {
370 if (Val & 1) return 0; // Multiple bits set?
371 Val >>= 1;
372 ++Count;
373 }
374 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000375}
376
Chris Lattner955f3312004-09-28 21:48:02 +0000377// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000378static ConstantInt *AddOne(ConstantInt *C) {
379 return cast<ConstantInt>(ConstantExpr::getAdd(C,
380 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000381}
Chris Lattnera96879a2004-09-29 17:40:11 +0000382static ConstantInt *SubOne(ConstantInt *C) {
383 return cast<ConstantInt>(ConstantExpr::getSub(C,
384 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000385}
386
387// isTrueWhenEqual - Return true if the specified setcondinst instruction is
388// true when both operands are equal...
389//
390static bool isTrueWhenEqual(Instruction &I) {
391 return I.getOpcode() == Instruction::SetEQ ||
392 I.getOpcode() == Instruction::SetGE ||
393 I.getOpcode() == Instruction::SetLE;
394}
Chris Lattner564a7272003-08-13 19:01:45 +0000395
396/// AssociativeOpt - Perform an optimization on an associative operator. This
397/// function is designed to check a chain of associative operators for a
398/// potential to apply a certain optimization. Since the optimization may be
399/// applicable if the expression was reassociated, this checks the chain, then
400/// reassociates the expression as necessary to expose the optimization
401/// opportunity. This makes use of a special Functor, which must define
402/// 'shouldApply' and 'apply' methods.
403///
404template<typename Functor>
405Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
406 unsigned Opcode = Root.getOpcode();
407 Value *LHS = Root.getOperand(0);
408
409 // Quick check, see if the immediate LHS matches...
410 if (F.shouldApply(LHS))
411 return F.apply(Root);
412
413 // Otherwise, if the LHS is not of the same opcode as the root, return.
414 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000415 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000416 // Should we apply this transform to the RHS?
417 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
418
419 // If not to the RHS, check to see if we should apply to the LHS...
420 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
421 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
422 ShouldApply = true;
423 }
424
425 // If the functor wants to apply the optimization to the RHS of LHSI,
426 // reassociate the expression from ((? op A) op B) to (? op (A op B))
427 if (ShouldApply) {
428 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000429
Chris Lattner564a7272003-08-13 19:01:45 +0000430 // Now all of the instructions are in the current basic block, go ahead
431 // and perform the reassociation.
432 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
433
434 // First move the selected RHS to the LHS of the root...
435 Root.setOperand(0, LHSI->getOperand(1));
436
437 // Make what used to be the LHS of the root be the user of the root...
438 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000439 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000440 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
441 return 0;
442 }
Chris Lattner65725312004-04-16 18:08:07 +0000443 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000444 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000445 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
446 BasicBlock::iterator ARI = &Root; ++ARI;
447 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
448 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000449
450 // Now propagate the ExtraOperand down the chain of instructions until we
451 // get to LHSI.
452 while (TmpLHSI != LHSI) {
453 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000454 // Move the instruction to immediately before the chain we are
455 // constructing to avoid breaking dominance properties.
456 NextLHSI->getParent()->getInstList().remove(NextLHSI);
457 BB->getInstList().insert(ARI, NextLHSI);
458 ARI = NextLHSI;
459
Chris Lattner564a7272003-08-13 19:01:45 +0000460 Value *NextOp = NextLHSI->getOperand(1);
461 NextLHSI->setOperand(1, ExtraOperand);
462 TmpLHSI = NextLHSI;
463 ExtraOperand = NextOp;
464 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000465
Chris Lattner564a7272003-08-13 19:01:45 +0000466 // Now that the instructions are reassociated, have the functor perform
467 // the transformation...
468 return F.apply(Root);
469 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000470
Chris Lattner564a7272003-08-13 19:01:45 +0000471 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
472 }
473 return 0;
474}
475
476
477// AddRHS - Implements: X + X --> X << 1
478struct AddRHS {
479 Value *RHS;
480 AddRHS(Value *rhs) : RHS(rhs) {}
481 bool shouldApply(Value *LHS) const { return LHS == RHS; }
482 Instruction *apply(BinaryOperator &Add) const {
483 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
484 ConstantInt::get(Type::UByteTy, 1));
485 }
486};
487
488// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
489// iff C1&C2 == 0
490struct AddMaskingAnd {
491 Constant *C2;
492 AddMaskingAnd(Constant *c) : C2(c) {}
493 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000494 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +0000495 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000496 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000497 }
498 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000499 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000500 }
501};
502
Chris Lattner6e7ba452005-01-01 16:22:27 +0000503static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000504 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000505 if (isa<CastInst>(I)) {
506 if (Constant *SOC = dyn_cast<Constant>(SO))
507 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +0000508
Chris Lattner6e7ba452005-01-01 16:22:27 +0000509 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
510 SO->getName() + ".cast"), I);
511 }
512
Chris Lattner2eefe512004-04-09 19:05:30 +0000513 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000514 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
515 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000516
Chris Lattner2eefe512004-04-09 19:05:30 +0000517 if (Constant *SOC = dyn_cast<Constant>(SO)) {
518 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +0000519 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
520 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000521 }
522
523 Value *Op0 = SO, *Op1 = ConstOperand;
524 if (!ConstIsRHS)
525 std::swap(Op0, Op1);
526 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +0000527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
528 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
529 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
530 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +0000531 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000532 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000533 abort();
534 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000535 return IC->InsertNewInstBefore(New, I);
536}
537
538// FoldOpIntoSelect - Given an instruction with a select as one operand and a
539// constant as the other operand, try to fold the binary operator into the
540// select arguments. This also works for Cast instructions, which obviously do
541// not have a second operand.
542static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
543 InstCombiner *IC) {
544 // Don't modify shared select instructions
545 if (!SI->hasOneUse()) return 0;
546 Value *TV = SI->getOperand(1);
547 Value *FV = SI->getOperand(2);
548
549 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000550 // Bool selects with constant operands can be folded to logical ops.
551 if (SI->getType() == Type::BoolTy) return 0;
552
Chris Lattner6e7ba452005-01-01 16:22:27 +0000553 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
554 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
555
556 return new SelectInst(SI->getCondition(), SelectTrueVal,
557 SelectFalseVal);
558 }
559 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000560}
561
Chris Lattner4e998b22004-09-29 05:07:12 +0000562
563/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
564/// node as operand #0, see if we can fold the instruction into the PHI (which
565/// is only possible if all operands to the PHI are constants).
566Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
567 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000568 unsigned NumPHIValues = PN->getNumIncomingValues();
569 if (!PN->hasOneUse() || NumPHIValues == 0 ||
570 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000571
572 // Check to see if all of the operands of the PHI are constants. If not, we
573 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000574 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000575 if (!isa<Constant>(PN->getIncomingValue(i)))
576 return 0;
577
578 // Okay, we can do the transformation: create the new PHI node.
579 PHINode *NewPN = new PHINode(I.getType(), I.getName());
580 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +0000581 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +0000582 InsertNewInstBefore(NewPN, *PN);
583
584 // Next, add all of the operands to the PHI.
585 if (I.getNumOperands() == 2) {
586 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000587 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000588 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
589 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
590 PN->getIncomingBlock(i));
591 }
592 } else {
593 assert(isa<CastInst>(I) && "Unary op should be a cast!");
594 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000595 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000596 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
597 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
598 PN->getIncomingBlock(i));
599 }
600 }
601 return ReplaceInstUsesWith(I, NewPN);
602}
603
Chris Lattner7e708292002-06-25 16:13:24 +0000604Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000605 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000606 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000607
Chris Lattner66331a42004-04-10 22:01:55 +0000608 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000609 // X + undef -> undef
610 if (isa<UndefValue>(RHS))
611 return ReplaceInstUsesWith(I, RHS);
612
Chris Lattner66331a42004-04-10 22:01:55 +0000613 // X + 0 --> X
614 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
615 RHSC->isNullValue())
616 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +0000617
Chris Lattner66331a42004-04-10 22:01:55 +0000618 // X + (signbit) --> X ^ signbit
619 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000620 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner66331a42004-04-10 22:01:55 +0000621 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattnerf1580922004-11-05 04:45:43 +0000622 if (Val == (1ULL << (NumBits-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000623 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000624 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000625
626 if (isa<PHINode>(LHS))
627 if (Instruction *NV = FoldOpIntoPhi(I))
628 return NV;
Chris Lattner66331a42004-04-10 22:01:55 +0000629 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000630
Chris Lattner564a7272003-08-13 19:01:45 +0000631 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000632 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000633 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000634
635 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
636 if (RHSI->getOpcode() == Instruction::Sub)
637 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
638 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
639 }
640 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
641 if (LHSI->getOpcode() == Instruction::Sub)
642 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
643 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
644 }
Robert Bocchino71698282004-07-27 21:02:21 +0000645 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000646
Chris Lattner5c4afb92002-05-08 22:46:53 +0000647 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000648 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000649 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000650
651 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000652 if (!isa<Constant>(RHS))
653 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000654 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000655
Misha Brukmanfd939082005-04-21 23:48:37 +0000656
Chris Lattner50af16a2004-11-13 19:50:12 +0000657 ConstantInt *C2;
658 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
659 if (X == RHS) // X*C + X --> X * (C+1)
660 return BinaryOperator::createMul(RHS, AddOne(C2));
661
662 // X*C1 + X*C2 --> X * (C1+C2)
663 ConstantInt *C1;
664 if (X == dyn_castFoldableMul(RHS, C1))
665 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000666 }
667
668 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000669 if (dyn_castFoldableMul(RHS, C2) == LHS)
670 return BinaryOperator::createMul(LHS, AddOne(C2));
671
Chris Lattnerad3448c2003-02-18 19:57:07 +0000672
Chris Lattner564a7272003-08-13 19:01:45 +0000673 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000674 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000675 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000676
Chris Lattner6b032052003-10-02 15:11:26 +0000677 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000678 Value *X;
679 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
680 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
681 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000682 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000683
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000684 // (X & FF00) + xx00 -> (X+xx00) & FF00
685 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
686 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
687 if (Anded == CRHS) {
688 // See if all bits from the first bit set in the Add RHS up are included
689 // in the mask. First, get the rightmost bit.
690 uint64_t AddRHSV = CRHS->getRawValue();
691
692 // Form a mask of all bits from the lowest bit added through the top.
693 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattnerf52d6812005-04-24 17:46:05 +0000694 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000695
696 // See if the and mask includes all of these bits.
697 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000698
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000699 if (AddRHSHighBits == AddRHSHighBitsAnd) {
700 // Okay, the xform is safe. Insert the new add pronto.
701 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
702 LHS->getName()), I);
703 return BinaryOperator::createAnd(NewAdd, C2);
704 }
705 }
706 }
707
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000708 // Try to fold constant add into select arguments.
709 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000710 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000711 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000712 }
713
Chris Lattner7e708292002-06-25 16:13:24 +0000714 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000715}
716
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000717// isSignBit - Return true if the value represented by the constant only has the
718// highest order bit set.
719static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000720 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +0000721 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000722}
723
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000724/// RemoveNoopCast - Strip off nonconverting casts from the value.
725///
726static Value *RemoveNoopCast(Value *V) {
727 if (CastInst *CI = dyn_cast<CastInst>(V)) {
728 const Type *CTy = CI->getType();
729 const Type *OpTy = CI->getOperand(0)->getType();
730 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000731 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000732 return RemoveNoopCast(CI->getOperand(0));
733 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
734 return RemoveNoopCast(CI->getOperand(0));
735 }
736 return V;
737}
738
Chris Lattner7e708292002-06-25 16:13:24 +0000739Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000740 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000741
Chris Lattner233f7dc2002-08-12 21:17:25 +0000742 if (Op0 == Op1) // sub X, X -> 0
743 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000744
Chris Lattner233f7dc2002-08-12 21:17:25 +0000745 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000746 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000747 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000748
Chris Lattnere87597f2004-10-16 18:11:37 +0000749 if (isa<UndefValue>(Op0))
750 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
751 if (isa<UndefValue>(Op1))
752 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
753
Chris Lattnerd65460f2003-11-05 01:06:05 +0000754 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
755 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000756 if (C->isAllOnesValue())
757 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000758
Chris Lattnerd65460f2003-11-05 01:06:05 +0000759 // C - ~X == X + (1+C)
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000760 Value *X;
761 if (match(Op1, m_Not(m_Value(X))))
762 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000763 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000764 // -((uint)X >> 31) -> ((int)X >> 31)
765 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000766 if (C->isNullValue()) {
767 Value *NoopCastedRHS = RemoveNoopCast(Op1);
768 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000769 if (SI->getOpcode() == Instruction::Shr)
770 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
771 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000772 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000773 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000774 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000775 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000776 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +0000777 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000778 // Ok, the transformation is safe. Insert a cast of the incoming
779 // value, then the new shift, then the new cast.
780 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
781 SI->getOperand(0)->getName());
782 Value *InV = InsertNewInstBefore(FirstCast, I);
783 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
784 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000785 if (NewShift->getType() == I.getType())
786 return NewShift;
787 else {
788 InV = InsertNewInstBefore(NewShift, I);
789 return new CastInst(NewShift, I.getType());
790 }
Chris Lattner9c290672004-03-12 23:53:13 +0000791 }
792 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000793 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000794
795 // Try to fold constant sub into select arguments.
796 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000797 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +0000798 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000799
800 if (isa<PHINode>(Op0))
801 if (Instruction *NV = FoldOpIntoPhi(I))
802 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000803 }
804
Chris Lattner43d84d62005-04-07 16:15:25 +0000805 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
806 if (Op1I->getOpcode() == Instruction::Add &&
807 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +0000808 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000809 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000810 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000811 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000812 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
813 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
814 // C1-(X+C2) --> (C1-C2)-X
815 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
816 Op1I->getOperand(0));
817 }
Chris Lattner43d84d62005-04-07 16:15:25 +0000818 }
819
Chris Lattnerfd059242003-10-15 16:48:29 +0000820 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000821 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
822 // is not used by anyone else...
823 //
Chris Lattner0517e722004-02-02 20:09:56 +0000824 if (Op1I->getOpcode() == Instruction::Sub &&
825 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000826 // Swap the two operands of the subexpr...
827 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
828 Op1I->setOperand(0, IIOp1);
829 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +0000830
Chris Lattnera2881962003-02-18 19:28:33 +0000831 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000832 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000833 }
834
835 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
836 //
837 if (Op1I->getOpcode() == Instruction::And &&
838 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
839 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
840
Chris Lattnerf523d062004-06-09 05:08:07 +0000841 Value *NewNot =
842 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000843 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000844 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000845
Chris Lattner91ccc152004-10-06 15:08:25 +0000846 // -(X sdiv C) -> (X sdiv -C)
847 if (Op1I->getOpcode() == Instruction::Div)
848 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +0000849 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +0000850 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +0000851 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +0000852 ConstantExpr::getNeg(DivRHS));
853
Chris Lattnerad3448c2003-02-18 19:57:07 +0000854 // X - X*C --> X * (1-C)
Chris Lattner50af16a2004-11-13 19:50:12 +0000855 ConstantInt *C2;
856 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000857 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +0000858 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +0000859 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000860 }
Chris Lattner40371712002-05-09 01:29:19 +0000861 }
Chris Lattner43d84d62005-04-07 16:15:25 +0000862 }
Chris Lattnera2881962003-02-18 19:28:33 +0000863
Chris Lattner7edc8c22005-04-07 17:14:51 +0000864 if (!Op0->getType()->isFloatingPoint())
865 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
866 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000867 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
868 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
869 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
870 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +0000871 } else if (Op0I->getOpcode() == Instruction::Sub) {
872 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
873 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000874 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000875
Chris Lattner50af16a2004-11-13 19:50:12 +0000876 ConstantInt *C1;
877 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
878 if (X == Op1) { // X*C - X --> X * (C-1)
879 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
880 return BinaryOperator::createMul(Op1, CP1);
881 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000882
Chris Lattner50af16a2004-11-13 19:50:12 +0000883 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
884 if (X == dyn_castFoldableMul(Op1, C2))
885 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
886 }
Chris Lattner3f5b8772002-05-06 16:14:14 +0000887 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000888}
889
Chris Lattner4cb170c2004-02-23 06:38:22 +0000890/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
891/// really just returns true if the most significant (sign) bit is set.
892static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
893 if (RHS->getType()->isSigned()) {
894 // True if source is LHS < 0 or LHS <= -1
895 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
896 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
897 } else {
898 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
899 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
900 // the size of the integer type.
901 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +0000902 return RHSC->getValue() ==
903 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000904 if (Opcode == Instruction::SetGT)
905 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +0000906 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000907 }
908 return false;
909}
910
Chris Lattner7e708292002-06-25 16:13:24 +0000911Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000912 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000913 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000914
Chris Lattnere87597f2004-10-16 18:11:37 +0000915 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
917
Chris Lattner233f7dc2002-08-12 21:17:25 +0000918 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000919 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
920 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000921
922 // ((X << C1)*C2) == (X * (C2 << C1))
923 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
924 if (SI->getOpcode() == Instruction::Shl)
925 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000926 return BinaryOperator::createMul(SI->getOperand(0),
927 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +0000928
Chris Lattner515c97c2003-09-11 22:24:54 +0000929 if (CI->isNullValue())
930 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
931 if (CI->equalsInt(1)) // X * 1 == X
932 return ReplaceInstUsesWith(I, Op0);
933 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000934 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000935
Chris Lattner515c97c2003-09-11 22:24:54 +0000936 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000937 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
938 return new ShiftInst(Instruction::Shl, Op0,
939 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino71698282004-07-27 21:02:21 +0000940 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000941 if (Op1F->isNullValue())
942 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000943
Chris Lattnera2881962003-02-18 19:28:33 +0000944 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
945 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
946 if (Op1F->getValue() == 1.0)
947 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
948 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000949
950 // Try to fold constant mul into select arguments.
951 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000952 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +0000953 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000954
955 if (isa<PHINode>(Op0))
956 if (Instruction *NV = FoldOpIntoPhi(I))
957 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000958 }
959
Chris Lattnera4f445b2003-03-10 23:23:04 +0000960 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
961 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000962 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000963
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000964 // If one of the operands of the multiply is a cast from a boolean value, then
965 // we know the bool is either zero or one, so this is a 'masking' multiply.
966 // See if we can simplify things based on how the boolean was originally
967 // formed.
968 CastInst *BoolCast = 0;
969 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
970 if (CI->getOperand(0)->getType() == Type::BoolTy)
971 BoolCast = CI;
972 if (!BoolCast)
973 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
974 if (CI->getOperand(0)->getType() == Type::BoolTy)
975 BoolCast = CI;
976 if (BoolCast) {
977 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
978 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
979 const Type *SCOpTy = SCIOp0->getType();
980
Chris Lattner4cb170c2004-02-23 06:38:22 +0000981 // If the setcc is true iff the sign bit of X is set, then convert this
982 // multiply into a shift/and combination.
983 if (isa<ConstantInt>(SCIOp1) &&
984 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000985 // Shift the X value right to turn it into "all signbits".
986 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +0000987 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000988 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000989 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +0000990 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
991 SCIOp0->getName()), I);
992 }
993
994 Value *V =
995 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
996 BoolCast->getOperand(0)->getName()+
997 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000998
999 // If the multiply type is not the same as the source type, sign extend
1000 // or truncate to the multiply type.
1001 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001002 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001003
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001004 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001005 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001006 }
1007 }
1008 }
1009
Chris Lattner7e708292002-06-25 16:13:24 +00001010 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001011}
1012
Chris Lattner7e708292002-06-25 16:13:24 +00001013Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001015
Chris Lattner857e8cd2004-12-12 21:48:58 +00001016 if (isa<UndefValue>(Op0)) // undef / X -> 0
1017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1018 if (isa<UndefValue>(Op1))
1019 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1020
1021 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001022 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001023 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001024 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001025
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001026 // div X, -1 == -X
1027 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001028 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001029
Chris Lattner857e8cd2004-12-12 21:48:58 +00001030 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001031 if (LHS->getOpcode() == Instruction::Div)
1032 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001033 // (X / C1) / C2 -> X / (C1*C2)
1034 return BinaryOperator::createDiv(LHS->getOperand(0),
1035 ConstantExpr::getMul(RHS, LHSRHS));
1036 }
1037
Chris Lattnera2881962003-02-18 19:28:33 +00001038 // Check to see if this is an unsigned division with an exact power of 2,
1039 // if so, convert to a right shift.
1040 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1041 if (uint64_t Val = C->getValue()) // Don't break X / 0
1042 if (uint64_t C = Log2(Val))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001043 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001044 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner4e998b22004-09-29 05:07:12 +00001045
Chris Lattnera052f822004-10-09 02:50:40 +00001046 // -X/C -> X/-C
1047 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001048 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001049 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1050
Chris Lattner857e8cd2004-12-12 21:48:58 +00001051 if (!RHS->isNullValue()) {
1052 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001053 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001054 return R;
1055 if (isa<PHINode>(Op0))
1056 if (Instruction *NV = FoldOpIntoPhi(I))
1057 return NV;
1058 }
Chris Lattnera2881962003-02-18 19:28:33 +00001059 }
1060
Chris Lattner857e8cd2004-12-12 21:48:58 +00001061 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1062 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1063 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1064 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1065 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1066 if (STO->getValue() == 0) { // Couldn't be this argument.
1067 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001068 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001069 } else if (SFO->getValue() == 0) {
Chris Lattnerbf70b832005-04-08 04:03:26 +00001070 I.setOperand(2, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001071 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001072 }
1073
Chris Lattnerbf70b832005-04-08 04:03:26 +00001074 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1075 unsigned TSA = 0, FSA = 0;
1076 if ((TVA == 1 || (TSA = Log2(TVA))) && // Log2 fails for 0 & 1.
1077 (FVA == 1 || (FSA = Log2(FVA)))) {
1078 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1079 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1080 TC, SI->getName()+".t");
1081 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001082
Chris Lattnerbf70b832005-04-08 04:03:26 +00001083 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1084 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1085 FC, SI->getName()+".f");
1086 FSI = InsertNewInstBefore(FSI, I);
1087 return new SelectInst(SI->getOperand(0), TSI, FSI);
1088 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001089 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001090
Chris Lattnera2881962003-02-18 19:28:33 +00001091 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001092 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001093 if (LHS->equalsInt(0))
1094 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1095
Chris Lattner3f5b8772002-05-06 16:14:14 +00001096 return 0;
1097}
1098
1099
Chris Lattner7e708292002-06-25 16:13:24 +00001100Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner5b73c082004-07-06 07:01:22 +00001102 if (I.getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001103 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001104 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001105 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001106 // X % -Y -> X % Y
1107 AddUsesToWorkList(I);
1108 I.setOperand(1, RHSNeg);
1109 return &I;
1110 }
1111
Chris Lattner857e8cd2004-12-12 21:48:58 +00001112 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00001113 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001114 if (isa<UndefValue>(Op1))
1115 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00001116
Chris Lattner857e8cd2004-12-12 21:48:58 +00001117 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001118 if (RHS->equalsInt(1)) // X % 1 == 0
1119 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1120
1121 // Check to see if this is an unsigned remainder with an exact power of 2,
1122 // if so, convert to a bitwise and.
1123 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1124 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001125 if (!(Val & (Val-1))) // Power of 2
Chris Lattner857e8cd2004-12-12 21:48:58 +00001126 return BinaryOperator::createAnd(Op0,
1127 ConstantUInt::get(I.getType(), Val-1));
1128
1129 if (!RHS->isNullValue()) {
1130 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001131 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001132 return R;
1133 if (isa<PHINode>(Op0))
1134 if (Instruction *NV = FoldOpIntoPhi(I))
1135 return NV;
1136 }
Chris Lattnera2881962003-02-18 19:28:33 +00001137 }
1138
Chris Lattner857e8cd2004-12-12 21:48:58 +00001139 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1140 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1141 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1142 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1143 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1144 if (STO->getValue() == 0) { // Couldn't be this argument.
1145 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001146 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001147 } else if (SFO->getValue() == 0) {
1148 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001149 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001150 }
1151
1152 if (!(STO->getValue() & (STO->getValue()-1)) &&
1153 !(SFO->getValue() & (SFO->getValue()-1))) {
1154 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1155 SubOne(STO), SI->getName()+".t"), I);
1156 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1157 SubOne(SFO), SI->getName()+".f"), I);
1158 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1159 }
1160 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001161
Chris Lattnera2881962003-02-18 19:28:33 +00001162 // 0 % X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001163 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001164 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1166
Chris Lattner3f5b8772002-05-06 16:14:14 +00001167 return 0;
1168}
1169
Chris Lattner8b170942002-08-09 23:47:40 +00001170// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001171static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001172 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1173 // Calculate -1 casted to the right type...
Chris Lattner484d3cf2005-04-24 06:59:08 +00001174 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001175 uint64_t Val = ~0ULL; // All ones
1176 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1177 return CU->getValue() == Val-1;
1178 }
1179
1180 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001181
Chris Lattner8b170942002-08-09 23:47:40 +00001182 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001183 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001184 int64_t Val = INT64_MAX; // All ones
1185 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1186 return CS->getValue() == Val-1;
1187}
1188
1189// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001190static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001191 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1192 return CU->getValue() == 1;
1193
1194 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001195
1196 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00001197 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001198 int64_t Val = -1; // All ones
1199 Val <<= TypeBits-1; // Shift over to the right spot
1200 return CS->getValue() == Val+1;
1201}
1202
Chris Lattner457dd822004-06-09 07:59:58 +00001203// isOneBitSet - Return true if there is exactly one bit set in the specified
1204// constant.
1205static bool isOneBitSet(const ConstantInt *CI) {
1206 uint64_t V = CI->getRawValue();
1207 return V && (V & (V-1)) == 0;
1208}
1209
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001210#if 0 // Currently unused
1211// isLowOnes - Return true if the constant is of the form 0+1+.
1212static bool isLowOnes(const ConstantInt *CI) {
1213 uint64_t V = CI->getRawValue();
1214
1215 // There won't be bits set in parts that the type doesn't contain.
1216 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1217
1218 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1219 return U && V && (U & V) == 0;
1220}
1221#endif
1222
1223// isHighOnes - Return true if the constant is of the form 1+0+.
1224// This is the same as lowones(~X).
1225static bool isHighOnes(const ConstantInt *CI) {
1226 uint64_t V = ~CI->getRawValue();
1227
1228 // There won't be bits set in parts that the type doesn't contain.
1229 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1230
1231 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1232 return U && V && (U & V) == 0;
1233}
1234
1235
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001236/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1237/// are carefully arranged to allow folding of expressions such as:
1238///
1239/// (A < B) | (A > B) --> (A != B)
1240///
1241/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1242/// represents that the comparison is true if A == B, and bit value '1' is true
1243/// if A < B.
1244///
1245static unsigned getSetCondCode(const SetCondInst *SCI) {
1246 switch (SCI->getOpcode()) {
1247 // False -> 0
1248 case Instruction::SetGT: return 1;
1249 case Instruction::SetEQ: return 2;
1250 case Instruction::SetGE: return 3;
1251 case Instruction::SetLT: return 4;
1252 case Instruction::SetNE: return 5;
1253 case Instruction::SetLE: return 6;
1254 // True -> 7
1255 default:
1256 assert(0 && "Invalid SetCC opcode!");
1257 return 0;
1258 }
1259}
1260
1261/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1262/// opcode and two operands into either a constant true or false, or a brand new
1263/// SetCC instruction.
1264static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1265 switch (Opcode) {
1266 case 0: return ConstantBool::False;
1267 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1268 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1269 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1270 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1271 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1272 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1273 case 7: return ConstantBool::True;
1274 default: assert(0 && "Illegal SetCCCode!"); return 0;
1275 }
1276}
1277
1278// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1279struct FoldSetCCLogical {
1280 InstCombiner &IC;
1281 Value *LHS, *RHS;
1282 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1283 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1284 bool shouldApply(Value *V) const {
1285 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1286 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1287 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1288 return false;
1289 }
1290 Instruction *apply(BinaryOperator &Log) const {
1291 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1292 if (SCI->getOperand(0) != LHS) {
1293 assert(SCI->getOperand(1) == LHS);
1294 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1295 }
1296
1297 unsigned LHSCode = getSetCondCode(SCI);
1298 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1299 unsigned Code;
1300 switch (Log.getOpcode()) {
1301 case Instruction::And: Code = LHSCode & RHSCode; break;
1302 case Instruction::Or: Code = LHSCode | RHSCode; break;
1303 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001304 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001305 }
1306
1307 Value *RV = getSetCCValue(Code, LHS, RHS);
1308 if (Instruction *I = dyn_cast<Instruction>(RV))
1309 return I;
1310 // Otherwise, it's a constant boolean value...
1311 return IC.ReplaceInstUsesWith(Log, RV);
1312 }
1313};
1314
1315
Chris Lattner6e7ba452005-01-01 16:22:27 +00001316/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1317/// this predicate to simplify operations downstream. V and Mask are known to
1318/// be the same type.
1319static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1320 if (isa<UndefValue>(V) || Mask->isNullValue())
1321 return true;
1322 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1323 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001324
Chris Lattner6e7ba452005-01-01 16:22:27 +00001325 if (Instruction *I = dyn_cast<Instruction>(V)) {
1326 switch (I->getOpcode()) {
1327 case Instruction::And:
1328 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1329 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1330 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1331 return true;
1332 break;
Chris Lattnerad1e3022005-01-23 20:26:55 +00001333 case Instruction::Or:
1334 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Misha Brukmanfd939082005-04-21 23:48:37 +00001335 return MaskedValueIsZero(I->getOperand(1), Mask) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00001336 MaskedValueIsZero(I->getOperand(0), Mask);
1337 case Instruction::Select:
1338 // If the T and F values are MaskedValueIsZero, the result is also zero.
Misha Brukmanfd939082005-04-21 23:48:37 +00001339 return MaskedValueIsZero(I->getOperand(2), Mask) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00001340 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001341 case Instruction::Cast: {
1342 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerd1523802005-05-06 01:53:19 +00001343 if (SrcTy == Type::BoolTy)
1344 return (Mask->getRawValue() & 1) == 0;
1345
1346 if (SrcTy->isInteger()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001347 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1348 if (SrcTy->isUnsigned() && // Only handle zero ext.
1349 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1350 return true;
1351
1352 // If this is a noop cast, recurse.
Chris Lattnerd1523802005-05-06 01:53:19 +00001353 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
1354 SrcTy->getSignedVersion() == I->getType()) {
1355 Constant *NewMask =
1356 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1357 return MaskedValueIsZero(I->getOperand(0),
1358 cast<ConstantIntegral>(NewMask));
1359 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001360 }
1361 break;
1362 }
1363 case Instruction::Shl:
1364 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1365 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1366 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1367 C1 = ConstantExpr::getShl(C1, SA);
1368 C1 = ConstantExpr::getAnd(C1, Mask);
1369 if (C1->isNullValue())
1370 return true;
1371 }
1372 break;
1373 case Instruction::Shr:
1374 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1375 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1376 if (I->getType()->isUnsigned()) {
1377 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1378 C1 = ConstantExpr::getShr(C1, SA);
1379 C1 = ConstantExpr::getAnd(C1, Mask);
1380 if (C1->isNullValue())
1381 return true;
1382 }
1383 break;
1384 }
1385 }
1386
1387 return false;
1388}
1389
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001390// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1391// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1392// guaranteed to be either a shift instruction or a binary operator.
1393Instruction *InstCombiner::OptAndOp(Instruction *Op,
1394 ConstantIntegral *OpRHS,
1395 ConstantIntegral *AndRHS,
1396 BinaryOperator &TheAnd) {
1397 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001398 Constant *Together = 0;
1399 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001400 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001401
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001402 switch (Op->getOpcode()) {
1403 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001404 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001405 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1406 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001407 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001408 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001409 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001410 }
1411 break;
1412 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001413 if (Together == AndRHS) // (X | C) & C --> C
1414 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001415
Chris Lattner6e7ba452005-01-01 16:22:27 +00001416 if (Op->hasOneUse() && Together != OpRHS) {
1417 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1418 std::string Op0Name = Op->getName(); Op->setName("");
1419 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1420 InsertNewInstBefore(Or, TheAnd);
1421 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001422 }
1423 break;
1424 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001425 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001426 // Adding a one to a single bit bit-field should be turned into an XOR
1427 // of the bit. First thing to check is to see if this AND is with a
1428 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001429 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001430
1431 // Clear bits that are not part of the constant.
Chris Lattnerf52d6812005-04-24 17:46:05 +00001432 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001433
1434 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001435 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001436 // Ok, at this point, we know that we are masking the result of the
1437 // ADD down to exactly one bit. If the constant we are adding has
1438 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001439 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001440
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001441 // Check to see if any bits below the one bit set in AndRHSV are set.
1442 if ((AddRHS & (AndRHSV-1)) == 0) {
1443 // If not, the only thing that can effect the output of the AND is
1444 // the bit specified by AndRHSV. If that bit is set, the effect of
1445 // the XOR is to toggle the bit. If it is clear, then the ADD has
1446 // no effect.
1447 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1448 TheAnd.setOperand(0, X);
1449 return &TheAnd;
1450 } else {
1451 std::string Name = Op->getName(); Op->setName("");
1452 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001453 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001454 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001455 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001456 }
1457 }
1458 }
1459 }
1460 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001461
1462 case Instruction::Shl: {
1463 // We know that the AND will not produce any of the bits shifted in, so if
1464 // the anded constant includes them, clear them now!
1465 //
1466 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001467 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1468 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001469
Chris Lattner0c967662004-09-24 15:21:34 +00001470 if (CI == ShlMask) { // Masking out bits that the shift already masks
1471 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1472 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001473 TheAnd.setOperand(1, CI);
1474 return &TheAnd;
1475 }
1476 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001477 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001478 case Instruction::Shr:
1479 // We know that the AND will not produce any of the bits shifted in, so if
1480 // the anded constant includes them, clear them now! This only applies to
1481 // unsigned shifts, because a signed shr may bring in set bits!
1482 //
1483 if (AndRHS->getType()->isUnsigned()) {
1484 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001485 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1486 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1487
1488 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1489 return ReplaceInstUsesWith(TheAnd, Op);
1490 } else if (CI != AndRHS) {
1491 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001492 return &TheAnd;
1493 }
Chris Lattner0c967662004-09-24 15:21:34 +00001494 } else { // Signed shr.
1495 // See if this is shifting in some sign extension, then masking it out
1496 // with an and.
1497 if (Op->hasOneUse()) {
1498 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1499 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1500 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001501 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001502 // Make the argument unsigned.
1503 Value *ShVal = Op->getOperand(0);
1504 ShVal = InsertCastBefore(ShVal,
1505 ShVal->getType()->getUnsignedVersion(),
1506 TheAnd);
1507 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1508 OpRHS, Op->getName()),
1509 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001510 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1511 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1512 TheAnd.getName()),
1513 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001514 return new CastInst(ShVal, Op->getType());
1515 }
1516 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001517 }
1518 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001519 }
1520 return 0;
1521}
1522
Chris Lattner8b170942002-08-09 23:47:40 +00001523
Chris Lattnera96879a2004-09-29 17:40:11 +00001524/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1525/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1526/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1527/// insert new instructions.
1528Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1529 bool Inside, Instruction &IB) {
1530 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1531 "Lo is not <= Hi in range emission code!");
1532 if (Inside) {
1533 if (Lo == Hi) // Trivially false.
1534 return new SetCondInst(Instruction::SetNE, V, V);
1535 if (cast<ConstantIntegral>(Lo)->isMinValue())
1536 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00001537
Chris Lattnera96879a2004-09-29 17:40:11 +00001538 Constant *AddCST = ConstantExpr::getNeg(Lo);
1539 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1540 InsertNewInstBefore(Add, IB);
1541 // Convert to unsigned for the comparison.
1542 const Type *UnsType = Add->getType()->getUnsignedVersion();
1543 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1544 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1545 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1546 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1547 }
1548
1549 if (Lo == Hi) // Trivially true.
1550 return new SetCondInst(Instruction::SetEQ, V, V);
1551
1552 Hi = SubOne(cast<ConstantInt>(Hi));
1553 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1554 return new SetCondInst(Instruction::SetGT, V, Hi);
1555
1556 // Emit X-Lo > Hi-Lo-1
1557 Constant *AddCST = ConstantExpr::getNeg(Lo);
1558 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1559 InsertNewInstBefore(Add, IB);
1560 // Convert to unsigned for the comparison.
1561 const Type *UnsType = Add->getType()->getUnsignedVersion();
1562 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1563 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1564 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1565 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1566}
1567
1568
Chris Lattner7e708292002-06-25 16:13:24 +00001569Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001570 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001571 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001572
Chris Lattnere87597f2004-10-16 18:11:37 +00001573 if (isa<UndefValue>(Op1)) // X & undef -> 0
1574 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1575
Chris Lattner6e7ba452005-01-01 16:22:27 +00001576 // and X, X = X
1577 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00001578 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001579
Chris Lattner6e7ba452005-01-01 16:22:27 +00001580 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerad1e3022005-01-23 20:26:55 +00001581 // and X, -1 == X
1582 if (AndRHS->isAllOnesValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001583 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001584
Chris Lattner6e7ba452005-01-01 16:22:27 +00001585 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1586 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1587
1588 // If the mask is not masking out any bits, there is no reason to do the
1589 // and in the first place.
Misha Brukmanfd939082005-04-21 23:48:37 +00001590 ConstantIntegral *NotAndRHS =
Chris Lattnerad1e3022005-01-23 20:26:55 +00001591 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanfd939082005-04-21 23:48:37 +00001592 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattnerad1e3022005-01-23 20:26:55 +00001593 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001594
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001595 // Optimize a variety of ((val OP C1) & C2) combinations...
1596 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1597 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001598 Value *Op0LHS = Op0I->getOperand(0);
1599 Value *Op0RHS = Op0I->getOperand(1);
1600 switch (Op0I->getOpcode()) {
1601 case Instruction::Xor:
1602 case Instruction::Or:
1603 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1604 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1605 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001606 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001607 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001608 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001609
1610 // If the mask is only needed on one incoming arm, push it up.
1611 if (Op0I->hasOneUse()) {
1612 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1613 // Not masking anything out for the LHS, move to RHS.
1614 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1615 Op0RHS->getName()+".masked");
1616 InsertNewInstBefore(NewRHS, I);
1617 return BinaryOperator::create(
1618 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001619 }
Chris Lattnerad1e3022005-01-23 20:26:55 +00001620 if (!isa<Constant>(NotAndRHS) &&
1621 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1622 // Not masking anything out for the RHS, move to LHS.
1623 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1624 Op0LHS->getName()+".masked");
1625 InsertNewInstBefore(NewLHS, I);
1626 return BinaryOperator::create(
1627 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1628 }
1629 }
1630
Chris Lattner6e7ba452005-01-01 16:22:27 +00001631 break;
1632 case Instruction::And:
1633 // (X & V) & C2 --> 0 iff (V & C2) == 0
1634 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1635 MaskedValueIsZero(Op0RHS, AndRHS))
1636 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1637 break;
1638 }
1639
Chris Lattner58403262003-07-23 19:25:52 +00001640 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001641 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001642 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001643 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1644 const Type *SrcTy = CI->getOperand(0)->getType();
1645
1646 // If this is an integer sign or zero extension instruction.
1647 if (SrcTy->isIntegral() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00001648 SrcTy->getPrimitiveSizeInBits() <
1649 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001650
1651 if (SrcTy->isUnsigned()) {
1652 // See if this and is clearing out bits that are known to be zero
1653 // anyway (due to the zero extension).
1654 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1655 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1656 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1657 if (Result == Mask) // The "and" isn't doing anything, remove it.
1658 return ReplaceInstUsesWith(I, CI);
1659 if (Result != AndRHS) { // Reduce the and RHS constant.
1660 I.setOperand(1, Result);
1661 return &I;
1662 }
1663
1664 } else {
1665 if (CI->hasOneUse() && SrcTy->isInteger()) {
1666 // We can only do this if all of the sign bits brought in are masked
1667 // out. Compute this by first getting 0000011111, then inverting
1668 // it.
1669 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1670 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1671 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1672 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1673 // If the and is clearing all of the sign bits, change this to a
1674 // zero extension cast. To do this, cast the cast input to
1675 // unsigned, then to the requested size.
1676 Value *CastOp = CI->getOperand(0);
1677 Instruction *NC =
1678 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1679 CI->getName()+".uns");
1680 NC = InsertNewInstBefore(NC, I);
1681 // Finally, insert a replacement for CI.
1682 NC = new CastInst(NC, CI->getType(), CI->getName());
1683 CI->setName("");
1684 NC = InsertNewInstBefore(NC, I);
1685 WorkList.push_back(CI); // Delete CI later.
1686 I.setOperand(0, NC);
1687 return &I; // The AND operand was modified.
1688 }
1689 }
1690 }
1691 }
Chris Lattner06782f82003-07-23 19:36:21 +00001692 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001693
1694 // Try to fold constant and into select arguments.
1695 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001696 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001697 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001698 if (isa<PHINode>(Op0))
1699 if (Instruction *NV = FoldOpIntoPhi(I))
1700 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001701 }
1702
Chris Lattner8d969642003-03-10 23:06:50 +00001703 Value *Op0NotVal = dyn_castNotVal(Op0);
1704 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001705
Chris Lattner5b62aa72004-06-18 06:07:51 +00001706 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1707 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1708
Misha Brukmancb6267b2004-07-30 12:50:08 +00001709 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001710 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001711 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1712 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001713 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001714 return BinaryOperator::createNot(Or);
1715 }
1716
Chris Lattner955f3312004-09-28 21:48:02 +00001717 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1718 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001719 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1720 return R;
1721
Chris Lattner955f3312004-09-28 21:48:02 +00001722 Value *LHSVal, *RHSVal;
1723 ConstantInt *LHSCst, *RHSCst;
1724 Instruction::BinaryOps LHSCC, RHSCC;
1725 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1726 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1727 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1728 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00001729 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00001730 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1731 // Ensure that the larger constant is on the RHS.
1732 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1733 SetCondInst *LHS = cast<SetCondInst>(Op0);
1734 if (cast<ConstantBool>(Cmp)->getValue()) {
1735 std::swap(LHS, RHS);
1736 std::swap(LHSCst, RHSCst);
1737 std::swap(LHSCC, RHSCC);
1738 }
1739
1740 // At this point, we know we have have two setcc instructions
1741 // comparing a value against two constants and and'ing the result
1742 // together. Because of the above check, we know that we only have
1743 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1744 // FoldSetCCLogical check above), that the two constants are not
1745 // equal.
1746 assert(LHSCst != RHSCst && "Compares not folded above?");
1747
1748 switch (LHSCC) {
1749 default: assert(0 && "Unknown integer condition code!");
1750 case Instruction::SetEQ:
1751 switch (RHSCC) {
1752 default: assert(0 && "Unknown integer condition code!");
1753 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1754 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1755 return ReplaceInstUsesWith(I, ConstantBool::False);
1756 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1757 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1758 return ReplaceInstUsesWith(I, LHS);
1759 }
1760 case Instruction::SetNE:
1761 switch (RHSCC) {
1762 default: assert(0 && "Unknown integer condition code!");
1763 case Instruction::SetLT:
1764 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1765 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1766 break; // (X != 13 & X < 15) -> no change
1767 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1768 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1769 return ReplaceInstUsesWith(I, RHS);
1770 case Instruction::SetNE:
1771 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1772 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1773 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1774 LHSVal->getName()+".off");
1775 InsertNewInstBefore(Add, I);
1776 const Type *UnsType = Add->getType()->getUnsignedVersion();
1777 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1778 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1779 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1780 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1781 }
1782 break; // (X != 13 & X != 15) -> no change
1783 }
1784 break;
1785 case Instruction::SetLT:
1786 switch (RHSCC) {
1787 default: assert(0 && "Unknown integer condition code!");
1788 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1789 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1790 return ReplaceInstUsesWith(I, ConstantBool::False);
1791 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1792 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1793 return ReplaceInstUsesWith(I, LHS);
1794 }
1795 case Instruction::SetGT:
1796 switch (RHSCC) {
1797 default: assert(0 && "Unknown integer condition code!");
1798 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1799 return ReplaceInstUsesWith(I, LHS);
1800 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1801 return ReplaceInstUsesWith(I, RHS);
1802 case Instruction::SetNE:
1803 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1804 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1805 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00001806 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1807 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00001808 }
1809 }
1810 }
1811 }
1812
Chris Lattner7e708292002-06-25 16:13:24 +00001813 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001814}
1815
Chris Lattner7e708292002-06-25 16:13:24 +00001816Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001817 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001818 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001819
Chris Lattnere87597f2004-10-16 18:11:37 +00001820 if (isa<UndefValue>(Op1))
1821 return ReplaceInstUsesWith(I, // X | undef -> -1
1822 ConstantIntegral::getAllOnesValue(I.getType()));
1823
Chris Lattner3f5b8772002-05-06 16:14:14 +00001824 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001825 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1826 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001827
1828 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001829 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001830 // If X is known to only contain bits that already exist in RHS, just
1831 // replace this instruction with RHS directly.
1832 if (MaskedValueIsZero(Op0,
1833 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1834 return ReplaceInstUsesWith(I, RHS);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001835
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001836 ConstantInt *C1; Value *X;
1837 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1838 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1839 std::string Op0Name = Op0->getName(); Op0->setName("");
1840 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1841 InsertNewInstBefore(Or, I);
1842 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1843 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001844
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001845 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1846 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1847 std::string Op0Name = Op0->getName(); Op0->setName("");
1848 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1849 InsertNewInstBefore(Or, I);
1850 return BinaryOperator::createXor(Or,
1851 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001852 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001853
1854 // Try to fold constant and into select arguments.
1855 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001856 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001857 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001858 if (isa<PHINode>(Op0))
1859 if (Instruction *NV = FoldOpIntoPhi(I))
1860 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001861 }
1862
Chris Lattner67ca7682003-08-12 19:11:07 +00001863 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001864 Value *A, *B; ConstantInt *C1, *C2;
1865 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1866 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1867 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner67ca7682003-08-12 19:11:07 +00001868
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001869 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1870 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00001871 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001872 ConstantIntegral::getAllOnesValue(I.getType()));
1873 } else {
1874 A = 0;
1875 }
Chris Lattnera2881962003-02-18 19:28:33 +00001876
Chris Lattner828eedd2005-05-06 00:58:50 +00001877 if (match(Op0, m_And(m_Value(A), m_Value(B))))
1878 if (A == Op1 || B == Op1) // (A & ?) | A --> A
1879 return ReplaceInstUsesWith(I, Op1);
1880 if (match(Op1, m_And(m_Value(A), m_Value(B))))
1881 if (A == Op0 || B == Op0) // A | (A & ?) --> A
1882 return ReplaceInstUsesWith(I, Op0);
1883
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001884 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1885 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00001886 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001887 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00001888
Misha Brukmancb6267b2004-07-30 12:50:08 +00001889 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001890 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1891 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1892 I.getName()+".demorgan"), I);
1893 return BinaryOperator::createNot(And);
1894 }
Chris Lattnera27231a2003-03-10 23:13:59 +00001895 }
Chris Lattnera2881962003-02-18 19:28:33 +00001896
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001897 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001898 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001899 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1900 return R;
1901
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001902 Value *LHSVal, *RHSVal;
1903 ConstantInt *LHSCst, *RHSCst;
1904 Instruction::BinaryOps LHSCC, RHSCC;
1905 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1906 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1907 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1908 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00001909 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001910 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1911 // Ensure that the larger constant is on the RHS.
1912 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1913 SetCondInst *LHS = cast<SetCondInst>(Op0);
1914 if (cast<ConstantBool>(Cmp)->getValue()) {
1915 std::swap(LHS, RHS);
1916 std::swap(LHSCst, RHSCst);
1917 std::swap(LHSCC, RHSCC);
1918 }
1919
1920 // At this point, we know we have have two setcc instructions
1921 // comparing a value against two constants and or'ing the result
1922 // together. Because of the above check, we know that we only have
1923 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1924 // FoldSetCCLogical check above), that the two constants are not
1925 // equal.
1926 assert(LHSCst != RHSCst && "Compares not folded above?");
1927
1928 switch (LHSCC) {
1929 default: assert(0 && "Unknown integer condition code!");
1930 case Instruction::SetEQ:
1931 switch (RHSCC) {
1932 default: assert(0 && "Unknown integer condition code!");
1933 case Instruction::SetEQ:
1934 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1935 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1936 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1937 LHSVal->getName()+".off");
1938 InsertNewInstBefore(Add, I);
1939 const Type *UnsType = Add->getType()->getUnsignedVersion();
1940 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1941 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1942 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1943 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1944 }
1945 break; // (X == 13 | X == 15) -> no change
1946
Chris Lattner240d6f42005-04-19 06:04:18 +00001947 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
1948 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001949 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1950 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1951 return ReplaceInstUsesWith(I, RHS);
1952 }
1953 break;
1954 case Instruction::SetNE:
1955 switch (RHSCC) {
1956 default: assert(0 && "Unknown integer condition code!");
1957 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1958 return ReplaceInstUsesWith(I, RHS);
1959 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1960 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1961 return ReplaceInstUsesWith(I, LHS);
1962 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1963 return ReplaceInstUsesWith(I, ConstantBool::True);
1964 }
1965 break;
1966 case Instruction::SetLT:
1967 switch (RHSCC) {
1968 default: assert(0 && "Unknown integer condition code!");
1969 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1970 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00001971 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1972 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001973 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1974 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1975 return ReplaceInstUsesWith(I, RHS);
1976 }
1977 break;
1978 case Instruction::SetGT:
1979 switch (RHSCC) {
1980 default: assert(0 && "Unknown integer condition code!");
1981 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1982 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1983 return ReplaceInstUsesWith(I, LHS);
1984 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1985 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1986 return ReplaceInstUsesWith(I, ConstantBool::True);
1987 }
1988 }
1989 }
1990 }
Chris Lattner7e708292002-06-25 16:13:24 +00001991 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001992}
1993
Chris Lattnerc317d392004-02-16 01:20:27 +00001994// XorSelf - Implements: X ^ X --> 0
1995struct XorSelf {
1996 Value *RHS;
1997 XorSelf(Value *rhs) : RHS(rhs) {}
1998 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1999 Instruction *apply(BinaryOperator &Xor) const {
2000 return &Xor;
2001 }
2002};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002003
2004
Chris Lattner7e708292002-06-25 16:13:24 +00002005Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002006 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002008
Chris Lattnere87597f2004-10-16 18:11:37 +00002009 if (isa<UndefValue>(Op1))
2010 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2011
Chris Lattnerc317d392004-02-16 01:20:27 +00002012 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2013 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2014 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002016 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002017
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002018 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00002019 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002020 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002021 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00002022
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002023 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002024 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002025 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002026 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002027 return new SetCondInst(SCI->getInverseCondition(),
2028 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002029
Chris Lattnerd65460f2003-11-05 01:06:05 +00002030 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002031 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2032 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002033 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2034 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002035 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002036 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002037 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002038
2039 // ~(~X & Y) --> (X | ~Y)
2040 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2041 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2042 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2043 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002044 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002045 Op0I->getOperand(1)->getName()+".not");
2046 InsertNewInstBefore(NotY, I);
2047 return BinaryOperator::createOr(Op0NotVal, NotY);
2048 }
2049 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002050
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002051 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002052 switch (Op0I->getOpcode()) {
2053 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00002054 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002055 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002056 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2057 return BinaryOperator::createSub(
2058 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002059 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002060 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002061 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002062 break;
2063 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002064 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00002065 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2066 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002067 break;
2068 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002069 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00002070 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00002071 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002072 break;
2073 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002074 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002075 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002076
2077 // Try to fold constant and into select arguments.
2078 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002079 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002080 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002081 if (isa<PHINode>(Op0))
2082 if (Instruction *NV = FoldOpIntoPhi(I))
2083 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002084 }
2085
Chris Lattner8d969642003-03-10 23:06:50 +00002086 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002087 if (X == Op1)
2088 return ReplaceInstUsesWith(I,
2089 ConstantIntegral::getAllOnesValue(I.getType()));
2090
Chris Lattner8d969642003-03-10 23:06:50 +00002091 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002092 if (X == Op0)
2093 return ReplaceInstUsesWith(I,
2094 ConstantIntegral::getAllOnesValue(I.getType()));
2095
Chris Lattnercb40a372003-03-10 18:24:17 +00002096 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002097 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002098 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2099 cast<BinaryOperator>(Op1I)->swapOperands();
2100 I.swapOperands();
2101 std::swap(Op0, Op1);
2102 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2103 I.swapOperands();
2104 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002105 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002106 } else if (Op1I->getOpcode() == Instruction::Xor) {
2107 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2108 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2109 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2110 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2111 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002112
2113 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002114 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002115 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2116 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002117 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00002118 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2119 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002120 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00002121 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002122 } else if (Op0I->getOpcode() == Instruction::Xor) {
2123 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2124 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2125 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2126 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00002127 }
2128
Chris Lattner14840892004-08-01 19:42:59 +00002129 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002130 Value *A, *B; ConstantInt *C1, *C2;
2131 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2132 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00002133 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002134 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00002135
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002136 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2137 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2138 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2139 return R;
2140
Chris Lattner7e708292002-06-25 16:13:24 +00002141 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002142}
2143
Chris Lattnera96879a2004-09-29 17:40:11 +00002144/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2145/// overflowed for this type.
2146static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2147 ConstantInt *In2) {
2148 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2149 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2150}
2151
2152static bool isPositive(ConstantInt *C) {
2153 return cast<ConstantSInt>(C)->getValue() >= 0;
2154}
2155
2156/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2157/// overflowed for this type.
2158static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2159 ConstantInt *In2) {
2160 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2161
2162 if (In1->getType()->isUnsigned())
2163 return cast<ConstantUInt>(Result)->getValue() <
2164 cast<ConstantUInt>(In1)->getValue();
2165 if (isPositive(In1) != isPositive(In2))
2166 return false;
2167 if (isPositive(In1))
2168 return cast<ConstantSInt>(Result)->getValue() <
2169 cast<ConstantSInt>(In1)->getValue();
2170 return cast<ConstantSInt>(Result)->getValue() >
2171 cast<ConstantSInt>(In1)->getValue();
2172}
2173
Chris Lattner574da9b2005-01-13 20:14:25 +00002174/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2175/// code necessary to compute the offset from the base pointer (without adding
2176/// in the base pointer). Return the result as a signed integer of intptr size.
2177static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2178 TargetData &TD = IC.getTargetData();
2179 gep_type_iterator GTI = gep_type_begin(GEP);
2180 const Type *UIntPtrTy = TD.getIntPtrType();
2181 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2182 Value *Result = Constant::getNullValue(SIntPtrTy);
2183
2184 // Build a mask for high order bits.
2185 uint64_t PtrSizeMask = ~0ULL;
2186 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2187
Chris Lattner574da9b2005-01-13 20:14:25 +00002188 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2189 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00002190 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00002191 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2192 SIntPtrTy);
2193 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2194 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002195 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00002196 Scale = ConstantExpr::getMul(OpC, Scale);
2197 if (Constant *RC = dyn_cast<Constant>(Result))
2198 Result = ConstantExpr::getAdd(RC, Scale);
2199 else {
2200 // Emit an add instruction.
2201 Result = IC.InsertNewInstBefore(
2202 BinaryOperator::createAdd(Result, Scale,
2203 GEP->getName()+".offs"), I);
2204 }
2205 }
2206 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00002207 // Convert to correct type.
2208 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2209 Op->getName()+".c"), I);
2210 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002211 // We'll let instcombine(mul) convert this to a shl if possible.
2212 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2213 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00002214
2215 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002216 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00002217 GEP->getName()+".offs"), I);
2218 }
2219 }
2220 return Result;
2221}
2222
2223/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2224/// else. At this point we know that the GEP is on the LHS of the comparison.
2225Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2226 Instruction::BinaryOps Cond,
2227 Instruction &I) {
2228 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00002229
2230 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2231 if (isa<PointerType>(CI->getOperand(0)->getType()))
2232 RHS = CI->getOperand(0);
2233
Chris Lattner574da9b2005-01-13 20:14:25 +00002234 Value *PtrBase = GEPLHS->getOperand(0);
2235 if (PtrBase == RHS) {
2236 // As an optimization, we don't actually have to compute the actual value of
2237 // OFFSET if this is a seteq or setne comparison, just return whether each
2238 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002239 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2240 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002241 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2242 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00002243 bool EmitIt = true;
2244 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2245 if (isa<UndefValue>(C)) // undef index -> undef.
2246 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2247 if (C->isNullValue())
2248 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002249 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2250 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00002251 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00002252 return ReplaceInstUsesWith(I, // No comparison is needed here.
2253 ConstantBool::get(Cond == Instruction::SetNE));
2254 }
2255
2256 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002257 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00002258 new SetCondInst(Cond, GEPLHS->getOperand(i),
2259 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2260 if (InVal == 0)
2261 InVal = Comp;
2262 else {
2263 InVal = InsertNewInstBefore(InVal, I);
2264 InsertNewInstBefore(Comp, I);
2265 if (Cond == Instruction::SetNE) // True if any are unequal
2266 InVal = BinaryOperator::createOr(InVal, Comp);
2267 else // True if all are equal
2268 InVal = BinaryOperator::createAnd(InVal, Comp);
2269 }
2270 }
2271 }
2272
2273 if (InVal)
2274 return InVal;
2275 else
2276 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2277 ConstantBool::get(Cond == Instruction::SetEQ));
2278 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002279
2280 // Only lower this if the setcc is the only user of the GEP or if we expect
2281 // the result to fold to a constant!
2282 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2283 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2284 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2285 return new SetCondInst(Cond, Offset,
2286 Constant::getNullValue(Offset->getType()));
2287 }
2288 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00002289 // If the base pointers are different, but the indices are the same, just
2290 // compare the base pointer.
2291 if (PtrBase != GEPRHS->getOperand(0)) {
2292 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Chris Lattner93b94a62005-04-26 14:40:41 +00002293 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2294 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00002295 if (IndicesTheSame)
2296 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2297 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2298 IndicesTheSame = false;
2299 break;
2300 }
2301
2302 // If all indices are the same, just compare the base pointers.
2303 if (IndicesTheSame)
2304 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2305 GEPRHS->getOperand(0));
2306
2307 // Otherwise, the base pointers are different and the indices are
2308 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00002309 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00002310 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002311
Chris Lattnere9d782b2005-01-13 22:25:21 +00002312 // If one of the GEPs has all zero indices, recurse.
2313 bool AllZeros = true;
2314 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2315 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2316 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2317 AllZeros = false;
2318 break;
2319 }
2320 if (AllZeros)
2321 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2322 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002323
2324 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002325 AllZeros = true;
2326 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2327 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2328 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2329 AllZeros = false;
2330 break;
2331 }
2332 if (AllZeros)
2333 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2334
Chris Lattner4401c9c2005-01-14 00:20:05 +00002335 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2336 // If the GEPs only differ by one index, compare it.
2337 unsigned NumDifferences = 0; // Keep track of # differences.
2338 unsigned DiffOperand = 0; // The operand that differs.
2339 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2340 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002341 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2342 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002343 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00002344 NumDifferences = 2;
2345 break;
2346 } else {
2347 if (NumDifferences++) break;
2348 DiffOperand = i;
2349 }
2350 }
2351
2352 if (NumDifferences == 0) // SAME GEP?
2353 return ReplaceInstUsesWith(I, // No comparison is needed here.
2354 ConstantBool::get(Cond == Instruction::SetEQ));
2355 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002356 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2357 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2358 if (LHSV->getType() != RHSV->getType())
2359 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2360 LHSV->getName()+".c"), I);
2361 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002362 }
2363 }
2364
Chris Lattner574da9b2005-01-13 20:14:25 +00002365 // Only lower this if the setcc is the only user of the GEP or if we expect
2366 // the result to fold to a constant!
2367 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2368 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2369 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2370 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2371 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2372 return new SetCondInst(Cond, L, R);
2373 }
2374 }
2375 return 0;
2376}
2377
2378
Chris Lattner484d3cf2005-04-24 06:59:08 +00002379Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002380 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00002381 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2382 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00002383
2384 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00002385 if (Op0 == Op1)
2386 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00002387
Chris Lattnere87597f2004-10-16 18:11:37 +00002388 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2389 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2390
Chris Lattner711b3402004-11-14 07:33:16 +00002391 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2392 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00002393 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2394 isa<ConstantPointerNull>(Op0)) &&
2395 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00002396 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00002397 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2398
2399 // setcc's with boolean values can always be turned into bitwise operations
2400 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00002401 switch (I.getOpcode()) {
2402 default: assert(0 && "Invalid setcc instruction!");
2403 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00002404 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00002405 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00002406 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00002407 }
Chris Lattner5dbef222004-08-11 00:50:51 +00002408 case Instruction::SetNE:
2409 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00002410
Chris Lattner5dbef222004-08-11 00:50:51 +00002411 case Instruction::SetGT:
2412 std::swap(Op0, Op1); // Change setgt -> setlt
2413 // FALL THROUGH
2414 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2415 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2416 InsertNewInstBefore(Not, I);
2417 return BinaryOperator::createAnd(Not, Op1);
2418 }
2419 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00002420 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00002421 // FALL THROUGH
2422 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2423 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2424 InsertNewInstBefore(Not, I);
2425 return BinaryOperator::createOr(Not, Op1);
2426 }
2427 }
Chris Lattner8b170942002-08-09 23:47:40 +00002428 }
2429
Chris Lattner2be51ae2004-06-09 04:24:29 +00002430 // See if we are doing a comparison between a constant and an instruction that
2431 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00002432 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002433 // Check to see if we are comparing against the minimum or maximum value...
2434 if (CI->isMinValue()) {
2435 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2436 return ReplaceInstUsesWith(I, ConstantBool::False);
2437 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2438 return ReplaceInstUsesWith(I, ConstantBool::True);
2439 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2440 return BinaryOperator::createSetEQ(Op0, Op1);
2441 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2442 return BinaryOperator::createSetNE(Op0, Op1);
2443
2444 } else if (CI->isMaxValue()) {
2445 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2446 return ReplaceInstUsesWith(I, ConstantBool::False);
2447 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2448 return ReplaceInstUsesWith(I, ConstantBool::True);
2449 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2450 return BinaryOperator::createSetEQ(Op0, Op1);
2451 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2452 return BinaryOperator::createSetNE(Op0, Op1);
2453
2454 // Comparing against a value really close to min or max?
2455 } else if (isMinValuePlusOne(CI)) {
2456 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2457 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2458 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2459 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2460
2461 } else if (isMaxValueMinusOne(CI)) {
2462 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2463 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2464 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2465 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2466 }
2467
2468 // If we still have a setle or setge instruction, turn it into the
2469 // appropriate setlt or setgt instruction. Since the border cases have
2470 // already been handled above, this requires little checking.
2471 //
2472 if (I.getOpcode() == Instruction::SetLE)
2473 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2474 if (I.getOpcode() == Instruction::SetGE)
2475 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2476
Chris Lattner3c6a0d42004-05-25 06:32:08 +00002477 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00002478 switch (LHSI->getOpcode()) {
2479 case Instruction::And:
2480 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2481 LHSI->getOperand(0)->hasOneUse()) {
2482 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2483 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2484 // happens a LOT in code produced by the C front-end, for bitfield
2485 // access.
2486 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2487 ConstantUInt *ShAmt;
2488 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2489 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2490 const Type *Ty = LHSI->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +00002491
Chris Lattner648e3bc2004-09-23 21:52:49 +00002492 // We can fold this as long as we can't shift unknown bits
2493 // into the mask. This can only happen with signed shift
2494 // rights, as they sign-extend.
2495 if (ShAmt) {
2496 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00002497 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00002498 if (!CanFold) {
2499 // To test for the bad case of the signed shr, see if any
2500 // of the bits shifted in could be tested after the mask.
Misha Brukmanfd939082005-04-21 23:48:37 +00002501 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00002502 Ty->getPrimitiveSizeInBits()-ShAmt->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002503 Constant *ShVal =
Chris Lattner648e3bc2004-09-23 21:52:49 +00002504 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2505 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2506 CanFold = true;
2507 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002508
Chris Lattner648e3bc2004-09-23 21:52:49 +00002509 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002510 Constant *NewCst;
2511 if (Shift->getOpcode() == Instruction::Shl)
2512 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2513 else
2514 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002515
Chris Lattner648e3bc2004-09-23 21:52:49 +00002516 // Check to see if we are shifting out any of the bits being
2517 // compared.
2518 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2519 // If we shifted bits out, the fold is not going to work out.
2520 // As a special case, check to see if this means that the
2521 // result is always true or false now.
2522 if (I.getOpcode() == Instruction::SetEQ)
2523 return ReplaceInstUsesWith(I, ConstantBool::False);
2524 if (I.getOpcode() == Instruction::SetNE)
2525 return ReplaceInstUsesWith(I, ConstantBool::True);
2526 } else {
2527 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002528 Constant *NewAndCST;
2529 if (Shift->getOpcode() == Instruction::Shl)
2530 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2531 else
2532 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2533 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002534 LHSI->setOperand(0, Shift->getOperand(0));
2535 WorkList.push_back(Shift); // Shift is dead.
2536 AddUsesToWorkList(I);
2537 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002538 }
2539 }
Chris Lattner457dd822004-06-09 07:59:58 +00002540 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002541 }
2542 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00002543
Chris Lattner18d19ca2004-09-28 18:22:15 +00002544 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2545 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2546 switch (I.getOpcode()) {
2547 default: break;
2548 case Instruction::SetEQ:
2549 case Instruction::SetNE: {
2550 // If we are comparing against bits always shifted out, the
2551 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002552 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00002553 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2554 if (Comp != CI) {// Comparing against a bit that we know is zero.
2555 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2556 Constant *Cst = ConstantBool::get(IsSetNE);
2557 return ReplaceInstUsesWith(I, Cst);
2558 }
2559
2560 if (LHSI->hasOneUse()) {
2561 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00002562 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner484d3cf2005-04-24 06:59:08 +00002563 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002564 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2565
2566 Constant *Mask;
2567 if (CI->getType()->isUnsigned()) {
2568 Mask = ConstantUInt::get(CI->getType(), Val);
2569 } else if (ShAmtVal != 0) {
2570 Mask = ConstantSInt::get(CI->getType(), Val);
2571 } else {
2572 Mask = ConstantInt::getAllOnesValue(CI->getType());
2573 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002574
Chris Lattner18d19ca2004-09-28 18:22:15 +00002575 Instruction *AndI =
2576 BinaryOperator::createAnd(LHSI->getOperand(0),
2577 Mask, LHSI->getName()+".mask");
2578 Value *And = InsertNewInstBefore(AndI, I);
2579 return new SetCondInst(I.getOpcode(), And,
2580 ConstantExpr::getUShr(CI, ShAmt));
2581 }
2582 }
2583 }
2584 }
2585 break;
2586
Chris Lattner83c4ec02004-09-27 19:29:18 +00002587 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002588 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002589 switch (I.getOpcode()) {
2590 default: break;
2591 case Instruction::SetEQ:
2592 case Instruction::SetNE: {
2593 // If we are comparing against bits always shifted out, the
2594 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002595 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00002596 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00002597
Chris Lattnerf63f6472004-09-27 16:18:50 +00002598 if (Comp != CI) {// Comparing against a bit that we know is zero.
2599 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2600 Constant *Cst = ConstantBool::get(IsSetNE);
2601 return ReplaceInstUsesWith(I, Cst);
2602 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002603
Chris Lattnerf63f6472004-09-27 16:18:50 +00002604 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00002605 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002606
Chris Lattnerf63f6472004-09-27 16:18:50 +00002607 // Otherwise strength reduce the shift into an and.
2608 uint64_t Val = ~0ULL; // All ones.
2609 Val <<= ShAmtVal; // Shift over to the right spot.
2610
2611 Constant *Mask;
2612 if (CI->getType()->isUnsigned()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002613 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +00002614 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00002615 Mask = ConstantUInt::get(CI->getType(), Val);
2616 } else {
2617 Mask = ConstantSInt::get(CI->getType(), Val);
2618 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002619
Chris Lattnerf63f6472004-09-27 16:18:50 +00002620 Instruction *AndI =
2621 BinaryOperator::createAnd(LHSI->getOperand(0),
2622 Mask, LHSI->getName()+".mask");
2623 Value *And = InsertNewInstBefore(AndI, I);
2624 return new SetCondInst(I.getOpcode(), And,
2625 ConstantExpr::getShl(CI, ShAmt));
2626 }
2627 break;
2628 }
2629 }
2630 }
2631 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002632
Chris Lattnera96879a2004-09-29 17:40:11 +00002633 case Instruction::Div:
2634 // Fold: (div X, C1) op C2 -> range check
2635 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2636 // Fold this div into the comparison, producing a range check.
2637 // Determine, based on the divide type, what the range is being
2638 // checked. If there is an overflow on the low or high side, remember
2639 // it, otherwise compute the range [low, hi) bounding the new value.
2640 bool LoOverflow = false, HiOverflow = 0;
2641 ConstantInt *LoBound = 0, *HiBound = 0;
2642
2643 ConstantInt *Prod;
2644 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2645
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002646 Instruction::BinaryOps Opcode = I.getOpcode();
2647
Chris Lattnera96879a2004-09-29 17:40:11 +00002648 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2649 } else if (LHSI->getType()->isUnsigned()) { // udiv
2650 LoBound = Prod;
2651 LoOverflow = ProdOV;
2652 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2653 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2654 if (CI->isNullValue()) { // (X / pos) op 0
2655 // Can't overflow.
2656 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2657 HiBound = DivRHS;
2658 } else if (isPositive(CI)) { // (X / pos) op pos
2659 LoBound = Prod;
2660 LoOverflow = ProdOV;
2661 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2662 } else { // (X / pos) op neg
2663 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2664 LoOverflow = AddWithOverflow(LoBound, Prod,
2665 cast<ConstantInt>(DivRHSH));
2666 HiBound = Prod;
2667 HiOverflow = ProdOV;
2668 }
2669 } else { // Divisor is < 0.
2670 if (CI->isNullValue()) { // (X / neg) op 0
2671 LoBound = AddOne(DivRHS);
2672 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2673 } else if (isPositive(CI)) { // (X / neg) op pos
2674 HiOverflow = LoOverflow = ProdOV;
2675 if (!LoOverflow)
2676 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2677 HiBound = AddOne(Prod);
2678 } else { // (X / neg) op neg
2679 LoBound = Prod;
2680 LoOverflow = HiOverflow = ProdOV;
2681 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2682 }
Chris Lattner340a05f2004-10-08 19:15:44 +00002683
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002684 // Dividing by a negate swaps the condition.
2685 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00002686 }
2687
2688 if (LoBound) {
2689 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002690 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002691 default: assert(0 && "Unhandled setcc opcode!");
2692 case Instruction::SetEQ:
2693 if (LoOverflow && HiOverflow)
2694 return ReplaceInstUsesWith(I, ConstantBool::False);
2695 else if (HiOverflow)
2696 return new SetCondInst(Instruction::SetGE, X, LoBound);
2697 else if (LoOverflow)
2698 return new SetCondInst(Instruction::SetLT, X, HiBound);
2699 else
2700 return InsertRangeTest(X, LoBound, HiBound, true, I);
2701 case Instruction::SetNE:
2702 if (LoOverflow && HiOverflow)
2703 return ReplaceInstUsesWith(I, ConstantBool::True);
2704 else if (HiOverflow)
2705 return new SetCondInst(Instruction::SetLT, X, LoBound);
2706 else if (LoOverflow)
2707 return new SetCondInst(Instruction::SetGE, X, HiBound);
2708 else
2709 return InsertRangeTest(X, LoBound, HiBound, false, I);
2710 case Instruction::SetLT:
2711 if (LoOverflow)
2712 return ReplaceInstUsesWith(I, ConstantBool::False);
2713 return new SetCondInst(Instruction::SetLT, X, LoBound);
2714 case Instruction::SetGT:
2715 if (HiOverflow)
2716 return ReplaceInstUsesWith(I, ConstantBool::False);
2717 return new SetCondInst(Instruction::SetGE, X, HiBound);
2718 }
2719 }
2720 }
2721 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002722 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002723
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002724 // Simplify seteq and setne instructions...
2725 if (I.getOpcode() == Instruction::SetEQ ||
2726 I.getOpcode() == Instruction::SetNE) {
2727 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2728
Chris Lattner00b1a7e2003-07-23 17:26:36 +00002729 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002730 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00002731 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2732 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00002733 case Instruction::Rem:
2734 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2735 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2736 BO->hasOneUse() &&
2737 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2738 if (unsigned L2 =
2739 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2740 const Type *UTy = BO->getType()->getUnsignedVersion();
2741 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2742 UTy, "tmp"), I);
2743 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2744 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2745 RHSCst, BO->getName()), I);
2746 return BinaryOperator::create(I.getOpcode(), NewRem,
2747 Constant::getNullValue(UTy));
2748 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002749 break;
Chris Lattner3571b722004-07-06 07:38:18 +00002750
Chris Lattner934754b2003-08-13 05:33:12 +00002751 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00002752 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2753 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00002754 if (BO->hasOneUse())
2755 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2756 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00002757 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002758 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2759 // efficiently invertible, or if the add has just this one use.
2760 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002761
Chris Lattner934754b2003-08-13 05:33:12 +00002762 if (Value *NegVal = dyn_castNegVal(BOp1))
2763 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2764 else if (Value *NegVal = dyn_castNegVal(BOp0))
2765 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00002766 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002767 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2768 BO->setName("");
2769 InsertNewInstBefore(Neg, I);
2770 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2771 }
2772 }
2773 break;
2774 case Instruction::Xor:
2775 // For the xor case, we can xor two constants together, eliminating
2776 // the explicit xor.
2777 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2778 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002779 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00002780
2781 // FALLTHROUGH
2782 case Instruction::Sub:
2783 // Replace (([sub|xor] A, B) != 0) with (A != B)
2784 if (CI->isNullValue())
2785 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2786 BO->getOperand(1));
2787 break;
2788
2789 case Instruction::Or:
2790 // If bits are being or'd in that are not present in the constant we
2791 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00002792 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00002793 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00002794 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002795 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002796 }
Chris Lattner934754b2003-08-13 05:33:12 +00002797 break;
2798
2799 case Instruction::And:
2800 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002801 // If bits are being compared against that are and'd out, then the
2802 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00002803 if (!ConstantExpr::getAnd(CI,
2804 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002805 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00002806
Chris Lattner457dd822004-06-09 07:59:58 +00002807 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00002808 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00002809 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2810 Instruction::SetNE, Op0,
2811 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00002812
Chris Lattner934754b2003-08-13 05:33:12 +00002813 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2814 // to be a signed value as appropriate.
2815 if (isSignBit(BOC)) {
2816 Value *X = BO->getOperand(0);
2817 // If 'X' is not signed, insert a cast now...
2818 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002819 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00002820 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00002821 }
2822 return new SetCondInst(isSetNE ? Instruction::SetLT :
2823 Instruction::SetGE, X,
2824 Constant::getNullValue(X->getType()));
2825 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002826
Chris Lattner83c4ec02004-09-27 19:29:18 +00002827 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002828 if (CI->isNullValue() && isHighOnes(BOC)) {
2829 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002830 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002831
2832 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00002833 if (NegX->getType()->isSigned()) {
2834 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2835 X = InsertCastBefore(X, DestTy, I);
2836 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002837 }
2838
2839 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00002840 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002841 }
2842
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002843 }
Chris Lattner934754b2003-08-13 05:33:12 +00002844 default: break;
2845 }
2846 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002847 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00002848 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002849 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2850 Value *CastOp = Cast->getOperand(0);
2851 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00002852 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002853 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00002854 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002855 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002856 "Source and destination signednesses should differ!");
2857 if (Cast->getType()->isSigned()) {
2858 // If this is a signed comparison, check for comparisons in the
2859 // vicinity of zero.
2860 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2861 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00002862 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00002863 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002864 else if (I.getOpcode() == Instruction::SetGT &&
2865 cast<ConstantSInt>(CI)->getValue() == -1)
2866 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00002867 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00002868 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002869 } else {
2870 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2871 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00002872 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002873 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00002874 return BinaryOperator::createSetGT(CastOp,
2875 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002876 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00002877 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002878 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00002879 return BinaryOperator::createSetLT(CastOp,
2880 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002881 }
2882 }
2883 }
Chris Lattner40f5d702003-06-04 05:10:11 +00002884 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002885 }
2886
Chris Lattner6970b662005-04-23 15:31:55 +00002887 // Handle setcc with constant RHS's that can be integer, FP or pointer.
2888 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2889 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2890 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00002891 case Instruction::GetElementPtr:
2892 if (RHSC->isNullValue()) {
2893 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
2894 bool isAllZeros = true;
2895 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
2896 if (!isa<Constant>(LHSI->getOperand(i)) ||
2897 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
2898 isAllZeros = false;
2899 break;
2900 }
2901 if (isAllZeros)
2902 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2903 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2904 }
2905 break;
2906
Chris Lattner6970b662005-04-23 15:31:55 +00002907 case Instruction::PHI:
2908 if (Instruction *NV = FoldOpIntoPhi(I))
2909 return NV;
2910 break;
2911 case Instruction::Select:
2912 // If either operand of the select is a constant, we can fold the
2913 // comparison into the select arms, which will cause one to be
2914 // constant folded and the select turned into a bitwise or.
2915 Value *Op1 = 0, *Op2 = 0;
2916 if (LHSI->hasOneUse()) {
2917 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2918 // Fold the known value into the constant operand.
2919 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2920 // Insert a new SetCC of the other select operand.
2921 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2922 LHSI->getOperand(2), RHSC,
2923 I.getName()), I);
2924 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2925 // Fold the known value into the constant operand.
2926 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2927 // Insert a new SetCC of the other select operand.
2928 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2929 LHSI->getOperand(1), RHSC,
2930 I.getName()), I);
2931 }
2932 }
Jeff Cohen9d809302005-04-23 21:38:35 +00002933
Chris Lattner6970b662005-04-23 15:31:55 +00002934 if (Op1)
2935 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2936 break;
2937 }
2938 }
2939
Chris Lattner574da9b2005-01-13 20:14:25 +00002940 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2941 if (User *GEP = dyn_castGetElementPtr(Op0))
2942 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2943 return NI;
2944 if (User *GEP = dyn_castGetElementPtr(Op1))
2945 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2946 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2947 return NI;
2948
Chris Lattnerde90b762003-11-03 04:25:02 +00002949 // Test to see if the operands of the setcc are casted versions of other
2950 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00002951 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2952 Value *CastOp0 = CI->getOperand(0);
2953 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00002954 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00002955 (I.getOpcode() == Instruction::SetEQ ||
2956 I.getOpcode() == Instruction::SetNE)) {
2957 // We keep moving the cast from the left operand over to the right
2958 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00002959 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00002960
Chris Lattnerde90b762003-11-03 04:25:02 +00002961 // If operand #1 is a cast instruction, see if we can eliminate it as
2962 // well.
Chris Lattner68708052003-11-03 05:17:03 +00002963 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2964 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00002965 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00002966 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002967
Chris Lattnerde90b762003-11-03 04:25:02 +00002968 // If Op1 is a constant, we can fold the cast into the constant.
2969 if (Op1->getType() != Op0->getType())
2970 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2971 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2972 } else {
2973 // Otherwise, cast the RHS right before the setcc
2974 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2975 InsertNewInstBefore(cast<Instruction>(Op1), I);
2976 }
2977 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2978 }
2979
Chris Lattner68708052003-11-03 05:17:03 +00002980 // Handle the special case of: setcc (cast bool to X), <cst>
2981 // This comes up when you have code like
2982 // int X = A < B;
2983 // if (X) ...
2984 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00002985 // with a constant or another cast from the same type.
2986 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
2987 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
2988 return R;
Chris Lattner68708052003-11-03 05:17:03 +00002989 }
Chris Lattner7e708292002-06-25 16:13:24 +00002990 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002991}
2992
Chris Lattner484d3cf2005-04-24 06:59:08 +00002993// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
2994// We only handle extending casts so far.
2995//
2996Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
2997 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
2998 const Type *SrcTy = LHSCIOp->getType();
2999 const Type *DestTy = SCI.getOperand(0)->getType();
3000 Value *RHSCIOp;
3001
3002 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00003003 return 0;
3004
Chris Lattner484d3cf2005-04-24 06:59:08 +00003005 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3006 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3007 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3008
3009 // Is this a sign or zero extension?
3010 bool isSignSrc = SrcTy->isSigned();
3011 bool isSignDest = DestTy->isSigned();
3012
3013 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3014 // Not an extension from the same type?
3015 RHSCIOp = CI->getOperand(0);
3016 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3017 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3018 // Compute the constant that would happen if we truncated to SrcTy then
3019 // reextended to DestTy.
3020 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3021
3022 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3023 RHSCIOp = Res;
3024 } else {
3025 // If the value cannot be represented in the shorter type, we cannot emit
3026 // a simple comparison.
3027 if (SCI.getOpcode() == Instruction::SetEQ)
3028 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3029 if (SCI.getOpcode() == Instruction::SetNE)
3030 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3031
Chris Lattner484d3cf2005-04-24 06:59:08 +00003032 // Evaluate the comparison for LT.
3033 Value *Result;
3034 if (DestTy->isSigned()) {
3035 // We're performing a signed comparison.
3036 if (isSignSrc) {
3037 // Signed extend and signed comparison.
3038 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3039 Result = ConstantBool::False;
3040 else
3041 Result = ConstantBool::True; // X < (large) --> true
3042 } else {
3043 // Unsigned extend and signed comparison.
3044 if (cast<ConstantSInt>(CI)->getValue() < 0)
3045 Result = ConstantBool::False;
3046 else
3047 Result = ConstantBool::True;
3048 }
3049 } else {
3050 // We're performing an unsigned comparison.
3051 if (!isSignSrc) {
3052 // Unsigned extend & compare -> always true.
3053 Result = ConstantBool::True;
3054 } else {
3055 // We're performing an unsigned comp with a sign extended value.
3056 // This is true if the input is >= 0. [aka >s -1]
3057 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3058 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3059 NegOne, SCI.getName()), SCI);
3060 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00003061 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003062
Chris Lattner484d3cf2005-04-24 06:59:08 +00003063 // Finally, return the value computed.
3064 if (SCI.getOpcode() == Instruction::SetLT) {
3065 return ReplaceInstUsesWith(SCI, Result);
3066 } else {
3067 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3068 if (Constant *CI = dyn_cast<Constant>(Result))
3069 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3070 else
3071 return BinaryOperator::createNot(Result);
3072 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003073 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00003074 } else {
3075 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00003076 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003077
Chris Lattner484d3cf2005-04-24 06:59:08 +00003078 // Okay, we have the two reduced sized operands. If we are doing a <,>
3079 // comparison, make sure we perform the compare with the same signedness as
3080 // the DestTy. We don't have to do this if the comparison is !=/== or if the
3081 // source is a bool.
3082 if (isSignSrc != isSignDest && SrcTy != Type::BoolTy &&
3083 SCI.getOpcode() != Instruction::SetEQ &&
3084 SCI.getOpcode() != Instruction::SetNE) {
3085 // Insert noop casts of the two operands to change the sign of the
3086 // comparison.
3087 const Type *NewSrcTy;
3088 if (isSignDest)
3089 NewSrcTy = SrcTy->getSignedVersion();
3090 else
3091 NewSrcTy = SrcTy->getUnsignedVersion();
3092
3093 // Insert the new casts.
3094 LHSCIOp = InsertNewInstBefore(new CastInst(LHSCIOp, NewSrcTy,
3095 LHSCIOp->getName()), SCI);
3096 if (Constant *RHSC = dyn_cast<Constant>(RHSCIOp))
3097 RHSCIOp = ConstantExpr::getCast(RHSC, NewSrcTy);
3098 else
3099 RHSCIOp = InsertNewInstBefore(new CastInst(RHSCIOp, NewSrcTy,
3100 RHSCIOp->getName()), SCI);
3101 }
3102
3103 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3104}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003105
Chris Lattnerea340052003-03-10 19:16:08 +00003106Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00003107 assert(I.getOperand(1)->getType() == Type::UByteTy);
3108 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003109 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110
3111 // shl X, 0 == X and shr X, 0 == X
3112 // shl 0, X == 0 and shr 0, X == 0
3113 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00003114 Op0 == Constant::getNullValue(Op0->getType()))
3115 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003116
Chris Lattnere87597f2004-10-16 18:11:37 +00003117 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3118 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00003119 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00003120 else // undef << X -> 0 AND undef >>u X -> 0
3121 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3122 }
3123 if (isa<UndefValue>(Op1)) {
3124 if (isLeftShift || I.getType()->isUnsigned())
3125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3126 else
3127 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3128 }
3129
Chris Lattnerdf17af12003-08-12 21:53:41 +00003130 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3131 if (!isLeftShift)
3132 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3133 if (CSI->isAllOnesValue())
3134 return ReplaceInstUsesWith(I, CSI);
3135
Chris Lattner2eefe512004-04-09 19:05:30 +00003136 // Try to fold constant and into select arguments.
3137 if (isa<Constant>(Op0))
3138 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003139 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003140 return R;
3141
Chris Lattner3f5b8772002-05-06 16:14:14 +00003142 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003143 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3144 // of a signed value.
3145 //
Chris Lattner484d3cf2005-04-24 06:59:08 +00003146 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner8adac752004-02-23 20:30:06 +00003147 if (CUI->getValue() >= TypeBits) {
3148 if (!Op0->getType()->isSigned() || isLeftShift)
3149 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3150 else {
3151 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3152 return &I;
3153 }
3154 }
Chris Lattnerf2836082002-09-10 23:04:09 +00003155
Chris Lattnere92d2f42003-08-13 04:18:28 +00003156 // ((X*C1) << C2) == (X * (C1 << C2))
3157 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3158 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3159 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00003160 return BinaryOperator::createMul(BO->getOperand(0),
3161 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanfd939082005-04-21 23:48:37 +00003162
Chris Lattner2eefe512004-04-09 19:05:30 +00003163 // Try to fold constant and into select arguments.
3164 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003165 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003166 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003167 if (isa<PHINode>(Op0))
3168 if (Instruction *NV = FoldOpIntoPhi(I))
3169 return NV;
Chris Lattnere92d2f42003-08-13 04:18:28 +00003170
Chris Lattner6e7ba452005-01-01 16:22:27 +00003171 if (Op0->hasOneUse()) {
3172 // If this is a SHL of a sign-extending cast, see if we can turn the input
3173 // into a zero extending cast (a simple strength reduction).
3174 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3175 const Type *SrcTy = CI->getOperand(0)->getType();
3176 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003177 SrcTy->getPrimitiveSizeInBits() <
3178 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00003179 // We can change it to a zero extension if we are shifting out all of
3180 // the sign extended bits. To check this, form a mask of all of the
3181 // sign extend bits, then shift them left and see if we have anything
3182 // left.
3183 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3184 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3185 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3186 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3187 // If the shift is nuking all of the sign bits, change this to a
3188 // zero extension cast. To do this, cast the cast input to
3189 // unsigned, then to the requested size.
3190 Value *CastOp = CI->getOperand(0);
3191 Instruction *NC =
3192 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3193 CI->getName()+".uns");
3194 NC = InsertNewInstBefore(NC, I);
3195 // Finally, insert a replacement for CI.
3196 NC = new CastInst(NC, CI->getType(), CI->getName());
3197 CI->setName("");
3198 NC = InsertNewInstBefore(NC, I);
3199 WorkList.push_back(CI); // Delete CI later.
3200 I.setOperand(0, NC);
3201 return &I; // The SHL operand was modified.
3202 }
3203 }
3204 }
3205
3206 // If the operand is an bitwise operator with a constant RHS, and the
3207 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003208 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3209 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3210 bool isValid = true; // Valid only for And, Or, Xor
3211 bool highBitSet = false; // Transform if high bit of constant set?
3212
3213 switch (Op0BO->getOpcode()) {
3214 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003215 case Instruction::Add:
3216 isValid = isLeftShift;
3217 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003218 case Instruction::Or:
3219 case Instruction::Xor:
3220 highBitSet = false;
3221 break;
3222 case Instruction::And:
3223 highBitSet = true;
3224 break;
3225 }
3226
3227 // If this is a signed shift right, and the high bit is modified
3228 // by the logical operation, do not perform the transformation.
3229 // The highBitSet boolean indicates the value of the high bit of
3230 // the constant which would cause it to be modified for this
3231 // operation.
3232 //
3233 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3234 uint64_t Val = Op0C->getRawValue();
3235 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3236 }
3237
3238 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00003239 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003240
3241 Instruction *NewShift =
3242 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3243 Op0BO->getName());
3244 Op0BO->setName("");
3245 InsertNewInstBefore(NewShift, I);
3246
3247 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3248 NewRHS);
3249 }
3250 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003251 }
Chris Lattnerdf17af12003-08-12 21:53:41 +00003252
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003253 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00003254 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00003255 if (ConstantUInt *ShiftAmt1C =
3256 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003257 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3258 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003259
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003260 // Check for (A << c1) << c2 and (A >> c1) >> c2
3261 if (I.getOpcode() == Op0SI->getOpcode()) {
3262 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner484d3cf2005-04-24 06:59:08 +00003263 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3264 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003265 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3266 ConstantUInt::get(Type::UByteTy, Amt));
3267 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003268
Chris Lattner943c7132003-07-24 18:38:56 +00003269 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3270 // signed types, we can only support the (A >> c1) << c2 configuration,
3271 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003272 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003273 // Calculate bitmask for what gets shifted off the edge...
3274 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00003275 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00003276 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003277 else
Chris Lattner48595f12004-06-10 02:07:29 +00003278 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanfd939082005-04-21 23:48:37 +00003279
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003280 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00003281 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3282 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003283 InsertNewInstBefore(Mask, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00003284
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003285 // Figure out what flavor of shift we should use...
3286 if (ShiftAmt1 == ShiftAmt2)
3287 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3288 else if (ShiftAmt1 < ShiftAmt2) {
3289 return new ShiftInst(I.getOpcode(), Mask,
3290 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3291 } else {
3292 return new ShiftInst(Op0SI->getOpcode(), Mask,
3293 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3294 }
3295 }
3296 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003297 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00003298
Chris Lattner3f5b8772002-05-06 16:14:14 +00003299 return 0;
3300}
3301
Chris Lattnerbee7e762004-07-20 00:59:32 +00003302enum CastType {
3303 Noop = 0,
3304 Truncate = 1,
3305 Signext = 2,
3306 Zeroext = 3
3307};
3308
3309/// getCastType - In the future, we will split the cast instruction into these
3310/// various types. Until then, we have to do the analysis here.
3311static CastType getCastType(const Type *Src, const Type *Dest) {
3312 assert(Src->isIntegral() && Dest->isIntegral() &&
3313 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00003314 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3315 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00003316
3317 if (SrcSize == DestSize) return Noop;
3318 if (SrcSize > DestSize) return Truncate;
3319 if (Src->isSigned()) return Signext;
3320 return Zeroext;
3321}
3322
Chris Lattner3f5b8772002-05-06 16:14:14 +00003323
Chris Lattnera1be5662002-05-02 17:06:02 +00003324// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3325// instruction.
3326//
Chris Lattner24c8e382003-07-24 17:35:25 +00003327static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00003328 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003329
Chris Lattner8fd217c2002-08-02 20:00:25 +00003330 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00003331 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00003332 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00003333 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00003334 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00003335
Chris Lattnere8a7e592004-07-21 04:27:24 +00003336 // If we are casting between pointer and integer types, treat pointers as
3337 // integers of the appropriate size for the code below.
3338 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3339 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3340 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00003341
Chris Lattnera1be5662002-05-02 17:06:02 +00003342 // Allow free casting and conversion of sizes as long as the sign doesn't
3343 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00003344 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00003345 CastType FirstCast = getCastType(SrcTy, MidTy);
3346 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00003347
Chris Lattnerbee7e762004-07-20 00:59:32 +00003348 // Capture the effect of these two casts. If the result is a legal cast,
3349 // the CastType is stored here, otherwise a special code is used.
3350 static const unsigned CastResult[] = {
3351 // First cast is noop
3352 0, 1, 2, 3,
3353 // First cast is a truncate
3354 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3355 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003356 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00003357 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003358 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00003359 };
3360
3361 unsigned Result = CastResult[FirstCast*4+SecondCast];
3362 switch (Result) {
3363 default: assert(0 && "Illegal table value!");
3364 case 0:
3365 case 1:
3366 case 2:
3367 case 3:
3368 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3369 // truncates, we could eliminate more casts.
3370 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3371 case 4:
3372 return false; // Not possible to eliminate this here.
3373 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00003374 // Sign or zero extend followed by truncate is always ok if the result
3375 // is a truncate or noop.
3376 CastType ResultCast = getCastType(SrcTy, DstTy);
3377 if (ResultCast == Noop || ResultCast == Truncate)
3378 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00003379 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00003380 // result will match the sign/zeroextendness of the result.
3381 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00003382 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00003383 }
Chris Lattnera1be5662002-05-02 17:06:02 +00003384 return false;
3385}
3386
Chris Lattner59a20772004-07-20 05:21:00 +00003387static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003388 if (V->getType() == Ty || isa<Constant>(V)) return false;
3389 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00003390 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3391 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00003392 return false;
3393 return true;
3394}
3395
3396/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3397/// InsertBefore instruction. This is specialized a bit to avoid inserting
3398/// casts that are known to not do anything...
3399///
3400Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3401 Instruction *InsertBefore) {
3402 if (V->getType() == DestTy) return V;
3403 if (Constant *C = dyn_cast<Constant>(V))
3404 return ConstantExpr::getCast(C, DestTy);
3405
3406 CastInst *CI = new CastInst(V, DestTy, V->getName());
3407 InsertNewInstBefore(CI, *InsertBefore);
3408 return CI;
3409}
Chris Lattnera1be5662002-05-02 17:06:02 +00003410
3411// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003412//
Chris Lattner7e708292002-06-25 16:13:24 +00003413Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00003414 Value *Src = CI.getOperand(0);
3415
Chris Lattnera1be5662002-05-02 17:06:02 +00003416 // If the user is casting a value to the same type, eliminate this cast
3417 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00003418 if (CI.getType() == Src->getType())
3419 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00003420
Chris Lattnere87597f2004-10-16 18:11:37 +00003421 if (isa<UndefValue>(Src)) // cast undef -> undef
3422 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3423
Chris Lattnera1be5662002-05-02 17:06:02 +00003424 // If casting the result of another cast instruction, try to eliminate this
3425 // one!
3426 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00003427 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3428 Value *A = CSrc->getOperand(0);
3429 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3430 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003431 // This instruction now refers directly to the cast's src operand. This
3432 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00003433 CI.setOperand(0, CSrc->getOperand(0));
3434 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00003435 }
3436
Chris Lattner8fd217c2002-08-02 20:00:25 +00003437 // If this is an A->B->A cast, and we are dealing with integral types, try
3438 // to convert this into a logical 'and' instruction.
3439 //
Misha Brukmanfd939082005-04-21 23:48:37 +00003440 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00003441 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00003442 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00003443 CSrc->getType()->getPrimitiveSizeInBits() <
3444 CI.getType()->getPrimitiveSizeInBits()&&
3445 A->getType()->getPrimitiveSizeInBits() ==
3446 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00003447 assert(CSrc->getType() != Type::ULongTy &&
3448 "Cannot have type bigger than ulong!");
Chris Lattnerf52d6812005-04-24 17:46:05 +00003449 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner6e7ba452005-01-01 16:22:27 +00003450 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3451 AndValue);
3452 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3453 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3454 if (And->getType() != CI.getType()) {
3455 And->setName(CSrc->getName()+".mask");
3456 InsertNewInstBefore(And, CI);
3457 And = new CastInst(And, CI.getType());
3458 }
3459 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00003460 }
3461 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003462
Chris Lattnera710ddc2004-05-25 04:29:21 +00003463 // If this is a cast to bool, turn it into the appropriate setne instruction.
3464 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00003465 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00003466 Constant::getNullValue(CI.getOperand(0)->getType()));
3467
Chris Lattner797249b2003-06-21 23:12:02 +00003468 // If casting the result of a getelementptr instruction with no offset, turn
3469 // this into a cast of the original pointer!
3470 //
Chris Lattner79d35b32003-06-23 21:59:52 +00003471 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00003472 bool AllZeroOperands = true;
3473 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3474 if (!isa<Constant>(GEP->getOperand(i)) ||
3475 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3476 AllZeroOperands = false;
3477 break;
3478 }
3479 if (AllZeroOperands) {
3480 CI.setOperand(0, GEP->getOperand(0));
3481 return &CI;
3482 }
3483 }
3484
Chris Lattnerbc61e662003-11-02 05:57:39 +00003485 // If we are casting a malloc or alloca to a pointer to a type of the same
3486 // size, rewrite the allocation instruction to allocate the "right" type.
3487 //
3488 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00003489 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00003490 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3491 // Get the type really allocated and the type casted to...
3492 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00003493 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00003494 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003495 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3496 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00003497
Chris Lattnerfae10102004-07-06 19:28:42 +00003498 // If the allocation is for an even multiple of the cast type size
3499 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003500 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00003501 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00003502 std::string Name = AI->getName(); AI->setName("");
3503 AllocationInst *New;
3504 if (isa<MallocInst>(AI))
3505 New = new MallocInst(CastElTy, Amt, Name);
3506 else
3507 New = new AllocaInst(CastElTy, Amt, Name);
3508 InsertNewInstBefore(New, *AI);
3509 return ReplaceInstUsesWith(CI, New);
3510 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00003511 }
3512 }
3513
Chris Lattner6e7ba452005-01-01 16:22:27 +00003514 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3515 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3516 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00003517 if (isa<PHINode>(Src))
3518 if (Instruction *NV = FoldOpIntoPhi(CI))
3519 return NV;
3520
Chris Lattner24c8e382003-07-24 17:35:25 +00003521 // If the source value is an instruction with only this use, we can attempt to
3522 // propagate the cast into the instruction. Also, only handle integral types
3523 // for now.
3524 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00003525 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00003526 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3527 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003528 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3529 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00003530
3531 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3532 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3533
3534 switch (SrcI->getOpcode()) {
3535 case Instruction::Add:
3536 case Instruction::Mul:
3537 case Instruction::And:
3538 case Instruction::Or:
3539 case Instruction::Xor:
3540 // If we are discarding information, or just changing the sign, rewrite.
3541 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3542 // Don't insert two casts if they cannot be eliminated. We allow two
3543 // casts to be inserted if the sizes are the same. This could only be
3544 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00003545 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3546 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003547 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3548 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3549 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3550 ->getOpcode(), Op0c, Op1c);
3551 }
3552 }
3553 break;
3554 case Instruction::Shl:
3555 // Allow changing the sign of the source operand. Do not allow changing
3556 // the size of the shift, UNLESS the shift amount is a constant. We
3557 // mush not change variable sized shifts to a smaller size, because it
3558 // is undefined to shift more bits out than exist in the value.
3559 if (DestBitSize == SrcBitSize ||
3560 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3561 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3562 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3563 }
3564 break;
Chris Lattner693787a2005-05-04 19:10:26 +00003565 case Instruction::SetNE:
Chris Lattner693787a2005-05-04 19:10:26 +00003566 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd1523802005-05-06 01:53:19 +00003567 if (Op1C->getRawValue() == 0) {
3568 // If the input only has the low bit set, simplify directly.
Chris Lattner693787a2005-05-04 19:10:26 +00003569 Constant *Not1 =
3570 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerd1523802005-05-06 01:53:19 +00003571 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner693787a2005-05-04 19:10:26 +00003572 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3573 if (CI.getType() == Op0->getType())
3574 return ReplaceInstUsesWith(CI, Op0);
3575 else
3576 return new CastInst(Op0, CI.getType());
3577 }
Chris Lattnerd1523802005-05-06 01:53:19 +00003578
3579 // If the input is an and with a single bit, shift then simplify.
3580 ConstantInt *AndRHS;
3581 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3582 if (AndRHS->getRawValue() &&
3583 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
3584 unsigned ShiftAmt = Log2(AndRHS->getRawValue());
3585 // Perform an unsigned shr by shiftamt. Convert input to
3586 // unsigned if it is signed.
3587 Value *In = Op0;
3588 if (In->getType()->isSigned())
3589 In = InsertNewInstBefore(new CastInst(In,
3590 In->getType()->getUnsignedVersion(), In->getName()),CI);
3591 // Insert the shift to put the result in the low bit.
3592 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3593 ConstantInt::get(Type::UByteTy, ShiftAmt),
3594 In->getName()+".lobit"), CI);
3595 std::cerr << "In1 = " << *Op0;
3596 std::cerr << "In2 = " << *CI.getOperand(0);
3597 std::cerr << "In3 = " << CI;
3598 if (CI.getType() == In->getType())
3599 return ReplaceInstUsesWith(CI, In);
3600 else
3601 return new CastInst(In, CI.getType());
3602 }
3603 }
3604 }
3605 break;
3606 case Instruction::SetEQ:
3607 // We if we are just checking for a seteq of a single bit and casting it
3608 // to an integer. If so, shift the bit to the appropriate place then
3609 // cast to integer to avoid the comparison.
3610 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3611 // Is Op1C a power of two or zero?
3612 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3613 // cast (X == 1) to int -> X iff X has only the low bit set.
3614 if (Op1C->getRawValue() == 1) {
3615 Constant *Not1 =
3616 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3617 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3618 if (CI.getType() == Op0->getType())
3619 return ReplaceInstUsesWith(CI, Op0);
3620 else
3621 return new CastInst(Op0, CI.getType());
3622 }
3623 }
Chris Lattner693787a2005-05-04 19:10:26 +00003624 }
3625 }
3626 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00003627 }
3628 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003629 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003630}
3631
Chris Lattnere576b912004-04-09 23:46:01 +00003632/// GetSelectFoldableOperands - We want to turn code that looks like this:
3633/// %C = or %A, %B
3634/// %D = select %cond, %C, %A
3635/// into:
3636/// %C = select %cond, %B, 0
3637/// %D = or %A, %C
3638///
3639/// Assuming that the specified instruction is an operand to the select, return
3640/// a bitmask indicating which operands of this instruction are foldable if they
3641/// equal the other incoming value of the select.
3642///
3643static unsigned GetSelectFoldableOperands(Instruction *I) {
3644 switch (I->getOpcode()) {
3645 case Instruction::Add:
3646 case Instruction::Mul:
3647 case Instruction::And:
3648 case Instruction::Or:
3649 case Instruction::Xor:
3650 return 3; // Can fold through either operand.
3651 case Instruction::Sub: // Can only fold on the amount subtracted.
3652 case Instruction::Shl: // Can only fold on the shift amount.
3653 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00003654 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00003655 default:
3656 return 0; // Cannot fold
3657 }
3658}
3659
3660/// GetSelectFoldableConstant - For the same transformation as the previous
3661/// function, return the identity constant that goes into the select.
3662static Constant *GetSelectFoldableConstant(Instruction *I) {
3663 switch (I->getOpcode()) {
3664 default: assert(0 && "This cannot happen!"); abort();
3665 case Instruction::Add:
3666 case Instruction::Sub:
3667 case Instruction::Or:
3668 case Instruction::Xor:
3669 return Constant::getNullValue(I->getType());
3670 case Instruction::Shl:
3671 case Instruction::Shr:
3672 return Constant::getNullValue(Type::UByteTy);
3673 case Instruction::And:
3674 return ConstantInt::getAllOnesValue(I->getType());
3675 case Instruction::Mul:
3676 return ConstantInt::get(I->getType(), 1);
3677 }
3678}
3679
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003680/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3681/// have the same opcode and only one use each. Try to simplify this.
3682Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3683 Instruction *FI) {
3684 if (TI->getNumOperands() == 1) {
3685 // If this is a non-volatile load or a cast from the same type,
3686 // merge.
3687 if (TI->getOpcode() == Instruction::Cast) {
3688 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3689 return 0;
3690 } else {
3691 return 0; // unknown unary op.
3692 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003693
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003694 // Fold this by inserting a select from the input values.
3695 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3696 FI->getOperand(0), SI.getName()+".v");
3697 InsertNewInstBefore(NewSI, SI);
3698 return new CastInst(NewSI, TI->getType());
3699 }
3700
3701 // Only handle binary operators here.
3702 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3703 return 0;
3704
3705 // Figure out if the operations have any operands in common.
3706 Value *MatchOp, *OtherOpT, *OtherOpF;
3707 bool MatchIsOpZero;
3708 if (TI->getOperand(0) == FI->getOperand(0)) {
3709 MatchOp = TI->getOperand(0);
3710 OtherOpT = TI->getOperand(1);
3711 OtherOpF = FI->getOperand(1);
3712 MatchIsOpZero = true;
3713 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3714 MatchOp = TI->getOperand(1);
3715 OtherOpT = TI->getOperand(0);
3716 OtherOpF = FI->getOperand(0);
3717 MatchIsOpZero = false;
3718 } else if (!TI->isCommutative()) {
3719 return 0;
3720 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3721 MatchOp = TI->getOperand(0);
3722 OtherOpT = TI->getOperand(1);
3723 OtherOpF = FI->getOperand(0);
3724 MatchIsOpZero = true;
3725 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3726 MatchOp = TI->getOperand(1);
3727 OtherOpT = TI->getOperand(0);
3728 OtherOpF = FI->getOperand(1);
3729 MatchIsOpZero = true;
3730 } else {
3731 return 0;
3732 }
3733
3734 // If we reach here, they do have operations in common.
3735 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3736 OtherOpF, SI.getName()+".v");
3737 InsertNewInstBefore(NewSI, SI);
3738
3739 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3740 if (MatchIsOpZero)
3741 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3742 else
3743 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3744 } else {
3745 if (MatchIsOpZero)
3746 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3747 else
3748 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3749 }
3750}
3751
Chris Lattner3d69f462004-03-12 05:52:32 +00003752Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003753 Value *CondVal = SI.getCondition();
3754 Value *TrueVal = SI.getTrueValue();
3755 Value *FalseVal = SI.getFalseValue();
3756
3757 // select true, X, Y -> X
3758 // select false, X, Y -> Y
3759 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00003760 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003761 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00003762 else {
3763 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003764 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00003765 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003766
3767 // select C, X, X -> X
3768 if (TrueVal == FalseVal)
3769 return ReplaceInstUsesWith(SI, TrueVal);
3770
Chris Lattnere87597f2004-10-16 18:11:37 +00003771 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3772 return ReplaceInstUsesWith(SI, FalseVal);
3773 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3774 return ReplaceInstUsesWith(SI, TrueVal);
3775 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3776 if (isa<Constant>(TrueVal))
3777 return ReplaceInstUsesWith(SI, TrueVal);
3778 else
3779 return ReplaceInstUsesWith(SI, FalseVal);
3780 }
3781
Chris Lattner0c199a72004-04-08 04:43:23 +00003782 if (SI.getType() == Type::BoolTy)
3783 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3784 if (C == ConstantBool::True) {
3785 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003786 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003787 } else {
3788 // Change: A = select B, false, C --> A = and !B, C
3789 Value *NotCond =
3790 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3791 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003792 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003793 }
3794 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3795 if (C == ConstantBool::False) {
3796 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003797 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003798 } else {
3799 // Change: A = select B, C, true --> A = or !B, C
3800 Value *NotCond =
3801 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3802 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003803 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003804 }
3805 }
3806
Chris Lattner2eefe512004-04-09 19:05:30 +00003807 // Selecting between two integer constants?
3808 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3809 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3810 // select C, 1, 0 -> cast C to int
3811 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3812 return new CastInst(CondVal, SI.getType());
3813 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3814 // select C, 0, 1 -> cast !C to int
3815 Value *NotCond =
3816 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00003817 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00003818 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00003819 }
Chris Lattner457dd822004-06-09 07:59:58 +00003820
3821 // If one of the constants is zero (we know they can't both be) and we
3822 // have a setcc instruction with zero, and we have an 'and' with the
3823 // non-constant value, eliminate this whole mess. This corresponds to
3824 // cases like this: ((X & 27) ? 27 : 0)
3825 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3826 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3827 if ((IC->getOpcode() == Instruction::SetEQ ||
3828 IC->getOpcode() == Instruction::SetNE) &&
3829 isa<ConstantInt>(IC->getOperand(1)) &&
3830 cast<Constant>(IC->getOperand(1))->isNullValue())
3831 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3832 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00003833 isa<ConstantInt>(ICA->getOperand(1)) &&
3834 (ICA->getOperand(1) == TrueValC ||
3835 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00003836 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3837 // Okay, now we know that everything is set up, we just don't
3838 // know whether we have a setne or seteq and whether the true or
3839 // false val is the zero.
3840 bool ShouldNotVal = !TrueValC->isNullValue();
3841 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3842 Value *V = ICA;
3843 if (ShouldNotVal)
3844 V = InsertNewInstBefore(BinaryOperator::create(
3845 Instruction::Xor, V, ICA->getOperand(1)), SI);
3846 return ReplaceInstUsesWith(SI, V);
3847 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003848 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00003849
3850 // See if we are selecting two values based on a comparison of the two values.
3851 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3852 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3853 // Transform (X == Y) ? X : Y -> Y
3854 if (SCI->getOpcode() == Instruction::SetEQ)
3855 return ReplaceInstUsesWith(SI, FalseVal);
3856 // Transform (X != Y) ? X : Y -> X
3857 if (SCI->getOpcode() == Instruction::SetNE)
3858 return ReplaceInstUsesWith(SI, TrueVal);
3859 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3860
3861 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3862 // Transform (X == Y) ? Y : X -> X
3863 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00003864 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003865 // Transform (X != Y) ? Y : X -> Y
3866 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00003867 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003868 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3869 }
3870 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003871
Chris Lattner87875da2005-01-13 22:52:24 +00003872 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3873 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3874 if (TI->hasOneUse() && FI->hasOneUse()) {
3875 bool isInverse = false;
3876 Instruction *AddOp = 0, *SubOp = 0;
3877
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003878 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3879 if (TI->getOpcode() == FI->getOpcode())
3880 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3881 return IV;
3882
3883 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3884 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00003885 if (TI->getOpcode() == Instruction::Sub &&
3886 FI->getOpcode() == Instruction::Add) {
3887 AddOp = FI; SubOp = TI;
3888 } else if (FI->getOpcode() == Instruction::Sub &&
3889 TI->getOpcode() == Instruction::Add) {
3890 AddOp = TI; SubOp = FI;
3891 }
3892
3893 if (AddOp) {
3894 Value *OtherAddOp = 0;
3895 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3896 OtherAddOp = AddOp->getOperand(1);
3897 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3898 OtherAddOp = AddOp->getOperand(0);
3899 }
3900
3901 if (OtherAddOp) {
3902 // So at this point we know we have:
3903 // select C, (add X, Y), (sub X, ?)
3904 // We can do the transform profitably if either 'Y' = '?' or '?' is
3905 // a constant.
3906 if (SubOp->getOperand(1) == AddOp ||
3907 isa<Constant>(SubOp->getOperand(1))) {
3908 Value *NegVal;
3909 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3910 NegVal = ConstantExpr::getNeg(C);
3911 } else {
3912 NegVal = InsertNewInstBefore(
3913 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3914 }
3915
Chris Lattner906ab502005-01-14 17:35:12 +00003916 Value *NewTrueOp = OtherAddOp;
Chris Lattner87875da2005-01-13 22:52:24 +00003917 Value *NewFalseOp = NegVal;
3918 if (AddOp != TI)
3919 std::swap(NewTrueOp, NewFalseOp);
3920 Instruction *NewSel =
3921 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanfd939082005-04-21 23:48:37 +00003922
Chris Lattner87875da2005-01-13 22:52:24 +00003923 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner906ab502005-01-14 17:35:12 +00003924 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00003925 }
3926 }
3927 }
3928 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003929
Chris Lattnere576b912004-04-09 23:46:01 +00003930 // See if we can fold the select into one of our operands.
3931 if (SI.getType()->isInteger()) {
3932 // See the comment above GetSelectFoldableOperands for a description of the
3933 // transformation we are doing here.
3934 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3935 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3936 !isa<Constant>(FalseVal))
3937 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3938 unsigned OpToFold = 0;
3939 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3940 OpToFold = 1;
3941 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3942 OpToFold = 2;
3943 }
3944
3945 if (OpToFold) {
3946 Constant *C = GetSelectFoldableConstant(TVI);
3947 std::string Name = TVI->getName(); TVI->setName("");
3948 Instruction *NewSel =
3949 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3950 Name);
3951 InsertNewInstBefore(NewSel, SI);
3952 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3953 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3954 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3955 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3956 else {
3957 assert(0 && "Unknown instruction!!");
3958 }
3959 }
3960 }
Chris Lattnera96879a2004-09-29 17:40:11 +00003961
Chris Lattnere576b912004-04-09 23:46:01 +00003962 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3963 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3964 !isa<Constant>(TrueVal))
3965 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3966 unsigned OpToFold = 0;
3967 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3968 OpToFold = 1;
3969 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3970 OpToFold = 2;
3971 }
3972
3973 if (OpToFold) {
3974 Constant *C = GetSelectFoldableConstant(FVI);
3975 std::string Name = FVI->getName(); FVI->setName("");
3976 Instruction *NewSel =
3977 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3978 Name);
3979 InsertNewInstBefore(NewSel, SI);
3980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3981 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3982 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3983 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3984 else {
3985 assert(0 && "Unknown instruction!!");
3986 }
3987 }
3988 }
3989 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00003990
3991 if (BinaryOperator::isNot(CondVal)) {
3992 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
3993 SI.setOperand(1, FalseVal);
3994 SI.setOperand(2, TrueVal);
3995 return &SI;
3996 }
3997
Chris Lattner3d69f462004-03-12 05:52:32 +00003998 return 0;
3999}
4000
4001
Chris Lattner9fe38862003-06-19 17:00:31 +00004002// CallInst simplification
4003//
4004Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004005 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4006 // visitCallSite.
Chris Lattner35b9e482004-10-12 04:52:52 +00004007 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4008 bool Changed = false;
4009
4010 // memmove/cpy/set of zero bytes is a noop.
4011 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4012 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4013
4014 // FIXME: Increase alignment here.
Misha Brukmanfd939082005-04-21 23:48:37 +00004015
Chris Lattner35b9e482004-10-12 04:52:52 +00004016 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4017 if (CI->getRawValue() == 1) {
4018 // Replace the instruction with just byte operations. We would
4019 // transform other cases to loads/stores, but we don't know if
4020 // alignment is sufficient.
4021 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004022 }
4023
Chris Lattner35b9e482004-10-12 04:52:52 +00004024 // If we have a memmove and the source operation is a constant global,
4025 // then the source and dest pointers can't alias, so we can change this
4026 // into a call to memcpy.
4027 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4028 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4029 if (GVSrc->isConstant()) {
4030 Module *M = CI.getParent()->getParent()->getParent();
4031 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4032 CI.getCalledFunction()->getFunctionType());
4033 CI.setOperand(0, MemCpy);
4034 Changed = true;
4035 }
4036
4037 if (Changed) return &CI;
Chris Lattner954f66a2004-11-18 21:41:39 +00004038 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4039 // If this stoppoint is at the same source location as the previous
4040 // stoppoint in the chain, it is not needed.
4041 if (DbgStopPointInst *PrevSPI =
4042 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4043 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4044 SPI->getColNo() == PrevSPI->getColNo()) {
4045 SPI->replaceAllUsesWith(PrevSPI);
4046 return EraseInstFromFunction(CI);
4047 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004048 }
4049
Chris Lattnera44d8a22003-10-07 22:32:43 +00004050 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00004051}
4052
4053// InvokeInst simplification
4054//
4055Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004056 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004057}
4058
Chris Lattnera44d8a22003-10-07 22:32:43 +00004059// visitCallSite - Improvements for call and invoke instructions.
4060//
4061Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004062 bool Changed = false;
4063
4064 // If the callee is a constexpr cast of a function, attempt to move the cast
4065 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004066 if (transformConstExprCastCall(CS)) return 0;
4067
Chris Lattner6c266db2003-10-07 22:54:13 +00004068 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004069
Chris Lattner17be6352004-10-18 02:59:09 +00004070 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4071 // This instruction is not reachable, just remove it. We insert a store to
4072 // undef so that we know that this code is not reachable, despite the fact
4073 // that we can't modify the CFG here.
4074 new StoreInst(ConstantBool::True,
4075 UndefValue::get(PointerType::get(Type::BoolTy)),
4076 CS.getInstruction());
4077
4078 if (!CS.getInstruction()->use_empty())
4079 CS.getInstruction()->
4080 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4081
4082 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4083 // Don't break the CFG, insert a dummy cond branch.
4084 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4085 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004086 }
Chris Lattner17be6352004-10-18 02:59:09 +00004087 return EraseInstFromFunction(*CS.getInstruction());
4088 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004089
Chris Lattner6c266db2003-10-07 22:54:13 +00004090 const PointerType *PTy = cast<PointerType>(Callee->getType());
4091 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4092 if (FTy->isVarArg()) {
4093 // See if we can optimize any arguments passed through the varargs area of
4094 // the call.
4095 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4096 E = CS.arg_end(); I != E; ++I)
4097 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4098 // If this cast does not effect the value passed through the varargs
4099 // area, we can eliminate the use of the cast.
4100 Value *Op = CI->getOperand(0);
4101 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4102 *I = Op;
4103 Changed = true;
4104 }
4105 }
4106 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004107
Chris Lattner6c266db2003-10-07 22:54:13 +00004108 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004109}
4110
Chris Lattner9fe38862003-06-19 17:00:31 +00004111// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4112// attempt to move the cast to the arguments of the call/invoke.
4113//
4114bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4115 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4116 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00004117 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004118 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004119 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004120 Instruction *Caller = CS.getInstruction();
4121
4122 // Okay, this is a cast from a function to a different type. Unless doing so
4123 // would cause a type conversion of one of our arguments, change this call to
4124 // be a direct call with arguments casted to the appropriate types.
4125 //
4126 const FunctionType *FT = Callee->getFunctionType();
4127 const Type *OldRetTy = Caller->getType();
4128
Chris Lattnerf78616b2004-01-14 06:06:08 +00004129 // Check to see if we are changing the return type...
4130 if (OldRetTy != FT->getReturnType()) {
4131 if (Callee->isExternal() &&
4132 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4133 !Caller->use_empty())
4134 return false; // Cannot transform this return value...
4135
4136 // If the callsite is an invoke instruction, and the return value is used by
4137 // a PHI node in a successor, we cannot change the return type of the call
4138 // because there is no place to put the cast instruction (without breaking
4139 // the critical edge). Bail out in this case.
4140 if (!Caller->use_empty())
4141 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4142 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4143 UI != E; ++UI)
4144 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4145 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004146 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004147 return false;
4148 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004149
4150 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4151 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004152
Chris Lattner9fe38862003-06-19 17:00:31 +00004153 CallSite::arg_iterator AI = CS.arg_begin();
4154 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4155 const Type *ParamTy = FT->getParamType(i);
4156 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00004157 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004158 }
4159
4160 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4161 Callee->isExternal())
4162 return false; // Do not delete arguments unless we have a function body...
4163
4164 // Okay, we decided that this is a safe thing to do: go ahead and start
4165 // inserting cast instructions as necessary...
4166 std::vector<Value*> Args;
4167 Args.reserve(NumActualArgs);
4168
4169 AI = CS.arg_begin();
4170 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4171 const Type *ParamTy = FT->getParamType(i);
4172 if ((*AI)->getType() == ParamTy) {
4173 Args.push_back(*AI);
4174 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00004175 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4176 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00004177 }
4178 }
4179
4180 // If the function takes more arguments than the call was taking, add them
4181 // now...
4182 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4183 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4184
4185 // If we are removing arguments to the function, emit an obnoxious warning...
4186 if (FT->getNumParams() < NumActualArgs)
4187 if (!FT->isVarArg()) {
4188 std::cerr << "WARNING: While resolving call to function '"
4189 << Callee->getName() << "' arguments were dropped!\n";
4190 } else {
4191 // Add all of the arguments in their promoted form to the arg list...
4192 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4193 const Type *PTy = getPromotedType((*AI)->getType());
4194 if (PTy != (*AI)->getType()) {
4195 // Must promote to pass through va_arg area!
4196 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4197 InsertNewInstBefore(Cast, *Caller);
4198 Args.push_back(Cast);
4199 } else {
4200 Args.push_back(*AI);
4201 }
4202 }
4203 }
4204
4205 if (FT->getReturnType() == Type::VoidTy)
4206 Caller->setName(""); // Void type should not have a name...
4207
4208 Instruction *NC;
4209 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004210 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00004211 Args, Caller->getName(), Caller);
4212 } else {
4213 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4214 }
4215
4216 // Insert a cast of the return type as necessary...
4217 Value *NV = NC;
4218 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4219 if (NV->getType() != Type::VoidTy) {
4220 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004221
4222 // If this is an invoke instruction, we should insert it after the first
4223 // non-phi, instruction in the normal successor block.
4224 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4225 BasicBlock::iterator I = II->getNormalDest()->begin();
4226 while (isa<PHINode>(I)) ++I;
4227 InsertNewInstBefore(NC, *I);
4228 } else {
4229 // Otherwise, it's a call, just insert cast right after the call instr
4230 InsertNewInstBefore(NC, *Caller);
4231 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004232 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004233 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00004234 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004235 }
4236 }
4237
4238 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4239 Caller->replaceAllUsesWith(NV);
4240 Caller->getParent()->getInstList().erase(Caller);
4241 removeFromWorkList(Caller);
4242 return true;
4243}
4244
4245
Chris Lattnerbac32862004-11-14 19:13:23 +00004246// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4247// operator and they all are only used by the PHI, PHI together their
4248// inputs, and do the operation once, to the result of the PHI.
4249Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4250 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4251
4252 // Scan the instruction, looking for input operations that can be folded away.
4253 // If all input operands to the phi are the same instruction (e.g. a cast from
4254 // the same type or "+42") we can pull the operation through the PHI, reducing
4255 // code size and simplifying code.
4256 Constant *ConstantOp = 0;
4257 const Type *CastSrcTy = 0;
4258 if (isa<CastInst>(FirstInst)) {
4259 CastSrcTy = FirstInst->getOperand(0)->getType();
4260 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4261 // Can fold binop or shift if the RHS is a constant.
4262 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4263 if (ConstantOp == 0) return 0;
4264 } else {
4265 return 0; // Cannot fold this operation.
4266 }
4267
4268 // Check to see if all arguments are the same operation.
4269 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4270 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4271 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4272 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4273 return 0;
4274 if (CastSrcTy) {
4275 if (I->getOperand(0)->getType() != CastSrcTy)
4276 return 0; // Cast operation must match.
4277 } else if (I->getOperand(1) != ConstantOp) {
4278 return 0;
4279 }
4280 }
4281
4282 // Okay, they are all the same operation. Create a new PHI node of the
4283 // correct type, and PHI together all of the LHS's of the instructions.
4284 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4285 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00004286 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00004287
4288 Value *InVal = FirstInst->getOperand(0);
4289 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00004290
4291 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00004292 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4293 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4294 if (NewInVal != InVal)
4295 InVal = 0;
4296 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4297 }
4298
4299 Value *PhiVal;
4300 if (InVal) {
4301 // The new PHI unions all of the same values together. This is really
4302 // common, so we handle it intelligently here for compile-time speed.
4303 PhiVal = InVal;
4304 delete NewPN;
4305 } else {
4306 InsertNewInstBefore(NewPN, PN);
4307 PhiVal = NewPN;
4308 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004309
Chris Lattnerbac32862004-11-14 19:13:23 +00004310 // Insert and return the new operation.
4311 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004312 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00004313 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004314 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004315 else
4316 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00004317 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004318}
Chris Lattnera1be5662002-05-02 17:06:02 +00004319
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004320/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4321/// that is dead.
4322static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4323 if (PN->use_empty()) return true;
4324 if (!PN->hasOneUse()) return false;
4325
4326 // Remember this node, and if we find the cycle, return.
4327 if (!PotentiallyDeadPHIs.insert(PN).second)
4328 return true;
4329
4330 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4331 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004332
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004333 return false;
4334}
4335
Chris Lattner473945d2002-05-06 18:06:38 +00004336// PHINode simplification
4337//
Chris Lattner7e708292002-06-25 16:13:24 +00004338Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerc30bda72004-10-17 21:22:38 +00004339 if (Value *V = hasConstantValue(&PN)) {
4340 // If V is an instruction, we have to be certain that it dominates PN.
4341 // However, because we don't have dom info, we can't do a perfect job.
4342 if (Instruction *I = dyn_cast<Instruction>(V)) {
4343 // We know that the instruction dominates the PHI if there are no undef
4344 // values coming in.
Chris Lattner77bcee72004-10-18 01:48:31 +00004345 if (I->getParent() != &I->getParent()->getParent()->front() ||
4346 isa<InvokeInst>(I))
Chris Lattnerca459302004-10-17 21:31:34 +00004347 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4348 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4349 V = 0;
4350 break;
4351 }
Chris Lattnerc30bda72004-10-17 21:22:38 +00004352 }
4353
4354 if (V)
4355 return ReplaceInstUsesWith(PN, V);
4356 }
Chris Lattner7059f2e2004-02-16 05:07:08 +00004357
4358 // If the only user of this instruction is a cast instruction, and all of the
4359 // incoming values are constants, change this PHI to merge together the casted
4360 // constants.
4361 if (PN.hasOneUse())
4362 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4363 if (CI->getType() != PN.getType()) { // noop casts will be folded
4364 bool AllConstant = true;
4365 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4366 if (!isa<Constant>(PN.getIncomingValue(i))) {
4367 AllConstant = false;
4368 break;
4369 }
4370 if (AllConstant) {
4371 // Make a new PHI with all casted values.
4372 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4373 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4374 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4375 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4376 PN.getIncomingBlock(i));
4377 }
4378
4379 // Update the cast instruction.
4380 CI->setOperand(0, New);
4381 WorkList.push_back(CI); // revisit the cast instruction to fold.
4382 WorkList.push_back(New); // Make sure to revisit the new Phi
4383 return &PN; // PN is now dead!
4384 }
4385 }
Chris Lattnerbac32862004-11-14 19:13:23 +00004386
4387 // If all PHI operands are the same operation, pull them through the PHI,
4388 // reducing code size.
4389 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4390 PN.getIncomingValue(0)->hasOneUse())
4391 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4392 return Result;
4393
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004394 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4395 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4396 // PHI)... break the cycle.
4397 if (PN.hasOneUse())
4398 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4399 std::set<PHINode*> PotentiallyDeadPHIs;
4400 PotentiallyDeadPHIs.insert(&PN);
4401 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4402 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4403 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004404
Chris Lattner60921c92003-12-19 05:58:40 +00004405 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00004406}
4407
Chris Lattner28977af2004-04-05 01:30:19 +00004408static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4409 Instruction *InsertPoint,
4410 InstCombiner *IC) {
4411 unsigned PS = IC->getTargetData().getPointerSize();
4412 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00004413 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4414 // We must insert a cast to ensure we sign-extend.
4415 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4416 V->getName()), *InsertPoint);
4417 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4418 *InsertPoint);
4419}
4420
Chris Lattnera1be5662002-05-02 17:06:02 +00004421
Chris Lattner7e708292002-06-25 16:13:24 +00004422Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00004423 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00004424 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00004425 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004426 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00004427 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004428
Chris Lattnere87597f2004-10-16 18:11:37 +00004429 if (isa<UndefValue>(GEP.getOperand(0)))
4430 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4431
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004432 bool HasZeroPointerIndex = false;
4433 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4434 HasZeroPointerIndex = C->isNullValue();
4435
4436 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00004437 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00004438
Chris Lattner28977af2004-04-05 01:30:19 +00004439 // Eliminate unneeded casts for indices.
4440 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004441 gep_type_iterator GTI = gep_type_begin(GEP);
4442 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4443 if (isa<SequentialType>(*GTI)) {
4444 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4445 Value *Src = CI->getOperand(0);
4446 const Type *SrcTy = Src->getType();
4447 const Type *DestTy = CI->getType();
4448 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004449 if (SrcTy->getPrimitiveSizeInBits() ==
4450 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004451 // We can always eliminate a cast from ulong or long to the other.
4452 // We can always eliminate a cast from uint to int or the other on
4453 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004454 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004455 MadeChange = true;
4456 GEP.setOperand(i, Src);
4457 }
4458 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4459 SrcTy->getPrimitiveSize() == 4) {
4460 // We can always eliminate a cast from int to [u]long. We can
4461 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4462 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00004463 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00004464 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004465 MadeChange = true;
4466 GEP.setOperand(i, Src);
4467 }
Chris Lattner28977af2004-04-05 01:30:19 +00004468 }
4469 }
4470 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004471 // If we are using a wider index than needed for this platform, shrink it
4472 // to what we need. If the incoming value needs a cast instruction,
4473 // insert it. This explicit cast can make subsequent optimizations more
4474 // obvious.
4475 Value *Op = GEP.getOperand(i);
4476 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00004477 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00004478 GEP.setOperand(i, ConstantExpr::getCast(C,
4479 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00004480 MadeChange = true;
4481 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004482 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4483 Op->getName()), GEP);
4484 GEP.setOperand(i, Op);
4485 MadeChange = true;
4486 }
Chris Lattner67769e52004-07-20 01:48:15 +00004487
4488 // If this is a constant idx, make sure to canonicalize it to be a signed
4489 // operand, otherwise CSE and other optimizations are pessimized.
4490 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4491 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4492 CUI->getType()->getSignedVersion()));
4493 MadeChange = true;
4494 }
Chris Lattner28977af2004-04-05 01:30:19 +00004495 }
4496 if (MadeChange) return &GEP;
4497
Chris Lattner90ac28c2002-08-02 19:29:35 +00004498 // Combine Indices - If the source pointer to this getelementptr instruction
4499 // is a getelementptr instruction, combine the indices of the two
4500 // getelementptr instructions into a single instruction.
4501 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00004502 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00004503 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00004504 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00004505
4506 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00004507 // Note that if our source is a gep chain itself that we wait for that
4508 // chain to be resolved before we perform this transformation. This
4509 // avoids us creating a TON of code in some cases.
4510 //
4511 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4512 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4513 return 0; // Wait until our source is folded to completion.
4514
Chris Lattner90ac28c2002-08-02 19:29:35 +00004515 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004516
4517 // Find out whether the last index in the source GEP is a sequential idx.
4518 bool EndsWithSequential = false;
4519 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4520 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004521 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00004522
Chris Lattner90ac28c2002-08-02 19:29:35 +00004523 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004524 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004525 // Replace: gep (gep %P, long B), long A, ...
4526 // With: T = long A+B; gep %P, T, ...
4527 //
Chris Lattner620ce142004-05-07 22:09:22 +00004528 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00004529 if (SO1 == Constant::getNullValue(SO1->getType())) {
4530 Sum = GO1;
4531 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4532 Sum = SO1;
4533 } else {
4534 // If they aren't the same type, convert both to an integer of the
4535 // target's pointer size.
4536 if (SO1->getType() != GO1->getType()) {
4537 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4538 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4539 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4540 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4541 } else {
4542 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00004543 if (SO1->getType()->getPrimitiveSize() == PS) {
4544 // Convert GO1 to SO1's type.
4545 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4546
4547 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4548 // Convert SO1 to GO1's type.
4549 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4550 } else {
4551 const Type *PT = TD->getIntPtrType();
4552 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4553 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4554 }
4555 }
4556 }
Chris Lattner620ce142004-05-07 22:09:22 +00004557 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4558 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4559 else {
Chris Lattner48595f12004-06-10 02:07:29 +00004560 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4561 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00004562 }
Chris Lattner28977af2004-04-05 01:30:19 +00004563 }
Chris Lattner620ce142004-05-07 22:09:22 +00004564
4565 // Recycle the GEP we already have if possible.
4566 if (SrcGEPOperands.size() == 2) {
4567 GEP.setOperand(0, SrcGEPOperands[0]);
4568 GEP.setOperand(1, Sum);
4569 return &GEP;
4570 } else {
4571 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4572 SrcGEPOperands.end()-1);
4573 Indices.push_back(Sum);
4574 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4575 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004576 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00004577 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004578 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004579 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00004580 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4581 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004582 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4583 }
4584
4585 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00004586 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00004587
Chris Lattner620ce142004-05-07 22:09:22 +00004588 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00004589 // GEP of global variable. If all of the indices for this GEP are
4590 // constants, we can promote this to a constexpr instead of an instruction.
4591
4592 // Scan for nonconstants...
4593 std::vector<Constant*> Indices;
4594 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4595 for (; I != E && isa<Constant>(*I); ++I)
4596 Indices.push_back(cast<Constant>(*I));
4597
4598 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00004599 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00004600
4601 // Replace all uses of the GEP with the new constexpr...
4602 return ReplaceInstUsesWith(GEP, CE);
4603 }
Chris Lattner620ce142004-05-07 22:09:22 +00004604 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004605 if (CE->getOpcode() == Instruction::Cast) {
4606 if (HasZeroPointerIndex) {
4607 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4608 // into : GEP [10 x ubyte]* X, long 0, ...
4609 //
4610 // This occurs when the program declares an array extern like "int X[];"
4611 //
4612 Constant *X = CE->getOperand(0);
4613 const PointerType *CPTy = cast<PointerType>(CE->getType());
4614 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4615 if (const ArrayType *XATy =
4616 dyn_cast<ArrayType>(XTy->getElementType()))
4617 if (const ArrayType *CATy =
4618 dyn_cast<ArrayType>(CPTy->getElementType()))
4619 if (CATy->getElementType() == XATy->getElementType()) {
4620 // At this point, we know that the cast source type is a pointer
4621 // to an array of the same type as the destination pointer
4622 // array. Because the array type is never stepped over (there
4623 // is a leading zero) we can fold the cast into this GEP.
4624 GEP.setOperand(0, X);
4625 return &GEP;
4626 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004627 } else if (GEP.getNumOperands() == 2 &&
4628 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner646641e2004-11-27 17:55:46 +00004629 // Transform things like:
4630 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4631 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4632 Constant *X = CE->getOperand(0);
4633 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4634 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4635 if (isa<ArrayType>(SrcElTy) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004636 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
Chris Lattner646641e2004-11-27 17:55:46 +00004637 TD->getTypeSize(ResElTy)) {
4638 Value *V = InsertNewInstBefore(
4639 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4640 GEP.getOperand(1), GEP.getName()), GEP);
4641 return new CastInst(V, GEP.getType());
4642 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004643 }
4644 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004645 }
4646
Chris Lattner8a2a3112001-12-14 16:52:21 +00004647 return 0;
4648}
4649
Chris Lattner0864acf2002-11-04 16:18:53 +00004650Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4651 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4652 if (AI.isArrayAllocation()) // Check C != 1
4653 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4654 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00004655 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00004656
4657 // Create and insert the replacement instruction...
4658 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00004659 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00004660 else {
4661 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00004662 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00004663 }
Chris Lattner7c881df2004-03-19 06:08:10 +00004664
4665 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00004666
Chris Lattner0864acf2002-11-04 16:18:53 +00004667 // Scan to the end of the allocation instructions, to skip over a block of
4668 // allocas if possible...
4669 //
4670 BasicBlock::iterator It = New;
4671 while (isa<AllocationInst>(*It)) ++It;
4672
4673 // Now that I is pointing to the first non-allocation-inst in the block,
4674 // insert our getelementptr instruction...
4675 //
Chris Lattner693787a2005-05-04 19:10:26 +00004676 Value *NullIdx = Constant::getNullValue(Type::IntTy);
4677 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
4678 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00004679
4680 // Now make everything use the getelementptr instead of the original
4681 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00004682 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00004683 } else if (isa<UndefValue>(AI.getArraySize())) {
4684 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00004685 }
Chris Lattner7c881df2004-03-19 06:08:10 +00004686
4687 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4688 // Note that we only do this for alloca's, because malloc should allocate and
4689 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00004690 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00004691 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00004692 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4693
Chris Lattner0864acf2002-11-04 16:18:53 +00004694 return 0;
4695}
4696
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004697Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4698 Value *Op = FI.getOperand(0);
4699
4700 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4701 if (CastInst *CI = dyn_cast<CastInst>(Op))
4702 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4703 FI.setOperand(0, CI->getOperand(0));
4704 return &FI;
4705 }
4706
Chris Lattner17be6352004-10-18 02:59:09 +00004707 // free undef -> unreachable.
4708 if (isa<UndefValue>(Op)) {
4709 // Insert a new store to null because we cannot modify the CFG here.
4710 new StoreInst(ConstantBool::True,
4711 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4712 return EraseInstFromFunction(FI);
4713 }
4714
Chris Lattner6160e852004-02-28 04:57:37 +00004715 // If we have 'free null' delete the instruction. This can happen in stl code
4716 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00004717 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004718 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00004719
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004720 return 0;
4721}
4722
4723
Chris Lattner833b8a42003-06-26 05:06:25 +00004724/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4725/// constantexpr, return the constant value being addressed by the constant
4726/// expression, or null if something is funny.
4727///
4728static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00004729 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00004730 return 0; // Do not allow stepping over the value!
4731
4732 // Loop over all of the operands, tracking down which value we are
4733 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00004734 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4735 for (++I; I != E; ++I)
4736 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4737 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4738 assert(CU->getValue() < STy->getNumElements() &&
4739 "Struct index out of range!");
Chris Lattner652f3cf2005-01-08 19:42:22 +00004740 unsigned El = (unsigned)CU->getValue();
Chris Lattnere1368ae2004-05-27 17:30:27 +00004741 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00004742 C = CS->getOperand(El);
Chris Lattnere1368ae2004-05-27 17:30:27 +00004743 } else if (isa<ConstantAggregateZero>(C)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00004744 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattnere87597f2004-10-16 18:11:37 +00004745 } else if (isa<UndefValue>(C)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00004746 C = UndefValue::get(STy->getElementType(El));
Chris Lattnere1368ae2004-05-27 17:30:27 +00004747 } else {
4748 return 0;
4749 }
4750 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4751 const ArrayType *ATy = cast<ArrayType>(*I);
4752 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4753 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattner652f3cf2005-01-08 19:42:22 +00004754 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00004755 else if (isa<ConstantAggregateZero>(C))
4756 C = Constant::getNullValue(ATy->getElementType());
Chris Lattnere87597f2004-10-16 18:11:37 +00004757 else if (isa<UndefValue>(C))
4758 C = UndefValue::get(ATy->getElementType());
Chris Lattnere1368ae2004-05-27 17:30:27 +00004759 else
4760 return 0;
4761 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00004762 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00004763 }
Chris Lattner833b8a42003-06-26 05:06:25 +00004764 return C;
4765}
4766
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00004767/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00004768static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4769 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00004770 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00004771
4772 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00004773 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00004774 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00004775
4776 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4777 // If the source is an array, the code below will not succeed. Check to
4778 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4779 // constants.
4780 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4781 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4782 if (ASrcTy->getNumElements() != 0) {
4783 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4784 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4785 SrcTy = cast<PointerType>(CastOp->getType());
4786 SrcPTy = SrcTy->getElementType();
4787 }
4788
4789 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00004790 // Do not allow turning this into a load of an integer, which is then
4791 // casted to a pointer, this pessimizes pointer analysis a lot.
4792 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004793 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00004794 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004795
Chris Lattnerf9527852005-01-31 04:50:46 +00004796 // Okay, we are casting from one integer or pointer type to another of
4797 // the same size. Instead of casting the pointer before the load, cast
4798 // the result of the loaded value.
4799 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4800 CI->getName(),
4801 LI.isVolatile()),LI);
4802 // Now cast the result of the load.
4803 return new CastInst(NewLoad, LI.getType());
4804 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00004805 }
4806 }
4807 return 0;
4808}
4809
Chris Lattnerc10aced2004-09-19 18:43:46 +00004810/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00004811/// from this value cannot trap. If it is not obviously safe to load from the
4812/// specified pointer, we do a quick local scan of the basic block containing
4813/// ScanFrom, to determine if the address is already accessed.
4814static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4815 // If it is an alloca or global variable, it is always safe to load from.
4816 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4817
4818 // Otherwise, be a little bit agressive by scanning the local block where we
4819 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00004820 // from/to. If so, the previous load or store would have already trapped,
4821 // so there is no harm doing an extra load (also, CSE will later eliminate
4822 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00004823 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4824
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00004825 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00004826 --BBI;
4827
4828 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4829 if (LI->getOperand(0) == V) return true;
4830 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4831 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00004832
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00004833 }
Chris Lattner8a375202004-09-19 19:18:10 +00004834 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00004835}
4836
Chris Lattner833b8a42003-06-26 05:06:25 +00004837Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4838 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00004839
Chris Lattner37366c12005-05-01 04:24:53 +00004840 // load (cast X) --> cast (load X) iff safe
4841 if (CastInst *CI = dyn_cast<CastInst>(Op))
4842 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4843 return Res;
4844
4845 // None of the following transforms are legal for volatile loads.
4846 if (LI.isVolatile()) return 0;
4847
4848 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
4849 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
4850 isa<UndefValue>(GEPI->getOperand(0))) {
4851 // Insert a new store to null instruction before the load to indicate
4852 // that this code is not reachable. We do this instead of inserting
4853 // an unreachable instruction directly because we cannot modify the
4854 // CFG.
4855 new StoreInst(UndefValue::get(LI.getType()),
4856 Constant::getNullValue(Op->getType()), &LI);
4857 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
4858 }
4859
Chris Lattnere87597f2004-10-16 18:11:37 +00004860 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00004861 // load null/undef -> undef
4862 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00004863 // Insert a new store to null instruction before the load to indicate that
4864 // this code is not reachable. We do this instead of inserting an
4865 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00004866 new StoreInst(UndefValue::get(LI.getType()),
4867 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00004868 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00004869 }
Chris Lattner833b8a42003-06-26 05:06:25 +00004870
Chris Lattnere87597f2004-10-16 18:11:37 +00004871 // Instcombine load (constant global) into the value loaded.
4872 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4873 if (GV->isConstant() && !GV->isExternal())
4874 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00004875
Chris Lattnere87597f2004-10-16 18:11:37 +00004876 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4877 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4878 if (CE->getOpcode() == Instruction::GetElementPtr) {
4879 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4880 if (GV->isConstant() && !GV->isExternal())
4881 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4882 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00004883 if (CE->getOperand(0)->isNullValue()) {
4884 // Insert a new store to null instruction before the load to indicate
4885 // that this code is not reachable. We do this instead of inserting
4886 // an unreachable instruction directly because we cannot modify the
4887 // CFG.
4888 new StoreInst(UndefValue::get(LI.getType()),
4889 Constant::getNullValue(Op->getType()), &LI);
4890 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
4891 }
4892
Chris Lattnere87597f2004-10-16 18:11:37 +00004893 } else if (CE->getOpcode() == Instruction::Cast) {
4894 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4895 return Res;
4896 }
4897 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00004898
Chris Lattner37366c12005-05-01 04:24:53 +00004899 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00004900 // Change select and PHI nodes to select values instead of addresses: this
4901 // helps alias analysis out a lot, allows many others simplifications, and
4902 // exposes redundancy in the code.
4903 //
4904 // Note that we cannot do the transformation unless we know that the
4905 // introduced loads cannot trap! Something like this is valid as long as
4906 // the condition is always false: load (select bool %C, int* null, int* %G),
4907 // but it would not be valid if we transformed it to load from null
4908 // unconditionally.
4909 //
4910 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4911 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00004912 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4913 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00004914 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004915 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00004916 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004917 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00004918 return new SelectInst(SI->getCondition(), V1, V2);
4919 }
4920
Chris Lattner684fe212004-09-23 15:46:00 +00004921 // load (select (cond, null, P)) -> load P
4922 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4923 if (C->isNullValue()) {
4924 LI.setOperand(0, SI->getOperand(2));
4925 return &LI;
4926 }
4927
4928 // load (select (cond, P, null)) -> load P
4929 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4930 if (C->isNullValue()) {
4931 LI.setOperand(0, SI->getOperand(1));
4932 return &LI;
4933 }
4934
Chris Lattnerc10aced2004-09-19 18:43:46 +00004935 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4936 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004937 bool Safe = PN->getParent() == LI.getParent();
4938
4939 // Scan all of the instructions between the PHI and the load to make
4940 // sure there are no instructions that might possibly alter the value
4941 // loaded from the PHI.
4942 if (Safe) {
4943 BasicBlock::iterator I = &LI;
4944 for (--I; !isa<PHINode>(I); --I)
4945 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4946 Safe = false;
4947 break;
4948 }
4949 }
4950
4951 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00004952 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004953 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00004954 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00004955
Chris Lattnerc10aced2004-09-19 18:43:46 +00004956 if (Safe) {
4957 // Create the PHI.
4958 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4959 InsertNewInstBefore(NewPN, *PN);
4960 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4961
4962 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4963 BasicBlock *BB = PN->getIncomingBlock(i);
4964 Value *&TheLoad = LoadMap[BB];
4965 if (TheLoad == 0) {
4966 Value *InVal = PN->getIncomingValue(i);
4967 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4968 InVal->getName()+".val"),
4969 *BB->getTerminator());
4970 }
4971 NewPN->addIncoming(TheLoad, BB);
4972 }
4973 return ReplaceInstUsesWith(LI, NewPN);
4974 }
4975 }
4976 }
Chris Lattner833b8a42003-06-26 05:06:25 +00004977 return 0;
4978}
4979
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00004980/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
4981/// when possible.
4982static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
4983 User *CI = cast<User>(SI.getOperand(1));
4984 Value *CastOp = CI->getOperand(0);
4985
4986 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4987 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
4988 const Type *SrcPTy = SrcTy->getElementType();
4989
4990 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4991 // If the source is an array, the code below will not succeed. Check to
4992 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4993 // constants.
4994 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4995 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4996 if (ASrcTy->getNumElements() != 0) {
4997 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4998 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4999 SrcTy = cast<PointerType>(CastOp->getType());
5000 SrcPTy = SrcTy->getElementType();
5001 }
5002
5003 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005004 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005005 IC.getTargetData().getTypeSize(DestPTy)) {
5006
5007 // Okay, we are casting from one integer or pointer type to another of
5008 // the same size. Instead of casting the pointer before the store, cast
5009 // the value to be stored.
5010 Value *NewCast;
5011 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5012 NewCast = ConstantExpr::getCast(C, SrcPTy);
5013 else
5014 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5015 SrcPTy,
5016 SI.getOperand(0)->getName()+".c"), SI);
5017
5018 return new StoreInst(NewCast, CastOp);
5019 }
5020 }
5021 }
5022 return 0;
5023}
5024
Chris Lattner2f503e62005-01-31 05:36:43 +00005025Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5026 Value *Val = SI.getOperand(0);
5027 Value *Ptr = SI.getOperand(1);
5028
5029 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5030 removeFromWorkList(&SI);
5031 SI.eraseFromParent();
5032 ++NumCombined;
5033 return 0;
5034 }
5035
5036 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5037
5038 // store X, null -> turns into 'unreachable' in SimplifyCFG
5039 if (isa<ConstantPointerNull>(Ptr)) {
5040 if (!isa<UndefValue>(Val)) {
5041 SI.setOperand(0, UndefValue::get(Val->getType()));
5042 if (Instruction *U = dyn_cast<Instruction>(Val))
5043 WorkList.push_back(U); // Dropped a use.
5044 ++NumCombined;
5045 }
5046 return 0; // Do not modify these!
5047 }
5048
5049 // store undef, Ptr -> noop
5050 if (isa<UndefValue>(Val)) {
5051 removeFromWorkList(&SI);
5052 SI.eraseFromParent();
5053 ++NumCombined;
5054 return 0;
5055 }
5056
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005057 // If the pointer destination is a cast, see if we can fold the cast into the
5058 // source instead.
5059 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5060 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5061 return Res;
5062 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5063 if (CE->getOpcode() == Instruction::Cast)
5064 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5065 return Res;
5066
Chris Lattner2f503e62005-01-31 05:36:43 +00005067 return 0;
5068}
5069
5070
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005071Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5072 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005073 Value *X;
5074 BasicBlock *TrueDest;
5075 BasicBlock *FalseDest;
5076 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5077 !isa<Constant>(X)) {
5078 // Swap Destinations and condition...
5079 BI.setCondition(X);
5080 BI.setSuccessor(0, FalseDest);
5081 BI.setSuccessor(1, TrueDest);
5082 return &BI;
5083 }
5084
5085 // Cannonicalize setne -> seteq
5086 Instruction::BinaryOps Op; Value *Y;
5087 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5088 TrueDest, FalseDest)))
5089 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5090 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5091 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5092 std::string Name = I->getName(); I->setName("");
5093 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5094 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00005095 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005096 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00005097 BI.setSuccessor(0, FalseDest);
5098 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005099 removeFromWorkList(I);
5100 I->getParent()->getInstList().erase(I);
5101 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00005102 return &BI;
5103 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005104
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005105 return 0;
5106}
Chris Lattner0864acf2002-11-04 16:18:53 +00005107
Chris Lattner46238a62004-07-03 00:26:11 +00005108Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5109 Value *Cond = SI.getCondition();
5110 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5111 if (I->getOpcode() == Instruction::Add)
5112 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5113 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5114 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00005115 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005116 AddRHS));
5117 SI.setOperand(0, I->getOperand(0));
5118 WorkList.push_back(I);
5119 return &SI;
5120 }
5121 }
5122 return 0;
5123}
5124
Chris Lattner8a2a3112001-12-14 16:52:21 +00005125
Chris Lattner62b14df2002-09-02 04:59:56 +00005126void InstCombiner::removeFromWorkList(Instruction *I) {
5127 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5128 WorkList.end());
5129}
5130
Chris Lattnerea1c4542004-12-08 23:43:58 +00005131
5132/// TryToSinkInstruction - Try to move the specified instruction from its
5133/// current block into the beginning of DestBlock, which can only happen if it's
5134/// safe to move the instruction past all of the instructions between it and the
5135/// end of its block.
5136static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5137 assert(I->hasOneUse() && "Invariants didn't hold!");
5138
5139 // Cannot move control-flow-involving instructions.
5140 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005141
Chris Lattnerea1c4542004-12-08 23:43:58 +00005142 // Do not sink alloca instructions out of the entry block.
5143 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5144 return false;
5145
Chris Lattner96a52a62004-12-09 07:14:34 +00005146 // We can only sink load instructions if there is nothing between the load and
5147 // the end of block that could change the value.
5148 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5149 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5150
5151 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5152 Scan != E; ++Scan)
5153 if (Scan->mayWriteToMemory())
5154 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005155 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005156
5157 BasicBlock::iterator InsertPos = DestBlock->begin();
5158 while (isa<PHINode>(InsertPos)) ++InsertPos;
5159
5160 BasicBlock *SrcBlock = I->getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00005161 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005162 ++NumSunkInst;
5163 return true;
5164}
5165
Chris Lattner7e708292002-06-25 16:13:24 +00005166bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005167 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005168 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00005169
Chris Lattner216d4d82004-05-01 23:19:52 +00005170 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
5171 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00005172
Chris Lattner8a2a3112001-12-14 16:52:21 +00005173
5174 while (!WorkList.empty()) {
5175 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5176 WorkList.pop_back();
5177
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005178 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00005179 // Check to see if we can DIE the instruction...
5180 if (isInstructionTriviallyDead(I)) {
5181 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00005182 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005183 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00005184 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005185
Chris Lattnerad5fec12005-01-28 19:32:01 +00005186 DEBUG(std::cerr << "IC: DCE: " << *I);
5187
5188 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00005189 removeFromWorkList(I);
5190 continue;
5191 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005192
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005193 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00005194 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005195 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00005196 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005197 cast<Constant>(Ptr)->isNullValue() &&
5198 !isa<ConstantPointerNull>(C) &&
5199 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00005200 // If this is a constant expr gep that is effectively computing an
5201 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5202 bool isFoldableGEP = true;
5203 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5204 if (!isa<ConstantInt>(I->getOperand(i)))
5205 isFoldableGEP = false;
5206 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005207 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00005208 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5209 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00005210 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00005211 C = ConstantExpr::getCast(C, I->getType());
5212 }
5213 }
5214
Chris Lattnerad5fec12005-01-28 19:32:01 +00005215 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5216
Chris Lattner62b14df2002-09-02 04:59:56 +00005217 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005218 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00005219 ReplaceInstUsesWith(*I, C);
5220
Chris Lattner62b14df2002-09-02 04:59:56 +00005221 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005222 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00005223 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005224 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00005225 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005226
Chris Lattnerea1c4542004-12-08 23:43:58 +00005227 // See if we can trivially sink this instruction to a successor basic block.
5228 if (I->hasOneUse()) {
5229 BasicBlock *BB = I->getParent();
5230 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5231 if (UserParent != BB) {
5232 bool UserIsSuccessor = false;
5233 // See if the user is one of our successors.
5234 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5235 if (*SI == UserParent) {
5236 UserIsSuccessor = true;
5237 break;
5238 }
5239
5240 // If the user is one of our immediate successors, and if that successor
5241 // only has us as a predecessors (we'd have to split the critical edge
5242 // otherwise), we can keep going.
5243 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5244 next(pred_begin(UserParent)) == pred_end(UserParent))
5245 // Okay, the CFG is simple enough, try to sink this instruction.
5246 Changed |= TryToSinkInstruction(I, UserParent);
5247 }
5248 }
5249
Chris Lattner8a2a3112001-12-14 16:52:21 +00005250 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00005251 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005252 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005253 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005254 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005255 DEBUG(std::cerr << "IC: Old = " << *I
5256 << " New = " << *Result);
5257
Chris Lattnerf523d062004-06-09 05:08:07 +00005258 // Everything uses the new instruction now.
5259 I->replaceAllUsesWith(Result);
5260
5261 // Push the new instruction and any users onto the worklist.
5262 WorkList.push_back(Result);
5263 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005264
5265 // Move the name to the new instruction first...
5266 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00005267 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005268
5269 // Insert the new instruction into the basic block...
5270 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005271 BasicBlock::iterator InsertPos = I;
5272
5273 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5274 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5275 ++InsertPos;
5276
5277 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005278
Chris Lattner00d51312004-05-01 23:27:23 +00005279 // Make sure that we reprocess all operands now that we reduced their
5280 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00005281 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5282 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5283 WorkList.push_back(OpI);
5284
Chris Lattnerf523d062004-06-09 05:08:07 +00005285 // Instructions can end up on the worklist more than once. Make sure
5286 // we do not process an instruction that has been deleted.
5287 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005288
5289 // Erase the old instruction.
5290 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005291 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005292 DEBUG(std::cerr << "IC: MOD = " << *I);
5293
Chris Lattner90ac28c2002-08-02 19:29:35 +00005294 // If the instruction was modified, it's possible that it is now dead.
5295 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005296 if (isInstructionTriviallyDead(I)) {
5297 // Make sure we process all operands now that we are reducing their
5298 // use counts.
5299 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5300 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5301 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005302
Chris Lattner00d51312004-05-01 23:27:23 +00005303 // Instructions may end up in the worklist more than once. Erase all
5304 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005305 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00005306 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00005307 } else {
5308 WorkList.push_back(Result);
5309 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005310 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005311 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005312 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005313 }
5314 }
5315
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005316 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005317}
5318
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005319FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005320 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005321}
Brian Gaeked0fde302003-11-11 22:41:34 +00005322