1 //===- DivRemPairs.cpp - Hoist/[dr]ecompose division and remainder --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass hoists and/or decomposes/recomposes integer division and remainder 10 // instructions to enable CFG improvements and better codegen. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/DivRemPairs.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/MapVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/Analysis/GlobalsModRef.h" 19 #include "llvm/Analysis/TargetTransformInfo.h" 20 #include "llvm/IR/Dominators.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/PatternMatch.h" 23 #include "llvm/Pass.h" 24 #include "llvm/Support/DebugCounter.h" 25 #include "llvm/Transforms/Scalar.h" 26 #include "llvm/Transforms/Utils/BypassSlowDivision.h" 27 28 using namespace llvm; 29 using namespace llvm::PatternMatch; 30 31 #define DEBUG_TYPE "div-rem-pairs" 32 STATISTIC(NumPairs, "Number of div/rem pairs"); 33 STATISTIC(NumRecomposed, "Number of instructions recomposed"); 34 STATISTIC(NumHoisted, "Number of instructions hoisted"); 35 STATISTIC(NumDecomposed, "Number of instructions decomposed"); 36 DEBUG_COUNTER(DRPCounter, "div-rem-pairs-transform", 37 "Controls transformations in div-rem-pairs pass"); 38 39 namespace { 40 struct ExpandedMatch { 41 DivRemMapKey Key; 42 Instruction *Value; 43 }; 44 } // namespace 45 46 /// See if we can match: (which is the form we expand into) 47 /// X - ((X ?/ Y) * Y) 48 /// which is equivalent to: 49 /// X ?% Y 50 static llvm::Optional<ExpandedMatch> matchExpandedRem(Instruction &I) { 51 Value *Dividend, *XroundedDownToMultipleOfY; 52 if (!match(&I, m_Sub(m_Value(Dividend), m_Value(XroundedDownToMultipleOfY)))) 53 return llvm::None; 54 55 Value *Divisor; 56 Instruction *Div; 57 // Look for ((X / Y) * Y) 58 if (!match( 59 XroundedDownToMultipleOfY, 60 m_c_Mul(m_CombineAnd(m_IDiv(m_Specific(Dividend), m_Value(Divisor)), 61 m_Instruction(Div)), 62 m_Deferred(Divisor)))) 63 return llvm::None; 64 65 ExpandedMatch M; 66 M.Key.SignedOp = Div->getOpcode() == Instruction::SDiv; 67 M.Key.Dividend = Dividend; 68 M.Key.Divisor = Divisor; 69 M.Value = &I; 70 return M; 71 } 72 73 /// A thin wrapper to store two values that we matched as div-rem pair. 74 /// We want this extra indirection to avoid dealing with RAUW'ing the map keys. 75 struct DivRemPairWorklistEntry { 76 /// The actual udiv/sdiv instruction. Source of truth. 77 AssertingVH<Instruction> DivInst; 78 79 /// The instruction that we have matched as a remainder instruction. 80 /// Should only be used as Value, don't introspect it. 81 AssertingVH<Instruction> RemInst; 82 83 DivRemPairWorklistEntry(Instruction *DivInst_, Instruction *RemInst_) 84 : DivInst(DivInst_), RemInst(RemInst_) { 85 assert((DivInst->getOpcode() == Instruction::UDiv || 86 DivInst->getOpcode() == Instruction::SDiv) && 87 "Not a division."); 88 assert(DivInst->getType() == RemInst->getType() && "Types should match."); 89 // We can't check anything else about remainder instruction, 90 // it's not strictly required to be a urem/srem. 91 } 92 93 /// The type for this pair, identical for both the div and rem. 94 Type *getType() const { return DivInst->getType(); } 95 96 /// Is this pair signed or unsigned? 97 bool isSigned() const { return DivInst->getOpcode() == Instruction::SDiv; } 98 99 /// In this pair, what are the divident and divisor? 100 Value *getDividend() const { return DivInst->getOperand(0); } 101 Value *getDivisor() const { return DivInst->getOperand(1); } 102 103 bool isRemExpanded() const { 104 switch (RemInst->getOpcode()) { 105 case Instruction::SRem: 106 case Instruction::URem: 107 return false; // single 'rem' instruction - unexpanded form. 108 default: 109 return true; // anything else means we have remainder in expanded form. 110 } 111 } 112 }; 113 using DivRemWorklistTy = SmallVector<DivRemPairWorklistEntry, 4>; 114 115 /// Find matching pairs of integer div/rem ops (they have the same numerator, 116 /// denominator, and signedness). Place those pairs into a worklist for further 117 /// processing. This indirection is needed because we have to use TrackingVH<> 118 /// because we will be doing RAUW, and if one of the rem instructions we change 119 /// happens to be an input to another div/rem in the maps, we'd have problems. 120 static DivRemWorklistTy getWorklist(Function &F) { 121 // Insert all divide and remainder instructions into maps keyed by their 122 // operands and opcode (signed or unsigned). 123 DenseMap<DivRemMapKey, Instruction *> DivMap; 124 // Use a MapVector for RemMap so that instructions are moved/inserted in a 125 // deterministic order. 126 MapVector<DivRemMapKey, Instruction *> RemMap; 127 for (auto &BB : F) { 128 for (auto &I : BB) { 129 if (I.getOpcode() == Instruction::SDiv) 130 DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; 131 else if (I.getOpcode() == Instruction::UDiv) 132 DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; 133 else if (I.getOpcode() == Instruction::SRem) 134 RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; 135 else if (I.getOpcode() == Instruction::URem) 136 RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; 137 else if (auto Match = matchExpandedRem(I)) 138 RemMap[Match->Key] = Match->Value; 139 } 140 } 141 142 // We'll accumulate the matching pairs of div-rem instructions here. 143 DivRemWorklistTy Worklist; 144 145 // We can iterate over either map because we are only looking for matched 146 // pairs. Choose remainders for efficiency because they are usually even more 147 // rare than division. 148 for (auto &RemPair : RemMap) { 149 // Find the matching division instruction from the division map. 150 Instruction *DivInst = DivMap[RemPair.first]; 151 if (!DivInst) 152 continue; 153 154 // We have a matching pair of div/rem instructions. 155 NumPairs++; 156 Instruction *RemInst = RemPair.second; 157 158 // Place it in the worklist. 159 Worklist.emplace_back(DivInst, RemInst); 160 } 161 162 return Worklist; 163 } 164 165 /// Find matching pairs of integer div/rem ops (they have the same numerator, 166 /// denominator, and signedness). If they exist in different basic blocks, bring 167 /// them together by hoisting or replace the common division operation that is 168 /// implicit in the remainder: 169 /// X % Y <--> X - ((X / Y) * Y). 170 /// 171 /// We can largely ignore the normal safety and cost constraints on speculation 172 /// of these ops when we find a matching pair. This is because we are already 173 /// guaranteed that any exceptions and most cost are already incurred by the 174 /// first member of the pair. 175 /// 176 /// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or 177 /// SimplifyCFG, but it's split off on its own because it's different enough 178 /// that it doesn't quite match the stated objectives of those passes. 179 static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI, 180 const DominatorTree &DT) { 181 bool Changed = false; 182 183 // Get the matching pairs of div-rem instructions. We want this extra 184 // indirection to avoid dealing with having to RAUW the keys of the maps. 185 DivRemWorklistTy Worklist = getWorklist(F); 186 187 // Process each entry in the worklist. 188 for (DivRemPairWorklistEntry &E : Worklist) { 189 if (!DebugCounter::shouldExecute(DRPCounter)) 190 continue; 191 192 bool HasDivRemOp = TTI.hasDivRemOp(E.getType(), E.isSigned()); 193 194 auto &DivInst = E.DivInst; 195 auto &RemInst = E.RemInst; 196 197 const bool RemOriginallyWasInExpandedForm = E.isRemExpanded(); 198 (void)RemOriginallyWasInExpandedForm; // suppress unused variable warning 199 200 if (HasDivRemOp && E.isRemExpanded()) { 201 // The target supports div+rem but the rem is expanded. 202 // We should recompose it first. 203 Value *X = E.getDividend(); 204 Value *Y = E.getDivisor(); 205 Instruction *RealRem = E.isSigned() ? BinaryOperator::CreateSRem(X, Y) 206 : BinaryOperator::CreateURem(X, Y); 207 // Note that we place it right next to the original expanded instruction, 208 // and letting further handling to move it if needed. 209 RealRem->setName(RemInst->getName() + ".recomposed"); 210 RealRem->insertAfter(RemInst); 211 Instruction *OrigRemInst = RemInst; 212 // Update AssertingVH<> with new instruction so it doesn't assert. 213 RemInst = RealRem; 214 // And replace the original instruction with the new one. 215 OrigRemInst->replaceAllUsesWith(RealRem); 216 OrigRemInst->eraseFromParent(); 217 NumRecomposed++; 218 // Note that we have left ((X / Y) * Y) around. 219 // If it had other uses we could rewrite it as X - X % Y 220 } 221 222 assert((!E.isRemExpanded() || !HasDivRemOp) && 223 "*If* the target supports div-rem, then by now the RemInst *is* " 224 "Instruction::[US]Rem."); 225 226 // If the target supports div+rem and the instructions are in the same block 227 // already, there's nothing to do. The backend should handle this. If the 228 // target does not support div+rem, then we will decompose the rem. 229 if (HasDivRemOp && RemInst->getParent() == DivInst->getParent()) 230 continue; 231 232 bool DivDominates = DT.dominates(DivInst, RemInst); 233 if (!DivDominates && !DT.dominates(RemInst, DivInst)) { 234 // We have matching div-rem pair, but they are in two different blocks, 235 // neither of which dominates one another. 236 // FIXME: We could hoist both ops to the common predecessor block? 237 continue; 238 } 239 240 // The target does not have a single div/rem operation, 241 // and the rem is already in expanded form. Nothing to do. 242 if (!HasDivRemOp && E.isRemExpanded()) 243 continue; 244 245 if (HasDivRemOp) { 246 // The target has a single div/rem operation. Hoist the lower instruction 247 // to make the matched pair visible to the backend. 248 if (DivDominates) 249 RemInst->moveAfter(DivInst); 250 else 251 DivInst->moveAfter(RemInst); 252 NumHoisted++; 253 } else { 254 // The target does not have a single div/rem operation, 255 // and the rem is *not* in a already-expanded form. 256 // Decompose the remainder calculation as: 257 // X % Y --> X - ((X / Y) * Y). 258 259 assert(!RemOriginallyWasInExpandedForm && 260 "We should not be expanding if the rem was in expanded form to " 261 "begin with."); 262 263 Value *X = E.getDividend(); 264 Value *Y = E.getDivisor(); 265 Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y); 266 Instruction *Sub = BinaryOperator::CreateSub(X, Mul); 267 268 // If the remainder dominates, then hoist the division up to that block: 269 // 270 // bb1: 271 // %rem = srem %x, %y 272 // bb2: 273 // %div = sdiv %x, %y 274 // --> 275 // bb1: 276 // %div = sdiv %x, %y 277 // %mul = mul %div, %y 278 // %rem = sub %x, %mul 279 // 280 // If the division dominates, it's already in the right place. The mul+sub 281 // will be in a different block because we don't assume that they are 282 // cheap to speculatively execute: 283 // 284 // bb1: 285 // %div = sdiv %x, %y 286 // bb2: 287 // %rem = srem %x, %y 288 // --> 289 // bb1: 290 // %div = sdiv %x, %y 291 // bb2: 292 // %mul = mul %div, %y 293 // %rem = sub %x, %mul 294 // 295 // If the div and rem are in the same block, we do the same transform, 296 // but any code movement would be within the same block. 297 298 if (!DivDominates) 299 DivInst->moveBefore(RemInst); 300 Mul->insertAfter(RemInst); 301 Sub->insertAfter(Mul); 302 303 // Now kill the explicit remainder. We have replaced it with: 304 // (sub X, (mul (div X, Y), Y) 305 Sub->setName(RemInst->getName() + ".decomposed"); 306 Instruction *OrigRemInst = RemInst; 307 // Update AssertingVH<> with new instruction so it doesn't assert. 308 RemInst = Sub; 309 // And replace the original instruction with the new one. 310 OrigRemInst->replaceAllUsesWith(Sub); 311 OrigRemInst->eraseFromParent(); 312 NumDecomposed++; 313 } 314 Changed = true; 315 } 316 317 return Changed; 318 } 319 320 // Pass manager boilerplate below here. 321 322 namespace { 323 struct DivRemPairsLegacyPass : public FunctionPass { 324 static char ID; 325 DivRemPairsLegacyPass() : FunctionPass(ID) { 326 initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry()); 327 } 328 329 void getAnalysisUsage(AnalysisUsage &AU) const override { 330 AU.addRequired<DominatorTreeWrapperPass>(); 331 AU.addRequired<TargetTransformInfoWrapperPass>(); 332 AU.setPreservesCFG(); 333 AU.addPreserved<DominatorTreeWrapperPass>(); 334 AU.addPreserved<GlobalsAAWrapperPass>(); 335 FunctionPass::getAnalysisUsage(AU); 336 } 337 338 bool runOnFunction(Function &F) override { 339 if (skipFunction(F)) 340 return false; 341 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 342 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 343 return optimizeDivRem(F, TTI, DT); 344 } 345 }; 346 } // namespace 347 348 char DivRemPairsLegacyPass::ID = 0; 349 INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs", 350 "Hoist/decompose integer division and remainder", false, 351 false) 352 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 353 INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs", 354 "Hoist/decompose integer division and remainder", false, 355 false) 356 FunctionPass *llvm::createDivRemPairsPass() { 357 return new DivRemPairsLegacyPass(); 358 } 359 360 PreservedAnalyses DivRemPairsPass::run(Function &F, 361 FunctionAnalysisManager &FAM) { 362 TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); 363 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); 364 if (!optimizeDivRem(F, TTI, DT)) 365 return PreservedAnalyses::all(); 366 // TODO: This pass just hoists/replaces math ops - all analyses are preserved? 367 PreservedAnalyses PA; 368 PA.preserveSet<CFGAnalyses>(); 369 PA.preserve<GlobalsAA>(); 370 return PA; 371 } 372