LLVM 24.0.0git
LoongArchMemoryBarrierOpt.cpp
Go to the documentation of this file.
1//===---- LoongArchMemoryBarrierOpt.cpp - Memory barrier Optimization -----===//
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 removes or merges redundant memory barrier instructions.
10///
11/// - DBAR x + DBAR y -> DBAR (x & y)
12/// - DBAR x + AMO_DB -> AMO_DB
13/// - DBAR x + AMO -> AMO_DB
14/// - DBAR x + LL -> LL
15/// - AMO_DB + DBAR x -> AMO_DB
16/// - AMO + DBAR x -> AMO_DB
17/// - SC + DBAR x -> SC
18///
19//===----------------------------------------------------------------------===//
20
21#include "LoongArch.h"
22#include "LoongArchInstrInfo.h"
23#include "LoongArchSubtarget.h"
27#include "llvm/IR/Analysis.h"
29
30using namespace llvm;
31
32#define DEBUG_TYPE "loongarch-memory-barrier-opt"
33#define LOONGARCH_MEMORY_BARRIER_OPT_NAME \
34 "LoongArch Memory Barrier Optimisation pass"
35
37 "loongarch-require-no-path-bypass",
38 cl::desc("Optimize only when no paths bypass either memory barrier"),
39 cl::init(true), cl::Hidden);
40
42 "loongarch-merge-amo-with-dbar",
43 cl::desc("Merge AMOs with DBARs into AMO_DB during optimization"),
44 cl::init(true), cl::Hidden);
45
47 "loongarch-replace-eliminated-dbar-to-nop",
48 cl::desc("Replace eliminated DBARs with NOPs to preserve code layout"),
49 cl::init(false), cl::Hidden);
50
51namespace {
52
53#define AMO_CASES \
54 CASE(AMSWAP, B) \
55 CASE(AMSWAP, H) \
56 CASE(AMSWAP, W) \
57 CASE(AMSWAP, D) \
58 CASE(AMADD, B) \
59 CASE(AMADD, H) \
60 CASE(AMADD, W) \
61 CASE(AMADD, D) \
62 CASE(AMAND, W) \
63 CASE(AMAND, D) \
64 CASE(AMOR, W) \
65 CASE(AMOR, D) \
66 CASE(AMXOR, W) \
67 CASE(AMXOR, D) \
68 CASE(AMMAX, W) \
69 CASE(AMMAX, D) \
70 CASE(AMMAX, WU) \
71 CASE(AMMAX, DU) \
72 CASE(AMMIN, W) \
73 CASE(AMMIN, D) \
74 CASE(AMMIN, WU) \
75 CASE(AMMIN, DU) \
76 CASE(AMCAS, B) \
77 CASE(AMCAS, H) \
78 CASE(AMCAS, W) \
79 CASE(AMCAS, D)
80
81static bool isMB(const MachineInstr &MI) {
82 return MI.getOpcode() == LoongArch::DBAR;
83}
84
85static bool isLL(const MachineInstr &MI) {
86 switch (MI.getOpcode()) {
87 case LoongArch::LL_W:
88 case LoongArch::LL_D:
89 return true;
90 default:
91 return false;
92 }
93}
94
95static bool isSC(const MachineInstr &MI) {
96 switch (MI.getOpcode()) {
97 case LoongArch::SC_W:
98 case LoongArch::SC_D:
99 case LoongArch::SC_Q:
100 return true;
101 default:
102 return false;
103 }
104}
105
106static std::optional<unsigned> isAM(const MachineInstr &MI) {
107#define CASE(Name, Suffix) \
108 case LoongArch::Name##_##Suffix: \
109 if (!MergeAMOWithMB) \
110 return std::nullopt; \
111 [[fallthrough]]; \
112 case LoongArch::Name##__DB_##Suffix: \
113 return LoongArch::Name##__DB_##Suffix;
114 switch (MI.getOpcode()) {
116 default:
117 return std::nullopt;
118 }
119#undef CASE
120}
121
122static bool isSafeToSkip(const MachineInstr &MI) {
123 if (MI.mayLoadOrStore())
124 return false;
125 if (MI.isCall() || MI.isReturn())
126 return false;
127 if (MI.isInlineAsm())
128 return false;
129 if (MI.hasUnmodeledSideEffects())
130 return isMB(MI);
131 return true;
132}
133
134struct BarrierHint {
135 BarrierHint(unsigned Hint) : Hint(Hint) {}
136
137 bool subsumes(const BarrierHint &O) const { return (Hint & O.Hint) == Hint; }
138
139 BarrierHint merge(const BarrierHint &O) const {
140 return BarrierHint(Hint & O.Hint);
141 }
142
143 static inline bool isValid(unsigned Hint) { return (Hint & ~0x1f) == 0; }
144
145 unsigned Hint;
146};
147
148struct InstBarrier {
149 InstBarrier(MachineInstr &MI)
150 : MI(&MI), Pre(0), Post(0), OpcAMDB(0), IsMB(false), IsAM(false) {
151 if (isMB(MI)) {
152 unsigned Hint = MI.getOperand(0).getImm();
153 if (!BarrierHint::isValid(Hint))
154 return;
155 IsMB = true;
156 Pre = Post = BarrierHint(Hint);
157 } else if (isLL(MI)) {
158 IsAM = true;
159 Pre = BarrierHint(0b10000);
160 Post = BarrierHint(0b11111);
161 } else if (isSC(MI)) {
162 IsAM = true;
163 Pre = BarrierHint(0b11111);
164 Post = BarrierHint(0b10000);
165 } else if (auto R = isAM(MI)) {
166 IsAM = true;
167 OpcAMDB = *R;
168 Pre = Post = BarrierHint(0b10000);
169 }
170 }
171
172 MachineInstr *MI;
173 BarrierHint Pre;
174 BarrierHint Post;
175 StringRef OpName;
176 StringRef Operands;
177 unsigned OpcAMDB;
178 bool IsMB;
179 bool IsAM;
180};
181
182class LoongArchMemoryBarrierOptLegacy : public MachineFunctionPass {
183public:
184 static char ID;
185
186 LoongArchMemoryBarrierOptLegacy() : MachineFunctionPass(ID) {}
187
188 StringRef getPassName() const override {
190 }
191
192 void getAnalysisUsage(AnalysisUsage &AU) const override {
193 AU.setPreservesCFG();
194 AU.addRequired<MachineDominatorTreeWrapperPass>();
195 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
197 }
198
199 bool runOnMachineFunction(MachineFunction &MF) override;
200};
201
202enum : unsigned {
203 CandidateA = 1u << 0,
204 CandidateB = 1u << 1,
205};
206
207} // namespace
208
209static bool checkAllPathSafe(const MachineBasicBlock *MBBA,
210 const MachineBasicBlock *MBBB, bool IsAToB) {
211 const MachineBasicBlock *Start = IsAToB ? MBBA : MBBB;
212 const MachineBasicBlock *End = IsAToB ? MBBB : MBBA;
213
216
217 Worklist.push_back(Start);
218 Visited.insert(Start);
219
220 while (!Worklist.empty()) {
221 const MachineBasicBlock *BB = Worklist.pop_back_val();
222
223 if (BB == End)
224 continue;
225
226 if (BB != Start) {
227 for (const MachineInstr &MI : *BB) {
228 if (!isSafeToSkip(MI))
229 return false;
230 }
231 }
232
233 if (IsAToB) {
234 for (const MachineBasicBlock *Succ : BB->successors()) {
235 if (Visited.insert(Succ).second)
236 Worklist.push_back(Succ);
237 }
238 } else {
239 for (const MachineBasicBlock *Pred : BB->predecessors()) {
240 if (Visited.insert(Pred).second)
241 Worklist.push_back(Pred);
242 }
243 }
244 }
245
246 return true;
247}
248
249// Returns a bitmask indicating removal candidates: A (bit 1) and B (bit 2).
251 const MachineInstr *B,
252 const MachineDominatorTree *MDT,
253 const MachinePostDominatorTree *MPDT) {
254 const MachineBasicBlock *MBBA = A->getParent();
255 const MachineBasicBlock *MBBB = B->getParent();
256
257 if (MBBA == MBBB) {
258 /* A -> B */
259 for (auto It = std::next(A->getIterator()); It != MBBA->end(); ++It) {
260 if (It == B->getIterator())
261 return CandidateA | CandidateB;
262 if (!isSafeToSkip(*It))
263 return 0;
264 }
265 return 0;
266 }
267
268 // Cross-block walk
269 bool ADomB = MDT->dominates(MBBA, MBBB);
270 bool BPostDomA = MPDT->dominates(MBBB, MBBA);
271 unsigned Mask = 0;
272 if (!ADomB && !BPostDomA)
273 return 0;
274
275 /* A -> MBBA->end() */
276 for (auto It = std::next(A->getIterator()); It != MBBA->end(); ++It)
277 if (!isSafeToSkip(*It))
278 return 0;
279 /* B -> MBBB->begin() */
280 for (auto It = MBBB->begin(); It != B->getIterator(); ++It)
281 if (!isSafeToSkip(*It))
282 return 0;
283
284 /* MBBA -> MBBB */
285 if (BPostDomA)
286 if (checkAllPathSafe(MBBA, MBBB, true /*IsAToB*/))
287 Mask |= CandidateA;
288
289 /* MBBB -> MBBA */
290 if (ADomB)
291 if (checkAllPathSafe(MBBA, MBBB, false /*IsAToB*/))
292 Mask |= CandidateB;
293
294 return Mask;
295}
296
297// Update DBAR hint
298static void updateMB(InstBarrier &I, BarrierHint Hint) {
299 assert(I.IsMB && "Unexpected!");
300 I.Pre = I.Post = Hint;
301 I.MI->getOperand(0).setImm(Hint.Hint);
302}
303
304// Replace AMO to AMO_DB
305static void replaceAM(InstBarrier &I, MachineFunction &MF) {
306 if (!I.IsAM)
307 return;
308 if (I.OpcAMDB) {
309 auto &ST = MF.getSubtarget<LoongArchSubtarget>();
310 I.MI->setDesc(ST.getInstrInfo()->get(I.OpcAMDB));
311 }
312}
313
314static bool eliminateRedundantBarrier(InstBarrier &IA, InstBarrier &IB,
315 MachineFunction &MF,
316 const MachineDominatorTree *MDT,
317 const MachinePostDominatorTree *MPDT) {
318 MachineInstr *A = IA.MI;
319 MachineInstr *B = IB.MI;
320
321 if (!A || !B)
322 return false; // Already erased
323 if (A == B)
324 return false;
325
326 unsigned Mask = resolveBarrierRedundancy(A, B, MDT, MPDT);
327 if (!Mask)
328 return false;
329
330 auto eraseOrReplaceWithNop = [&](MachineInstr *MI) {
332 auto &ST = MF.getSubtarget<LoongArchSubtarget>();
333 BuildMI(*MI->getParent(), MI->getIterator(), MI->getDebugLoc(),
334 ST.getInstrInfo()->get(LoongArch::ANDI), LoongArch::R0)
335 .addReg(LoongArch::R0)
336 .addImm(0);
337 }
338 MI->eraseFromParent();
339 };
340
341 // A B
342 // DBAR x + DBAR y -> DBAR (x & y)
343 // DBAR x + AMO_DB -> AMO_DB
344 // DBAR x + AMO -> AMO_DB
345 // DBAR x + LL -> LL
346 if ((Mask & CandidateA) && IA.IsMB) {
347 if (!IB.Pre.subsumes(IA.Post)) {
348 if (!IB.IsMB || (RequireNoPathBypass && !(Mask & CandidateB)))
349 return false;
350 updateMB(IB, IB.Pre.merge(IA.Post));
351 }
352 replaceAM(IB, MF);
353 eraseOrReplaceWithNop(A);
354 IA.MI = nullptr;
355 return true;
356 }
357
358 // A B
359 // DBAR x + DBAR y -> DBAR (x & y)
360 // AMO_DB + DBAR x -> AMO_DB
361 // AMO + DBAR x -> AMO_DB
362 // SC + DBAR x -> SC
363 if ((Mask & CandidateB) && IB.IsMB) {
364 if (!IA.Post.subsumes(IB.Pre)) {
365 if (!IA.IsMB || (RequireNoPathBypass && !(Mask & CandidateA)))
366 return false;
367 updateMB(IA, IA.Post.merge(IB.Pre));
368 }
369 replaceAM(IA, MF);
370 eraseOrReplaceWithNop(B);
371 IB.MI = nullptr;
372 return true;
373 }
374
375 return false;
376}
377
379 const MachineDominatorTree *MDT,
380 const MachinePostDominatorTree *MPDT) {
382 bool Changed = false;
383
384 for (MachineBasicBlock &MBB : MF)
385 for (MachineInstr &MI : MBB) {
386 InstBarrier IB(MI);
387 if (IB.IsMB || IB.IsAM)
388 Sites.push_back(IB);
389 }
390
391 for (size_t a = 0; a < Sites.size(); ++a) {
392 for (size_t b = a + 1; b < Sites.size(); ++b) {
393 InstBarrier &IA = Sites[a];
394 InstBarrier &IB = Sites[b];
395 Changed |= eliminateRedundantBarrier(IA, IB, MF, MDT, MPDT);
396 Changed |= eliminateRedundantBarrier(IB, IA, MF, MDT, MPDT);
397 }
398 }
399
400 return Changed;
401}
402
403bool LoongArchMemoryBarrierOptLegacy::runOnMachineFunction(
404 MachineFunction &MF) {
405 if (skipFunction(MF.getFunction()))
406 return false;
407 return runMemoryBarrierOpt(
408 MF, &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree(),
409 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree());
410}
411
412char LoongArchMemoryBarrierOptLegacy::ID = 0;
413INITIALIZE_PASS_BEGIN(LoongArchMemoryBarrierOptLegacy, DEBUG_TYPE,
417INITIALIZE_PASS_END(LoongArchMemoryBarrierOptLegacy, DEBUG_TYPE,
419
421 return new LoongArchMemoryBarrierOptLegacy();
422}
423
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
static void replaceAM(InstBarrier &I, MachineFunction &MF)
static bool eliminateRedundantBarrier(InstBarrier &IA, InstBarrier &IB, MachineFunction &MF, const MachineDominatorTree *MDT, const MachinePostDominatorTree *MPDT)
static cl::opt< bool > RequireNoPathBypass("loongarch-require-no-path-bypass", cl::desc("Optimize only when no paths bypass either memory barrier"), cl::init(true), cl::Hidden)
static unsigned resolveBarrierRedundancy(const MachineInstr *A, const MachineInstr *B, const MachineDominatorTree *MDT, const MachinePostDominatorTree *MPDT)
#define AMO_CASES
static bool checkAllPathSafe(const MachineBasicBlock *MBBA, const MachineBasicBlock *MBBB, bool IsAToB)
static bool runMemoryBarrierOpt(MachineFunction &MF, const MachineDominatorTree *MDT, const MachinePostDominatorTree *MPDT)
#define LOONGARCH_MEMORY_BARRIER_OPT_NAME
static cl::opt< bool > ReplaceEliminatedMBToNop("loongarch-replace-eliminated-dbar-to-nop", cl::desc("Replace eliminated DBARs with NOPs to preserve code layout"), cl::init(false), cl::Hidden)
static void updateMB(InstBarrier &I, BarrierHint Hint)
static cl::opt< bool > MergeAMOWithMB("loongarch-merge-amo-with-dbar", cl::desc("Merge AMOs with DBARs into AMO_DB during optimization"), cl::init(true), cl::Hidden)
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
Pass manager infrastructure for declaring and invalidating analyses.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createLoongArchMemoryBarrierOptLegacyPass()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320