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"
31 class InstCombiner : public FunctionPass,
32 public InstVisitor<InstCombiner, Instruction*> {
33 // Worklist of all of the instructions that need to be simplified.
34 std::vector<Instruction*> WorkList;
36 void AddUsesToWorkList(Instruction *I) {
37 // The instruction was simplified, add all users of the instruction to
38 // the work lists because they might get more simplified now...
40 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
42 WorkList.push_back(cast<Instruction>(*UI));
46 const char *getPassName() const { return "Instruction Combining"; }
48 virtual bool runOnFunction(Function *F);
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 // Visitation implementation - Implement instruction combining for different
55 // instruction types. The semantics are as follows:
57 // null - No change was made
58 // I - Change was made, I is still valid
59 // otherwise - Change was made, replace I with returned instruction
61 Instruction *visitNot(UnaryOperator *I);
62 Instruction *visitAdd(BinaryOperator *I);
63 Instruction *visitSub(BinaryOperator *I);
64 Instruction *visitMul(BinaryOperator *I);
65 Instruction *visitDiv(BinaryOperator *I);
66 Instruction *visitRem(BinaryOperator *I);
67 Instruction *visitAnd(BinaryOperator *I);
68 Instruction *visitOr (BinaryOperator *I);
69 Instruction *visitXor(BinaryOperator *I);
70 Instruction *visitSetCondInst(BinaryOperator *I);
71 Instruction *visitShiftInst(Instruction *I);
72 Instruction *visitCastInst(CastInst *CI);
73 Instruction *visitPHINode(PHINode *PN);
74 Instruction *visitGetElementPtrInst(GetElementPtrInst *GEP);
75 Instruction *visitMemAccessInst(MemAccessInst *MAI);
77 // visitInstruction - Specify what to return for unhandled instructions...
78 Instruction *visitInstruction(Instruction *I) { return 0; }
83 Instruction *InstCombiner::visitNot(UnaryOperator *I) {
84 if (I->use_empty()) return 0; // Don't fix dead instructions...
87 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(0)))
88 if (Op->getOpcode() == Instruction::Not) {
89 AddUsesToWorkList(I); // Add all modified instrs to worklist
90 I->replaceAllUsesWith(Op->getOperand(0));
97 // Make sure that this instruction has a constant on the right hand side if it
98 // has any constant arguments. If not, fix it an return true.
100 static bool SimplifyBinOp(BinaryOperator *I) {
101 if (isa<Constant>(I->getOperand(0)) && !isa<Constant>(I->getOperand(1)))
102 return !I->swapOperands();
106 // dyn_castNegInst - Given a 'sub' instruction, return the RHS of the
107 // instruction if the LHS is a constant zero (which is the 'negate' form).
109 static inline Value *dyn_castNegInst(Value *V) {
110 Instruction *I = dyn_cast<Instruction>(V);
111 if (!I || I->getOpcode() != Instruction::Sub) return 0;
113 if (I->getOperand(0) == Constant::getNullValue(I->getType()))
114 return I->getOperand(1);
118 Instruction *InstCombiner::visitAdd(BinaryOperator *I) {
119 if (I->use_empty()) return 0; // Don't fix dead add instructions...
120 bool Changed = SimplifyBinOp(I);
121 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
123 // Eliminate 'add int %X, 0'
124 if (I->getType()->isIntegral() &&
125 RHS == Constant::getNullValue(I->getType())) {
126 AddUsesToWorkList(I); // Add all modified instrs to worklist
127 I->replaceAllUsesWith(LHS);
132 if (Value *V = dyn_castNegInst(LHS))
133 return BinaryOperator::create(Instruction::Sub, RHS, V);
136 if (Value *V = dyn_castNegInst(RHS))
137 return BinaryOperator::create(Instruction::Sub, LHS, V);
139 // Simplify add instructions with a constant RHS...
140 if (Constant *Op2 = dyn_cast<Constant>(RHS)) {
141 if (BinaryOperator *ILHS = dyn_cast<BinaryOperator>(LHS)) {
142 if (ILHS->getOpcode() == Instruction::Add &&
143 isa<Constant>(ILHS->getOperand(1))) {
145 // %Y = add int %X, 1
146 // %Z = add int %Y, 1
148 // %Z = add int %X, 2
150 if (Constant *Val = *Op2 + *cast<Constant>(ILHS->getOperand(1))) {
151 I->setOperand(0, ILHS->getOperand(0));
152 I->setOperand(1, Val);
159 return Changed ? I : 0;
162 Instruction *InstCombiner::visitSub(BinaryOperator *I) {
163 if (I->use_empty()) return 0; // Don't fix dead add instructions...
164 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
166 if (Op0 == Op1) { // sub X, X -> 0
167 AddUsesToWorkList(I); // Add all modified instrs to worklist
168 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
172 // If this is a subtract instruction with a constant RHS, convert it to an add
173 // instruction of a negative constant
175 if (Constant *Op2 = dyn_cast<Constant>(Op1))
176 if (Constant *RHS = *Constant::getNullValue(I->getType()) - *Op2) // 0 - RHS
177 return BinaryOperator::create(Instruction::Add, Op0, RHS, I->getName());
179 // If this is a 'C = x-B', check to see if 'B = -A', so that C = x+A...
180 if (Value *V = dyn_castNegInst(Op1))
181 return BinaryOperator::create(Instruction::Add, Op0, V);
183 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression is
184 // not used by anyone else...
186 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
187 if (Op1I->use_size() == 1) {
188 // Swap the two operands of the subexpr...
189 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
190 Op1I->setOperand(0, IIOp1);
191 Op1I->setOperand(1, IIOp0);
193 // Create the new top level add instruction...
194 return BinaryOperator::create(Instruction::Add, Op0, Op1);
199 Instruction *InstCombiner::visitMul(BinaryOperator *I) {
200 if (I->use_empty()) return 0; // Don't fix dead instructions...
201 bool Changed = SimplifyBinOp(I);
202 Value *Op1 = I->getOperand(0);
204 // Simplify add instructions with a constant RHS...
205 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(1))) {
206 if (I->getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1)){
207 // Eliminate 'mul int %X, 1'
208 AddUsesToWorkList(I); // Add all modified instrs to worklist
209 I->replaceAllUsesWith(Op1);
212 } else if (I->getType()->isIntegral() &&
213 cast<ConstantInt>(Op2)->equalsInt(2)) {
214 // Convert 'mul int %X, 2' to 'add int %X, %X'
215 return BinaryOperator::create(Instruction::Add, Op1, Op1, I->getName());
217 } else if (Op2->isNullValue()) {
218 // Eliminate 'mul int %X, 0'
219 AddUsesToWorkList(I); // Add all modified instrs to worklist
220 I->replaceAllUsesWith(Op2); // Set this value to zero directly
225 return Changed ? I : 0;
229 Instruction *InstCombiner::visitDiv(BinaryOperator *I) {
230 if (I->use_empty()) return 0; // Don't fix dead instructions...
233 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
234 if (RHS->equalsInt(1)) {
235 AddUsesToWorkList(I); // Add all modified instrs to worklist
236 I->replaceAllUsesWith(I->getOperand(0));
243 Instruction *InstCombiner::visitRem(BinaryOperator *I) {
244 if (I->use_empty()) return 0; // Don't fix dead instructions...
247 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
248 if (RHS->equalsInt(1)) {
249 AddUsesToWorkList(I); // Add all modified instrs to worklist
250 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
256 static Constant *getMaxValue(const Type *Ty) {
257 assert(Ty == Type::BoolTy || Ty->isIntegral());
258 if (Ty == Type::BoolTy)
259 return ConstantBool::True;
262 return ConstantSInt::get(Ty, -1);
263 else if (Ty->isUnsigned()) {
264 // Calculate -1 casted to the right type...
265 unsigned TypeBits = Ty->getPrimitiveSize()*8;
266 uint64_t Val = (uint64_t)-1LL; // All ones
267 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
268 return ConstantUInt::get(Ty, Val);
274 Instruction *InstCombiner::visitAnd(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);
279 // and X, X = X and X, 0 == 0
280 if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
281 AddUsesToWorkList(I); // Add all modified instrs to worklist
282 I->replaceAllUsesWith(Op1);
287 if (Constant *RHS = dyn_cast<Constant>(Op1))
288 if (RHS == getMaxValue(I->getType())) {
289 AddUsesToWorkList(I); // Add all modified instrs to worklist
290 I->replaceAllUsesWith(Op0);
294 return Changed ? I : 0;
299 Instruction *InstCombiner::visitOr(BinaryOperator *I) {
300 if (I->use_empty()) return 0; // Don't fix dead instructions...
301 bool Changed = SimplifyBinOp(I);
302 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
304 // or X, X = X or X, 0 == X
305 if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
306 AddUsesToWorkList(I); // Add all modified instrs to worklist
307 I->replaceAllUsesWith(Op0);
312 if (Constant *RHS = dyn_cast<Constant>(Op1))
313 if (RHS == getMaxValue(I->getType())) {
314 AddUsesToWorkList(I); // Add all modified instrs to worklist
315 I->replaceAllUsesWith(Op1);
319 return Changed ? I : 0;
324 Instruction *InstCombiner::visitXor(BinaryOperator *I) {
325 if (I->use_empty()) return 0; // Don't fix dead instructions...
326 bool Changed = SimplifyBinOp(I);
327 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
331 AddUsesToWorkList(I); // Add all modified instrs to worklist
332 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
337 if (Op1 == Constant::getNullValue(I->getType())) {
338 AddUsesToWorkList(I); // Add all modified instrs to worklist
339 I->replaceAllUsesWith(Op0);
343 return Changed ? I : 0;
346 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
347 // true when both operands are equal...
349 static bool isTrueWhenEqual(Instruction *I) {
350 return I->getOpcode() == Instruction::SetEQ ||
351 I->getOpcode() == Instruction::SetGE ||
352 I->getOpcode() == Instruction::SetLE;
355 Instruction *InstCombiner::visitSetCondInst(BinaryOperator *I) {
356 if (I->use_empty()) return 0; // Don't fix dead instructions...
357 bool Changed = SimplifyBinOp(I);
360 if (I->getOperand(0) == I->getOperand(1)) {
361 AddUsesToWorkList(I); // Add all modified instrs to worklist
362 I->replaceAllUsesWith(ConstantBool::get(isTrueWhenEqual(I)));
366 // setcc <global*>, 0 - Global value addresses are never null!
367 if (isa<GlobalValue>(I->getOperand(0)) &&
368 isa<ConstantPointerNull>(I->getOperand(1))) {
369 AddUsesToWorkList(I); // Add all modified instrs to worklist
370 I->replaceAllUsesWith(ConstantBool::get(!isTrueWhenEqual(I)));
374 return Changed ? I : 0;
379 Instruction *InstCombiner::visitShiftInst(Instruction *I) {
380 if (I->use_empty()) return 0; // Don't fix dead instructions...
381 assert(I->getOperand(1)->getType() == Type::UByteTy);
382 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
384 // shl X, 0 == X and shr X, 0 == X
385 // shl 0, X == 0 and shr 0, X == 0
386 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
387 Op0 == Constant::getNullValue(Op0->getType())) {
388 AddUsesToWorkList(I); // Add all modified instrs to worklist
389 I->replaceAllUsesWith(Op0);
393 // shl int X, 32 = 0 and shr sbyte Y, 9 = 0, ... just don't eliminate shr of
396 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
397 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
398 if (CUI->getValue() >= TypeBits &&
399 !(Op0->getType()->isSigned() && I->getOpcode() == Instruction::Shr)) {
400 AddUsesToWorkList(I); // Add all modified instrs to worklist
401 I->replaceAllUsesWith(Constant::getNullValue(Op0->getType()));
409 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
412 static inline bool isEliminableCastOfCast(const CastInst *CI,
413 const CastInst *CSrc) {
414 assert(CI->getOperand(0) == CSrc);
415 const Type *SrcTy = CSrc->getOperand(0)->getType();
416 const Type *MidTy = CSrc->getType();
417 const Type *DstTy = CI->getType();
419 // It is legal to eliminate the instruction if casting A->B->A
420 if (SrcTy == DstTy) return true;
422 // Allow free casting and conversion of sizes as long as the sign doesn't
424 if (SrcTy->isSigned() == MidTy->isSigned() &&
425 MidTy->isSigned() == DstTy->isSigned())
428 // Otherwise, we cannot succeed. Specifically we do not want to allow things
429 // like: short -> ushort -> uint, because this can create wrong results if
430 // the input short is negative!
436 // CastInst simplification
438 Instruction *InstCombiner::visitCastInst(CastInst *CI) {
439 if (CI->use_empty()) return 0; // Don't fix dead instructions...
441 // If the user is casting a value to the same type, eliminate this cast
443 if (CI->getType() == CI->getOperand(0)->getType() && !CI->use_empty()) {
444 AddUsesToWorkList(CI); // Add all modified instrs to worklist
445 CI->replaceAllUsesWith(CI->getOperand(0));
450 // If casting the result of another cast instruction, try to eliminate this
453 if (CastInst *CSrc = dyn_cast<CastInst>(CI->getOperand(0)))
454 if (isEliminableCastOfCast(CI, CSrc)) {
455 // This instruction now refers directly to the cast's src operand. This
456 // has a good chance of making CSrc dead.
457 CI->setOperand(0, CSrc->getOperand(0));
465 // PHINode simplification
467 Instruction *InstCombiner::visitPHINode(PHINode *PN) {
468 if (PN->use_empty()) return 0; // Don't fix dead instructions...
470 // If the PHI node only has one incoming value, eliminate the PHI node...
471 if (PN->getNumIncomingValues() == 1) {
472 AddUsesToWorkList(PN); // Add all modified instrs to worklist
473 PN->replaceAllUsesWith(PN->getIncomingValue(0));
481 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst *GEP) {
482 // Is it getelementptr %P, uint 0
483 // If so, elminate the noop.
484 if (GEP->getNumOperands() == 2 && !GEP->use_empty() &&
485 GEP->getOperand(1) == Constant::getNullValue(Type::UIntTy)) {
486 AddUsesToWorkList(GEP); // Add all modified instrs to worklist
487 GEP->replaceAllUsesWith(GEP->getOperand(0));
491 return visitMemAccessInst(GEP);
495 // Combine Indices - If the source pointer to this mem access instruction is a
496 // getelementptr instruction, combine the indices of the GEP into this
499 Instruction *InstCombiner::visitMemAccessInst(MemAccessInst *MAI) {
500 GetElementPtrInst *Src =
501 dyn_cast<GetElementPtrInst>(MAI->getPointerOperand());
504 std::vector<Value *> Indices;
506 // Only special case we have to watch out for is pointer arithmetic on the
508 unsigned FirstIdx = MAI->getFirstIndexOperandNumber();
509 if (FirstIdx == MAI->getNumOperands() ||
510 (FirstIdx == MAI->getNumOperands()-1 &&
511 MAI->getOperand(FirstIdx) == ConstantUInt::get(Type::UIntTy, 0))) {
512 // Replace the index list on this MAI with the index on the getelementptr
513 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
514 } else if (*MAI->idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) {
515 // Otherwise we can do the fold if the first index of the GEP is a zero
516 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
517 Indices.insert(Indices.end(), MAI->idx_begin()+1, MAI->idx_end());
520 if (Indices.empty()) return 0; // Can't do the fold?
522 switch (MAI->getOpcode()) {
523 case Instruction::GetElementPtr:
524 return new GetElementPtrInst(Src->getOperand(0), Indices, MAI->getName());
525 case Instruction::Load:
526 return new LoadInst(Src->getOperand(0), Indices, MAI->getName());
527 case Instruction::Store:
528 return new StoreInst(MAI->getOperand(0), Src->getOperand(0), Indices);
530 assert(0 && "Unknown memaccessinst!");
538 bool InstCombiner::runOnFunction(Function *F) {
539 bool Changed = false;
541 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
543 while (!WorkList.empty()) {
544 Instruction *I = WorkList.back(); // Get an instruction from the worklist
547 // Now that we have an instruction, try combining it to simplify it...
548 Instruction *Result = visit(I);
550 // Should we replace the old instruction with a new one?
552 ReplaceInstWithInst(I, Result);
554 WorkList.push_back(Result);
555 AddUsesToWorkList(Result);
563 Pass *createInstructionCombiningPass() {
564 return new InstCombiner();