blob: c56436048be5c20de847de8a4578c857b66a9ce5 [file] [log] [blame]
Chris Lattnerca081252001-12-14 16:52:21 +00001//===- InstructionCombining.cpp - Combine multiple instructions -------------=//
2//
3// InstructionCombining - Combine instructions to form fewer, simple
4// instructions. This pass does not modify the CFG, and has a tendancy to
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005// make instructions dead, so a subsequent DIE pass is useful. This pass is
6// where algebraic simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +00007//
8// This pass combines things like:
9// %Y = add int 1, %X
10// %Z = add int 1, %Y
11// into:
12// %Z = add int 2, %X
13//
14// This is a simple worklist driven algorithm.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/Scalar/InstructionCombining.h"
Chris Lattner65b529f2002-04-08 20:18:09 +000019#include "llvm/ConstantHandling.h"
Chris Lattnerca081252001-12-14 16:52:21 +000020#include "llvm/iMemory.h"
Chris Lattner3a60d042002-04-15 19:45:29 +000021#include "llvm/iOther.h"
Chris Lattner260ab202002-04-18 17:39:14 +000022#include "llvm/iOperators.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000023#include "llvm/Pass.h"
Chris Lattner60a65912002-02-12 21:07:25 +000024#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000025#include "llvm/Support/InstVisitor.h"
Chris Lattneree965ab2002-01-21 23:17:48 +000026#include "../TransformInternals.h"
Chris Lattnerca081252001-12-14 16:52:21 +000027
Chris Lattnerca081252001-12-14 16:52:21 +000028
Chris Lattner260ab202002-04-18 17:39:14 +000029namespace {
Chris Lattnerc8e66542002-04-27 06:56:12 +000030 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000031 public InstVisitor<InstCombiner, Instruction*> {
32 // Worklist of all of the instructions that need to be simplified.
33 std::vector<Instruction*> WorkList;
34
35 void AddUsesToWorkList(Instruction *I) {
36 // The instruction was simplified, add all users of the instruction to
37 // the work lists because they might get more simplified now...
38 //
39 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
40 UI != UE; ++UI)
41 WorkList.push_back(cast<Instruction>(*UI));
42 }
43
44 public:
Chris Lattner37104aa2002-04-29 14:57:45 +000045 const char *getPassName() const { return "Instruction Combining"; }
46
Chris Lattnerc8e66542002-04-27 06:56:12 +000047 virtual bool runOnFunction(Function *F);
Chris Lattner260ab202002-04-18 17:39:14 +000048
Chris Lattnerf12cc842002-04-28 21:27:06 +000049 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50 AU.preservesCFG();
51 }
52
Chris Lattner260ab202002-04-18 17:39:14 +000053 // Visitation implementation - Implement instruction combining for different
54 // instruction types. The semantics are as follows:
55 // Return Value:
56 // null - No change was made
57 // I - Change was made, I is still valid
58 // otherwise - Change was made, replace I with returned instruction
59 //
60
61 Instruction *visitAdd(BinaryOperator *I);
62 Instruction *visitSub(BinaryOperator *I);
63 Instruction *visitMul(BinaryOperator *I);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +000064 Instruction *visitDiv(BinaryOperator *I);
65 Instruction *visitRem(BinaryOperator *I);
66 Instruction *visitAnd(BinaryOperator *I);
67 Instruction *visitOr (BinaryOperator *I);
68 Instruction *visitXor(BinaryOperator *I);
69 Instruction *visitSetCondInst(BinaryOperator *I);
70 Instruction *visitShiftInst(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000071 Instruction *visitCastInst(CastInst *CI);
Chris Lattner48a44f72002-05-02 17:06:02 +000072 Instruction *visitGetElementPtrInst(GetElementPtrInst *GEP);
Chris Lattner260ab202002-04-18 17:39:14 +000073 Instruction *visitMemAccessInst(MemAccessInst *MAI);
74
75 // visitInstruction - Specify what to return for unhandled instructions...
76 Instruction *visitInstruction(Instruction *I) { return 0; }
77 };
78}
79
80
81
82// Make sure that this instruction has a constant on the right hand side if it
83// has any constant arguments. If not, fix it an return true.
84//
85static bool SimplifyBinOp(BinaryOperator *I) {
Chris Lattnerca081252001-12-14 16:52:21 +000086 if (isa<Constant>(I->getOperand(0)) && !isa<Constant>(I->getOperand(1)))
Chris Lattner31ba1292002-04-29 22:24:47 +000087 return !I->swapOperands();
Chris Lattner260ab202002-04-18 17:39:14 +000088 return false;
89}
Chris Lattnerca081252001-12-14 16:52:21 +000090
Chris Lattner260ab202002-04-18 17:39:14 +000091Instruction *InstCombiner::visitAdd(BinaryOperator *I) {
92 if (I->use_empty()) return 0; // Don't fix dead add instructions...
93 bool Changed = SimplifyBinOp(I);
94 Value *Op1 = I->getOperand(0);
95
96 // Simplify add instructions with a constant RHS...
97 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(1))) {
98 // Eliminate 'add int %X, 0'
99 if (I->getType()->isIntegral() && Op2->isNullValue()) {
100 AddUsesToWorkList(I); // Add all modified instrs to worklist
101 I->replaceAllUsesWith(Op1);
102 return I;
103 }
104
105 if (BinaryOperator *IOp1 = dyn_cast<BinaryOperator>(Op1)) {
106 Changed |= SimplifyBinOp(IOp1);
107
108 if (IOp1->getOpcode() == Instruction::Add &&
109 isa<Constant>(IOp1->getOperand(1))) {
110 // Fold:
111 // %Y = add int %X, 1
112 // %Z = add int %Y, 1
113 // into:
114 // %Z = add int %X, 2
115 //
116 if (Constant *Val = *Op2 + *cast<Constant>(IOp1->getOperand(1))) {
117 I->setOperand(0, IOp1->getOperand(0));
118 I->setOperand(1, Val);
Chris Lattnerbee86622002-03-11 23:28:45 +0000119 return I;
Chris Lattner04805fa2002-02-26 21:46:54 +0000120 }
Chris Lattnerca081252001-12-14 16:52:21 +0000121 }
122 }
Chris Lattnerca081252001-12-14 16:52:21 +0000123 }
124
Chris Lattner260ab202002-04-18 17:39:14 +0000125 return Changed ? I : 0;
126}
127
128Instruction *InstCombiner::visitSub(BinaryOperator *I) {
129 if (I->use_empty()) return 0; // Don't fix dead add instructions...
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000130 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
131
132 if (Op0 == Op1) { // sub X, X -> 0
133 AddUsesToWorkList(I); // Add all modified instrs to worklist
134 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
135 return I;
136 }
Chris Lattner260ab202002-04-18 17:39:14 +0000137
138 // If this is a subtract instruction with a constant RHS, convert it to an add
139 // instruction of a negative constant
140 //
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000141 if (Constant *Op2 = dyn_cast<Constant>(Op1))
142 if (Constant *RHS = *Constant::getNullValue(I->getType()) - *Op2) // 0 - RHS
143 return BinaryOperator::create(Instruction::Add, Op0, RHS, I->getName());
Chris Lattner260ab202002-04-18 17:39:14 +0000144
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000145 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000146}
147
148Instruction *InstCombiner::visitMul(BinaryOperator *I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000149 if (I->use_empty()) return 0; // Don't fix dead instructions...
Chris Lattner260ab202002-04-18 17:39:14 +0000150 bool Changed = SimplifyBinOp(I);
151 Value *Op1 = I->getOperand(0);
152
153 // Simplify add instructions with a constant RHS...
154 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(1))) {
155 if (I->getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1)){
156 // Eliminate 'mul int %X, 1'
157 AddUsesToWorkList(I); // Add all modified instrs to worklist
158 I->replaceAllUsesWith(Op1);
159 return I;
Chris Lattner31ba1292002-04-29 22:24:47 +0000160
161 } else if (I->getType()->isIntegral() &&
162 cast<ConstantInt>(Op2)->equalsInt(2)) {
163 // Convert 'mul int %X, 2' to 'add int %X, %X'
164 return BinaryOperator::create(Instruction::Add, Op1, Op1, I->getName());
165
166 } else if (Op2->isNullValue()) {
167 // Eliminate 'mul int %X, 0'
168 AddUsesToWorkList(I); // Add all modified instrs to worklist
169 I->replaceAllUsesWith(Op2); // Set this value to zero directly
170 return I;
Chris Lattner260ab202002-04-18 17:39:14 +0000171 }
172 }
173
174 return Changed ? I : 0;
175}
176
177
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000178Instruction *InstCombiner::visitDiv(BinaryOperator *I) {
179 if (I->use_empty()) return 0; // Don't fix dead instructions...
180
181 // div X, 1 == X
182 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
183 if (RHS->equalsInt(1)) {
184 AddUsesToWorkList(I); // Add all modified instrs to worklist
185 I->replaceAllUsesWith(I->getOperand(0));
186 return I;
187 }
188 return 0;
189}
190
191
192Instruction *InstCombiner::visitRem(BinaryOperator *I) {
193 if (I->use_empty()) return 0; // Don't fix dead instructions...
194
195 // rem X, 1 == 0
196 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
197 if (RHS->equalsInt(1)) {
198 AddUsesToWorkList(I); // Add all modified instrs to worklist
199 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
200 return I;
201 }
202 return 0;
203}
204
205static Constant *getMaxValue(const Type *Ty) {
206 assert(Ty == Type::BoolTy || Ty->isIntegral());
207 if (Ty == Type::BoolTy)
208 return ConstantBool::True;
209
210 // Calculate -1 casted to the right type...
211 unsigned TypeBits = Ty->getPrimitiveSize()*8;
212 uint64_t Val = (uint64_t)-1LL; // All ones
213 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
214
215 if (Ty->isSigned())
216 return ConstantSInt::get(Ty, (int64_t)Val);
217 else if (Ty->isUnsigned())
218 return ConstantUInt::get(Ty, Val);
219
220 return 0;
221}
222
223
224Instruction *InstCombiner::visitAnd(BinaryOperator *I) {
225 if (I->use_empty()) return 0; // Don't fix dead instructions...
226 bool Changed = SimplifyBinOp(I);
227 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
228
229 // and X, X = X and X, 0 == 0
230 if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
231 AddUsesToWorkList(I); // Add all modified instrs to worklist
232 I->replaceAllUsesWith(Op1);
233 return I;
234 }
235
236 // and X, -1 == X
237 if (Constant *RHS = dyn_cast<Constant>(Op1))
238 if (RHS == getMaxValue(I->getType())) {
239 AddUsesToWorkList(I); // Add all modified instrs to worklist
240 I->replaceAllUsesWith(Op0);
241 return I;
242 }
243
244 return Changed ? I : 0;
245}
246
247
248
249Instruction *InstCombiner::visitOr(BinaryOperator *I) {
250 if (I->use_empty()) return 0; // Don't fix dead instructions...
251 bool Changed = SimplifyBinOp(I);
252 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
253
254 // or X, X = X or X, 0 == X
255 if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
256 AddUsesToWorkList(I); // Add all modified instrs to worklist
257 I->replaceAllUsesWith(Op0);
258 return I;
259 }
260
261 // or X, -1 == -1
262 if (Constant *RHS = dyn_cast<Constant>(Op1))
263 if (RHS == getMaxValue(I->getType())) {
264 AddUsesToWorkList(I); // Add all modified instrs to worklist
265 I->replaceAllUsesWith(Op1);
266 return I;
267 }
268
269 return Changed ? I : 0;
270}
271
272
273
274Instruction *InstCombiner::visitXor(BinaryOperator *I) {
275 if (I->use_empty()) return 0; // Don't fix dead instructions...
276 bool Changed = SimplifyBinOp(I);
277 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
278
279 // xor X, X = 0
280 if (Op0 == Op1) {
281 AddUsesToWorkList(I); // Add all modified instrs to worklist
282 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
283 return I;
284 }
285
286 // xor X, 0 == X
287 if (Op1 == Constant::getNullValue(I->getType())) {
288 AddUsesToWorkList(I); // Add all modified instrs to worklist
289 I->replaceAllUsesWith(Op0);
290 return I;
291 }
292
293 return Changed ? I : 0;
294}
295
296Instruction *InstCombiner::visitSetCondInst(BinaryOperator *I) {
297 if (I->use_empty()) return 0; // Don't fix dead instructions...
298 bool Changed = SimplifyBinOp(I);
299
300 // setcc X, X
301 if (I->getOperand(0) == I->getOperand(1)) {
302 bool NewVal = I->getOpcode() == Instruction::SetEQ ||
303 I->getOpcode() == Instruction::SetGE ||
304 I->getOpcode() == Instruction::SetLE;
305 AddUsesToWorkList(I); // Add all modified instrs to worklist
306 I->replaceAllUsesWith(ConstantBool::get(NewVal));
307 return I;
308 }
309
310 return Changed ? I : 0;
311}
312
313
314
315Instruction *InstCombiner::visitShiftInst(Instruction *I) {
316 if (I->use_empty()) return 0; // Don't fix dead instructions...
317 assert(I->getOperand(1)->getType() == Type::UByteTy);
318 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
319
320 // shl X, 0 == X and shr X, 0 == X
321 // shl 0, X == 0 and shr 0, X == 0
322 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
323 Op0 == Constant::getNullValue(Op0->getType())) {
324 AddUsesToWorkList(I); // Add all modified instrs to worklist
325 I->replaceAllUsesWith(Op0);
326 return I;
327 }
328
329 // shl int X, 32 = 0 and shr sbyte Y, 9 = 0, ... just don't eliminate shr of
330 // a signed value.
331 //
332 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
333 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
334 if (CUI->getValue() >= TypeBits &&
335 !(Op0->getType()->isSigned() && I->getOpcode() == Instruction::Shr)) {
336 AddUsesToWorkList(I); // Add all modified instrs to worklist
337 I->replaceAllUsesWith(Constant::getNullValue(Op0->getType()));
338 return I;
339 }
340 }
341 return 0;
342}
343
344
Chris Lattner48a44f72002-05-02 17:06:02 +0000345// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
346// instruction.
347//
348static inline bool isEliminableCastOfCast(const CastInst *CI,
349 const CastInst *CSrc) {
350 assert(CI->getOperand(0) == CSrc);
351 const Type *SrcTy = CSrc->getOperand(0)->getType();
352 const Type *MidTy = CSrc->getType();
353 const Type *DstTy = CI->getType();
354
355 // It is legal to eliminate the instruction if casting A->B->A
356 if (SrcTy == DstTy) return true;
357
358 // Allow free casting and conversion of sizes as long as the sign doesn't
359 // change...
360 if (SrcTy->isSigned() == MidTy->isSigned() &&
361 MidTy->isSigned() == DstTy->isSigned())
362 return true;
363
364 // Otherwise, we cannot succeed. Specifically we do not want to allow things
365 // like: short -> ushort -> uint, because this can create wrong results if
366 // the input short is negative!
367 //
368 return false;
369}
370
371
372// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000373//
374Instruction *InstCombiner::visitCastInst(CastInst *CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000375 // If the user is casting a value to the same type, eliminate this cast
376 // instruction...
Chris Lattner260ab202002-04-18 17:39:14 +0000377 if (CI->getType() == CI->getOperand(0)->getType() && !CI->use_empty()) {
378 AddUsesToWorkList(CI); // Add all modified instrs to worklist
379 CI->replaceAllUsesWith(CI->getOperand(0));
380 return CI;
381 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000382
383
384 // If casting the result of another cast instruction, try to eliminate this
385 // one!
386 //
387 if (CastInst *CSrc = dyn_cast<CastInst>(CI->getOperand(0)))
388 if (isEliminableCastOfCast(CI, CSrc)) {
389 // This instruction now refers directly to the cast's src operand. This
390 // has a good chance of making CSrc dead.
391 CI->setOperand(0, CSrc->getOperand(0));
392 return CI;
393 }
394
Chris Lattner260ab202002-04-18 17:39:14 +0000395 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000396}
397
Chris Lattner48a44f72002-05-02 17:06:02 +0000398
399
400Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst *GEP) {
401 // Is it getelementptr %P, uint 0
402 // If so, elminate the noop.
403 if (GEP->getNumOperands() == 2 && !GEP->use_empty() &&
404 GEP->getOperand(1) == Constant::getNullValue(Type::UIntTy)) {
405 AddUsesToWorkList(GEP); // Add all modified instrs to worklist
406 GEP->replaceAllUsesWith(GEP->getOperand(0));
407 return GEP;
408 }
409
410 return visitMemAccessInst(GEP);
411}
412
413
Chris Lattnerca081252001-12-14 16:52:21 +0000414// Combine Indices - If the source pointer to this mem access instruction is a
415// getelementptr instruction, combine the indices of the GEP into this
416// instruction
417//
Chris Lattner260ab202002-04-18 17:39:14 +0000418Instruction *InstCombiner::visitMemAccessInst(MemAccessInst *MAI) {
Chris Lattnerca081252001-12-14 16:52:21 +0000419 GetElementPtrInst *Src =
420 dyn_cast<GetElementPtrInst>(MAI->getPointerOperand());
421 if (!Src) return 0;
422
Chris Lattner7f74a562002-01-20 22:54:45 +0000423 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +0000424
425 // Only special case we have to watch out for is pointer arithmetic on the
426 // 0th index of MAI.
427 unsigned FirstIdx = MAI->getFirstIndexOperandNumber();
428 if (FirstIdx == MAI->getNumOperands() ||
429 (FirstIdx == MAI->getNumOperands()-1 &&
430 MAI->getOperand(FirstIdx) == ConstantUInt::get(Type::UIntTy, 0))) {
431 // Replace the index list on this MAI with the index on the getelementptr
432 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
433 } else if (*MAI->idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) {
434 // Otherwise we can do the fold if the first index of the GEP is a zero
435 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
436 Indices.insert(Indices.end(), MAI->idx_begin()+1, MAI->idx_end());
437 }
438
439 if (Indices.empty()) return 0; // Can't do the fold?
440
441 switch (MAI->getOpcode()) {
442 case Instruction::GetElementPtr:
443 return new GetElementPtrInst(Src->getOperand(0), Indices, MAI->getName());
444 case Instruction::Load:
445 return new LoadInst(Src->getOperand(0), Indices, MAI->getName());
446 case Instruction::Store:
Chris Lattnerf40379e2002-04-18 14:43:54 +0000447 return new StoreInst(MAI->getOperand(0), Src->getOperand(0), Indices);
Chris Lattnerca081252001-12-14 16:52:21 +0000448 default:
449 assert(0 && "Unknown memaccessinst!");
450 break;
451 }
452 abort();
453 return 0;
454}
455
Chris Lattnerca081252001-12-14 16:52:21 +0000456
Chris Lattnerc8e66542002-04-27 06:56:12 +0000457bool InstCombiner::runOnFunction(Function *F) {
Chris Lattner260ab202002-04-18 17:39:14 +0000458 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +0000459
Chris Lattner260ab202002-04-18 17:39:14 +0000460 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +0000461
462 while (!WorkList.empty()) {
463 Instruction *I = WorkList.back(); // Get an instruction from the worklist
464 WorkList.pop_back();
465
466 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner260ab202002-04-18 17:39:14 +0000467 Instruction *Result = visit(I);
468 if (Result) {
469 // Should we replace the old instruction with a new one?
470 if (Result != I)
471 ReplaceInstWithInst(I, Result);
472
473 WorkList.push_back(Result);
474 AddUsesToWorkList(Result);
475 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +0000476 }
477 }
478
Chris Lattner260ab202002-04-18 17:39:14 +0000479 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +0000480}
481
482Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +0000483 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +0000484}