LLVM  10.0.0svn
DivRemPairs.cpp
Go to the documentation of this file.
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 
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/Statistic.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/PatternMatch.h"
23 #include "llvm/Pass.h"
25 #include "llvm/Transforms/Scalar.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 {
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
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.
76  /// The actual udiv/sdiv instruction. Source of truth.
78 
79  /// The instruction that we have matched as a remainder instruction.
80  /// Should only be used as Value, don't introspect it.
82 
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 };
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.
121  // Insert all divide and remainder instructions into maps keyed by their
122  // operands and opcode (signed or unsigned).
124  // Use a MapVector for RemMap so that instructions are moved/inserted in a
125  // deterministic order.
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  assert(!RemOriginallyWasInExpandedForm &&
237  "Won't happen for expanded-form rem.");
238  // FIXME: We could hoist both ops to the common predecessor block?
239  continue;
240  }
241 
242  // The target does not have a single div/rem operation,
243  // and the rem is already in expanded form. Nothing to do.
244  if (!HasDivRemOp && E.isRemExpanded())
245  continue;
246 
247  if (HasDivRemOp) {
248  // The target has a single div/rem operation. Hoist the lower instruction
249  // to make the matched pair visible to the backend.
250  if (DivDominates)
251  RemInst->moveAfter(DivInst);
252  else
253  DivInst->moveAfter(RemInst);
254  NumHoisted++;
255  } else {
256  // The target does not have a single div/rem operation,
257  // and the rem is *not* in a already-expanded form.
258  // Decompose the remainder calculation as:
259  // X % Y --> X - ((X / Y) * Y).
260 
261  assert(!RemOriginallyWasInExpandedForm &&
262  "We should not be expanding if the rem was in expanded form to "
263  "begin with.");
264 
265  Value *X = E.getDividend();
266  Value *Y = E.getDivisor();
267  Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y);
268  Instruction *Sub = BinaryOperator::CreateSub(X, Mul);
269 
270  // If the remainder dominates, then hoist the division up to that block:
271  //
272  // bb1:
273  // %rem = srem %x, %y
274  // bb2:
275  // %div = sdiv %x, %y
276  // -->
277  // bb1:
278  // %div = sdiv %x, %y
279  // %mul = mul %div, %y
280  // %rem = sub %x, %mul
281  //
282  // If the division dominates, it's already in the right place. The mul+sub
283  // will be in a different block because we don't assume that they are
284  // cheap to speculatively execute:
285  //
286  // bb1:
287  // %div = sdiv %x, %y
288  // bb2:
289  // %rem = srem %x, %y
290  // -->
291  // bb1:
292  // %div = sdiv %x, %y
293  // bb2:
294  // %mul = mul %div, %y
295  // %rem = sub %x, %mul
296  //
297  // If the div and rem are in the same block, we do the same transform,
298  // but any code movement would be within the same block.
299 
300  if (!DivDominates)
301  DivInst->moveBefore(RemInst);
302  Mul->insertAfter(RemInst);
303  Sub->insertAfter(Mul);
304 
305  // Now kill the explicit remainder. We have replaced it with:
306  // (sub X, (mul (div X, Y), Y)
307  Sub->setName(RemInst->getName() + ".decomposed");
308  Instruction *OrigRemInst = RemInst;
309  // Update AssertingVH<> with new instruction so it doesn't assert.
310  RemInst = Sub;
311  // And replace the original instruction with the new one.
312  OrigRemInst->replaceAllUsesWith(Sub);
313  OrigRemInst->eraseFromParent();
314  NumDecomposed++;
315  }
316  Changed = true;
317  }
318 
319  return Changed;
320 }
321 
322 // Pass manager boilerplate below here.
323 
324 namespace {
325 struct DivRemPairsLegacyPass : public FunctionPass {
326  static char ID;
327  DivRemPairsLegacyPass() : FunctionPass(ID) {
329  }
330 
331  void getAnalysisUsage(AnalysisUsage &AU) const override {
334  AU.setPreservesCFG();
338  }
339 
340  bool runOnFunction(Function &F) override {
341  if (skipFunction(F))
342  return false;
343  auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
344  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
345  return optimizeDivRem(F, TTI, DT);
346  }
347 };
348 } // namespace
349 
351 INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs",
352  "Hoist/decompose integer division and remainder", false,
353  false)
355 INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs",
356  "Hoist/decompose integer division and remainder", false,
357  false)
359  return new DivRemPairsLegacyPass();
360 }
361 
366  if (!optimizeDivRem(F, TTI, DT))
367  return PreservedAnalyses::all();
368  // TODO: This pass just hoists/replaces math ops - all analyses are preserved?
370  PA.preserveSet<CFGAnalyses>();
371  PA.preserve<GlobalsAA>();
372  return PA;
373 }
Legacy wrapper pass to provide the GlobalsAAResult object.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:641
Type * getType() const
The type for this pair, identical for both the div and rem.
Definition: DivRemPairs.cpp:94
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:70
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:728
static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI, const DominatorTree &DT)
Find matching pairs of integer div/rem ops (they have the same numerator, denominator, and signedness).
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:776
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This is the interface for a simple mod/ref and alias analysis over globals.
Analysis pass providing the TargetTransformInfo.
void initializeDivRemPairsLegacyPassPass(PassRegistry &)
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:37
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:230
F(f)
INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) INITIALIZE_PASS_END(DivRemPairsLegacyPass
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
AssertingVH< Instruction > RemInst
The instruction that we have matched as a remainder instruction.
Definition: DivRemPairs.cpp:81
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:285
Value * getDivisor() const
This file provides an implementation of debug counters.
div rem Hoist decompose integer division and remainder
Key
PAL metadata keys.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:96
div rem pairs
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool hasDivRemOp(Type *DataType, bool IsSigned) const
Return true if the target has a unified operation to calculate division and remainder.
A thin wrapper to store two values that we matched as div-rem pair.
Definition: DivRemPairs.cpp:75
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Value * getOperand(unsigned i) const
Definition: User.h:169
static bool runOnFunction(Function &F, bool PostInlining)
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
AssertingVH< Instruction > DivInst
The actual udiv/sdiv instruction. Source of truth.
Definition: DivRemPairs.cpp:77
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static DivRemWorklistTy getWorklist(Function &F)
Find matching pairs of integer div/rem ops (they have the same numerator, denominator, and signedness).
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:576
FunctionPass * createDivRemPairsPass()
Represent the analysis usage information of a pass.
Analysis pass providing a never-invalidated alias analysis result.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:73
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool isRemExpanded() const
deferredval_ty< Value > m_Deferred(Value *const &V)
A commutative-friendly version of m_Specific().
Definition: PatternMatch.h:589
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:248
static llvm::Optional< ExpandedMatch > matchExpandedRem(Instruction &I)
See if we can match: (which is the form we expand into) X - ((X ?/ Y) * Y) which is equivalent to: X ...
Definition: DivRemPairs.cpp:50
DivRemPairWorklistEntry(Instruction *DivInst_, Instruction *RemInst_)
Definition: DivRemPairs.cpp:83
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:301
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:114
DEBUG_COUNTER(DRPCounter, "div-rem-pairs-transform", "Controls transformations in div-rem-pairs pass")
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Value * getDividend() const
In this pair, what are the divident and divisor?
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:189
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
Definition: Instruction.cpp:79
#define I(x, y, z)
Definition: MD5.cpp:58
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:174
bool isSigned() const
Is this pair signed or unsigned?
Definition: DivRemPairs.cpp:97
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:143
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
This pass exposes codegen information to IR-level passes.
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:553