1 //===- InstructionCombining.cpp - Combine multiple instructions -------------=//
3 // InstructionCombining - Combine instructions to form fewer, simple
4 // instructions. This pass does not modify the CFG, and has a tendancy to
5 // make instructions dead, so a subsequent DIE pass is useful. This pass is
6 // where algebraic simplification happens.
8 // This pass combines things like:
14 // This is a simple worklist driven algorithm.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "llvm/ConstantHandling.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iOther.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iOperators.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/InstIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/StatisticReporter.h"
31 static Statistic<> NumCombined("instcombine\t- Number of insts combined");
34 class InstCombiner : public FunctionPass,
35 public InstVisitor<InstCombiner, Instruction*> {
36 // Worklist of all of the instructions that need to be simplified.
37 std::vector<Instruction*> WorkList;
39 void AddUsesToWorkList(Instruction *I) {
40 // The instruction was simplified, add all users of the instruction to
41 // the work lists because they might get more simplified now...
43 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
45 WorkList.push_back(cast<Instruction>(*UI));
49 const char *getPassName() const { return "Instruction Combining"; }
51 virtual bool runOnFunction(Function *F);
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 // Visitation implementation - Implement instruction combining for different
58 // instruction types. The semantics are as follows:
60 // null - No change was made
61 // I - Change was made, I is still valid
62 // otherwise - Change was made, replace I with returned instruction
64 Instruction *visitNot(UnaryOperator *I);
65 Instruction *visitAdd(BinaryOperator *I);
66 Instruction *visitSub(BinaryOperator *I);
67 Instruction *visitMul(BinaryOperator *I);
68 Instruction *visitDiv(BinaryOperator *I);
69 Instruction *visitRem(BinaryOperator *I);
70 Instruction *visitAnd(BinaryOperator *I);
71 Instruction *visitOr (BinaryOperator *I);
72 Instruction *visitXor(BinaryOperator *I);
73 Instruction *visitSetCondInst(BinaryOperator *I);
74 Instruction *visitShiftInst(Instruction *I);
75 Instruction *visitCastInst(CastInst *CI);
76 Instruction *visitPHINode(PHINode *PN);
77 Instruction *visitGetElementPtrInst(GetElementPtrInst *GEP);
78 Instruction *visitMemAccessInst(MemAccessInst *MAI);
80 // visitInstruction - Specify what to return for unhandled instructions...
81 Instruction *visitInstruction(Instruction *I) { return 0; }
86 Instruction *InstCombiner::visitNot(UnaryOperator *I) {
87 if (I->use_empty()) return 0; // Don't fix dead instructions...
90 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(0)))
91 if (Op->getOpcode() == Instruction::Not) {
92 AddUsesToWorkList(I); // Add all modified instrs to worklist
93 I->replaceAllUsesWith(Op->getOperand(0));
100 // Make sure that this instruction has a constant on the right hand side if it
101 // has any constant arguments. If not, fix it an return true.
103 static bool SimplifyBinOp(BinaryOperator *I) {
104 if (isa<Constant>(I->getOperand(0)) && !isa<Constant>(I->getOperand(1)))
105 return !I->swapOperands();
109 // dyn_castNegInst - Given a 'sub' instruction, return the RHS of the
110 // instruction if the LHS is a constant zero (which is the 'negate' form).
112 static inline Value *dyn_castNegInst(Value *V) {
113 Instruction *I = dyn_cast<Instruction>(V);
114 if (!I || I->getOpcode() != Instruction::Sub) return 0;
116 if (I->getOperand(0) == Constant::getNullValue(I->getType()))
117 return I->getOperand(1);
121 Instruction *InstCombiner::visitAdd(BinaryOperator *I) {
122 if (I->use_empty()) return 0; // Don't fix dead add instructions...
123 bool Changed = SimplifyBinOp(I);
124 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
126 // Eliminate 'add int %X, 0'
127 if (RHS == Constant::getNullValue(I->getType())) {
128 AddUsesToWorkList(I); // Add all modified instrs to worklist
129 I->replaceAllUsesWith(LHS);
134 if (Value *V = dyn_castNegInst(LHS))
135 return BinaryOperator::create(Instruction::Sub, RHS, V);
138 if (Value *V = dyn_castNegInst(RHS))
139 return BinaryOperator::create(Instruction::Sub, LHS, V);
141 // Simplify add instructions with a constant RHS...
142 if (Constant *Op2 = dyn_cast<Constant>(RHS)) {
143 if (BinaryOperator *ILHS = dyn_cast<BinaryOperator>(LHS)) {
144 if (ILHS->getOpcode() == Instruction::Add &&
145 isa<Constant>(ILHS->getOperand(1))) {
147 // %Y = add int %X, 1
148 // %Z = add int %Y, 1
150 // %Z = add int %X, 2
152 if (Constant *Val = *Op2 + *cast<Constant>(ILHS->getOperand(1))) {
153 I->setOperand(0, ILHS->getOperand(0));
154 I->setOperand(1, Val);
161 return Changed ? I : 0;
164 Instruction *InstCombiner::visitSub(BinaryOperator *I) {
165 if (I->use_empty()) return 0; // Don't fix dead add instructions...
166 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
168 if (Op0 == Op1) { // sub X, X -> 0
169 AddUsesToWorkList(I); // Add all modified instrs to worklist
170 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
174 // If this is a subtract instruction with a constant RHS, convert it to an add
175 // instruction of a negative constant
177 if (Constant *Op2 = dyn_cast<Constant>(Op1))
178 if (Constant *RHS = *Constant::getNullValue(I->getType()) - *Op2) // 0 - RHS
179 return BinaryOperator::create(Instruction::Add, Op0, RHS, I->getName());
181 // If this is a 'C = x-B', check to see if 'B = -A', so that C = x+A...
182 if (Value *V = dyn_castNegInst(Op1))
183 return BinaryOperator::create(Instruction::Add, Op0, V);
185 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression is
186 // not used by anyone else...
188 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
189 if (Op1I->use_size() == 1 && Op1I->getOpcode() == Instruction::Sub) {
190 // Swap the two operands of the subexpr...
191 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
192 Op1I->setOperand(0, IIOp1);
193 Op1I->setOperand(1, IIOp0);
195 // Create the new top level add instruction...
196 return BinaryOperator::create(Instruction::Add, Op0, Op1);
201 Instruction *InstCombiner::visitMul(BinaryOperator *I) {
202 if (I->use_empty()) return 0; // Don't fix dead instructions...
203 bool Changed = SimplifyBinOp(I);
204 Value *Op1 = I->getOperand(0);
206 // Simplify add instructions with a constant RHS...
207 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(1))) {
208 if (I->getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1)){
209 // Eliminate 'mul int %X, 1'
210 AddUsesToWorkList(I); // Add all modified instrs to worklist
211 I->replaceAllUsesWith(Op1);
214 } else if (I->getType()->isIntegral() &&
215 cast<ConstantInt>(Op2)->equalsInt(2)) {
216 // Convert 'mul int %X, 2' to 'add int %X, %X'
217 return BinaryOperator::create(Instruction::Add, Op1, Op1, I->getName());
219 } else if (Op2->isNullValue()) {
220 // Eliminate 'mul int %X, 0'
221 AddUsesToWorkList(I); // Add all modified instrs to worklist
222 I->replaceAllUsesWith(Op2); // Set this value to zero directly
227 return Changed ? I : 0;
231 Instruction *InstCombiner::visitDiv(BinaryOperator *I) {
232 if (I->use_empty()) return 0; // Don't fix dead instructions...
235 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
236 if (RHS->equalsInt(1)) {
237 AddUsesToWorkList(I); // Add all modified instrs to worklist
238 I->replaceAllUsesWith(I->getOperand(0));
245 Instruction *InstCombiner::visitRem(BinaryOperator *I) {
246 if (I->use_empty()) return 0; // Don't fix dead instructions...
249 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
250 if (RHS->equalsInt(1)) {
251 AddUsesToWorkList(I); // Add all modified instrs to worklist
252 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
258 static Constant *getMaxValue(const Type *Ty) {
259 assert(Ty == Type::BoolTy || Ty->isIntegral());
260 if (Ty == Type::BoolTy)
261 return ConstantBool::True;
264 return ConstantSInt::get(Ty, -1);
265 else if (Ty->isUnsigned()) {
266 // Calculate -1 casted to the right type...
267 unsigned TypeBits = Ty->getPrimitiveSize()*8;
268 uint64_t Val = (uint64_t)-1LL; // All ones
269 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
270 return ConstantUInt::get(Ty, Val);
276 Instruction *InstCombiner::visitAnd(BinaryOperator *I) {
277 if (I->use_empty()) return 0; // Don't fix dead instructions...
278 bool Changed = SimplifyBinOp(I);
279 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
281 // and X, X = X and X, 0 == 0
282 if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
283 AddUsesToWorkList(I); // Add all modified instrs to worklist
284 I->replaceAllUsesWith(Op1);
289 if (Constant *RHS = dyn_cast<Constant>(Op1))
290 if (RHS == getMaxValue(I->getType())) {
291 AddUsesToWorkList(I); // Add all modified instrs to worklist
292 I->replaceAllUsesWith(Op0);
296 return Changed ? I : 0;
301 Instruction *InstCombiner::visitOr(BinaryOperator *I) {
302 if (I->use_empty()) return 0; // Don't fix dead instructions...
303 bool Changed = SimplifyBinOp(I);
304 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
306 // or X, X = X or X, 0 == X
307 if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
308 AddUsesToWorkList(I); // Add all modified instrs to worklist
309 I->replaceAllUsesWith(Op0);
314 if (Constant *RHS = dyn_cast<Constant>(Op1))
315 if (RHS == getMaxValue(I->getType())) {
316 AddUsesToWorkList(I); // Add all modified instrs to worklist
317 I->replaceAllUsesWith(Op1);
321 return Changed ? I : 0;
326 Instruction *InstCombiner::visitXor(BinaryOperator *I) {
327 if (I->use_empty()) return 0; // Don't fix dead instructions...
328 bool Changed = SimplifyBinOp(I);
329 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
333 AddUsesToWorkList(I); // Add all modified instrs to worklist
334 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
339 if (Op1 == Constant::getNullValue(I->getType())) {
340 AddUsesToWorkList(I); // Add all modified instrs to worklist
341 I->replaceAllUsesWith(Op0);
345 return Changed ? I : 0;
348 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
349 // true when both operands are equal...
351 static bool isTrueWhenEqual(Instruction *I) {
352 return I->getOpcode() == Instruction::SetEQ ||
353 I->getOpcode() == Instruction::SetGE ||
354 I->getOpcode() == Instruction::SetLE;
357 Instruction *InstCombiner::visitSetCondInst(BinaryOperator *I) {
358 if (I->use_empty()) return 0; // Don't fix dead instructions...
359 bool Changed = SimplifyBinOp(I);
362 if (I->getOperand(0) == I->getOperand(1)) {
363 AddUsesToWorkList(I); // Add all modified instrs to worklist
364 I->replaceAllUsesWith(ConstantBool::get(isTrueWhenEqual(I)));
368 // setcc <global*>, 0 - Global value addresses are never null!
369 if (isa<GlobalValue>(I->getOperand(0)) &&
370 isa<ConstantPointerNull>(I->getOperand(1))) {
371 AddUsesToWorkList(I); // Add all modified instrs to worklist
372 I->replaceAllUsesWith(ConstantBool::get(!isTrueWhenEqual(I)));
376 return Changed ? I : 0;
381 Instruction *InstCombiner::visitShiftInst(Instruction *I) {
382 if (I->use_empty()) return 0; // Don't fix dead instructions...
383 assert(I->getOperand(1)->getType() == Type::UByteTy);
384 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
386 // shl X, 0 == X and shr X, 0 == X
387 // shl 0, X == 0 and shr 0, X == 0
388 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
389 Op0 == Constant::getNullValue(Op0->getType())) {
390 AddUsesToWorkList(I); // Add all modified instrs to worklist
391 I->replaceAllUsesWith(Op0);
395 // shl int X, 32 = 0 and shr sbyte Y, 9 = 0, ... just don't eliminate shr of
398 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
399 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
400 if (CUI->getValue() >= TypeBits &&
401 !(Op0->getType()->isSigned() && I->getOpcode() == Instruction::Shr)) {
402 AddUsesToWorkList(I); // Add all modified instrs to worklist
403 I->replaceAllUsesWith(Constant::getNullValue(Op0->getType()));
411 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
414 static inline bool isEliminableCastOfCast(const CastInst *CI,
415 const CastInst *CSrc) {
416 assert(CI->getOperand(0) == CSrc);
417 const Type *SrcTy = CSrc->getOperand(0)->getType();
418 const Type *MidTy = CSrc->getType();
419 const Type *DstTy = CI->getType();
421 // It is legal to eliminate the instruction if casting A->B->A
422 if (SrcTy == DstTy) return true;
424 // Allow free casting and conversion of sizes as long as the sign doesn't
426 if (SrcTy->isSigned() == MidTy->isSigned() &&
427 MidTy->isSigned() == DstTy->isSigned())
430 // Otherwise, we cannot succeed. Specifically we do not want to allow things
431 // like: short -> ushort -> uint, because this can create wrong results if
432 // the input short is negative!
438 // CastInst simplification
440 Instruction *InstCombiner::visitCastInst(CastInst *CI) {
441 if (CI->use_empty()) return 0; // Don't fix dead instructions...
443 // If the user is casting a value to the same type, eliminate this cast
445 if (CI->getType() == CI->getOperand(0)->getType() && !CI->use_empty()) {
446 AddUsesToWorkList(CI); // Add all modified instrs to worklist
447 CI->replaceAllUsesWith(CI->getOperand(0));
452 // If casting the result of another cast instruction, try to eliminate this
455 if (CastInst *CSrc = dyn_cast<CastInst>(CI->getOperand(0)))
456 if (isEliminableCastOfCast(CI, CSrc)) {
457 // This instruction now refers directly to the cast's src operand. This
458 // has a good chance of making CSrc dead.
459 CI->setOperand(0, CSrc->getOperand(0));
467 // PHINode simplification
469 Instruction *InstCombiner::visitPHINode(PHINode *PN) {
470 if (PN->use_empty()) return 0; // Don't fix dead instructions...
472 // If the PHI node only has one incoming value, eliminate the PHI node...
473 if (PN->getNumIncomingValues() == 1) {
474 AddUsesToWorkList(PN); // Add all modified instrs to worklist
475 PN->replaceAllUsesWith(PN->getIncomingValue(0));
483 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst *GEP) {
484 // Is it getelementptr %P, uint 0
485 // If so, elminate the noop.
486 if (GEP->getNumOperands() == 2 && !GEP->use_empty() &&
487 GEP->getOperand(1) == Constant::getNullValue(Type::UIntTy)) {
488 AddUsesToWorkList(GEP); // Add all modified instrs to worklist
489 GEP->replaceAllUsesWith(GEP->getOperand(0));
493 return visitMemAccessInst(GEP);
497 // Combine Indices - If the source pointer to this mem access instruction is a
498 // getelementptr instruction, combine the indices of the GEP into this
501 Instruction *InstCombiner::visitMemAccessInst(MemAccessInst *MAI) {
502 GetElementPtrInst *Src =
503 dyn_cast<GetElementPtrInst>(MAI->getPointerOperand());
506 std::vector<Value *> Indices;
508 // Only special case we have to watch out for is pointer arithmetic on the
510 unsigned FirstIdx = MAI->getFirstIndexOperandNumber();
511 if (FirstIdx == MAI->getNumOperands() ||
512 (FirstIdx == MAI->getNumOperands()-1 &&
513 MAI->getOperand(FirstIdx) == ConstantUInt::get(Type::UIntTy, 0))) {
514 // Replace the index list on this MAI with the index on the getelementptr
515 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
516 } else if (*MAI->idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) {
517 // Otherwise we can do the fold if the first index of the GEP is a zero
518 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
519 Indices.insert(Indices.end(), MAI->idx_begin()+1, MAI->idx_end());
522 if (Indices.empty()) return 0; // Can't do the fold?
524 switch (MAI->getOpcode()) {
525 case Instruction::GetElementPtr:
526 return new GetElementPtrInst(Src->getOperand(0), Indices, MAI->getName());
527 case Instruction::Load:
528 return new LoadInst(Src->getOperand(0), Indices, MAI->getName());
529 case Instruction::Store:
530 return new StoreInst(MAI->getOperand(0), Src->getOperand(0), Indices);
532 assert(0 && "Unknown memaccessinst!");
540 bool InstCombiner::runOnFunction(Function *F) {
541 bool Changed = false;
543 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
545 while (!WorkList.empty()) {
546 Instruction *I = WorkList.back(); // Get an instruction from the worklist
549 // Now that we have an instruction, try combining it to simplify it...
550 Instruction *Result = visit(I);
553 // Should we replace the old instruction with a new one?
555 // Instructions can end up on the worklist more than once. Make sure
556 // we do not process an instruction that has been deleted.
557 std::vector<Instruction*>::iterator It = std::find(WorkList.begin(),
559 while (It != WorkList.end()) {
560 It = WorkList.erase(It);
561 It = std::find(It, WorkList.end(), I);
564 ReplaceInstWithInst(I, Result);
567 WorkList.push_back(Result);
568 AddUsesToWorkList(Result);
576 Pass *createInstructionCombiningPass() {
577 return new InstCombiner();