Index: llvm/lib/Transforms/Utils/BypassSlowDivision.cpp =================================================================== --- llvm/lib/Transforms/Utils/BypassSlowDivision.cpp +++ llvm/lib/Transforms/Utils/BypassSlowDivision.cpp @@ -247,5 +247,22 @@ MadeChange |= reuseOrInsertFastDiv(I, BT, UseDivOp, UseSignedOp, DivCache); } + // Above we eagerly create divs and rems, as pairs, so that we can efficiently + // create divrem machine instructions. Now erase unused any divs / rems so we + // don't leave extra instructions sitting around. + SmallVector ToErase; + for (auto &KV : DivCache) + for (Instruction *Phi : {KV.second.Quotient, KV.second.Remainder}) { + if (!Phi->use_empty()) + continue; + ToErase.push_back(Phi); + for (Value *Operand : Phi->operand_values()) + if (Instruction *I = dyn_cast(Operand)) + ToErase.push_back(I); + } + + for (Instruction *I : ToErase) + I->eraseFromParent(); + return MadeChange; }