LLVM 24.0.0git
WebAssemblyCFGSort.cpp
Go to the documentation of this file.
1//===-- WebAssemblyCFGSort.cpp - CFG Sorting ------------------------------===//
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/// \file
10/// This file implements a CFG sorting pass.
11///
12/// This pass reorders the blocks in a function to put them into topological
13/// order, ignoring loop backedges, and without any loop or exception being
14/// interrupted by a block not dominated by the its header, with special care
15/// to keep the order as similar as possible to the original order.
16///
17////===----------------------------------------------------------------------===//
18
19#include "WebAssembly.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/IR/Analysis.h"
33#include "llvm/Support/Debug.h"
35using namespace llvm;
38
39#define DEBUG_TYPE "wasm-cfg-sort"
40
41namespace {
42
43class WebAssemblyCFGSortLegacy final : public MachineFunctionPass {
44 StringRef getPassName() const override { return "WebAssembly CFG Sort"; }
45
46 void getAnalysisUsage(AnalysisUsage &AU) const override {
47 AU.setPreservesCFG();
52 }
53
54 bool runOnMachineFunction(MachineFunction &MF) override;
55
56public:
57 static char ID; // Pass identification, replacement for typeid
58 WebAssemblyCFGSortLegacy() : MachineFunctionPass(ID) {}
59};
60} // end anonymous namespace
61
62char WebAssemblyCFGSortLegacy::ID = 0;
63INITIALIZE_PASS(WebAssemblyCFGSortLegacy, DEBUG_TYPE,
64 "Reorders blocks in topological order", false, false)
65
67 return new WebAssemblyCFGSortLegacy();
68}
69
71#ifndef NDEBUG
72 bool AnyBarrier = false;
73#endif
74 bool AllAnalyzable = true;
75 for (const MachineInstr &Term : MBB->terminators()) {
76#ifndef NDEBUG
77 AnyBarrier |= Term.isBarrier();
78#endif
79 AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
80 }
81 assert((AnyBarrier || AllAnalyzable) &&
82 "analyzeBranch needs to analyze any block with a fallthrough");
83
84 // Find the layout successor from the original block order.
85 MachineFunction *MF = MBB->getParent();
86 MachineBasicBlock *OriginalSuccessor =
87 unsigned(MBB->getNumber() + 1) < MF->getNumBlockIDs()
88 ? MF->getBlockNumbered(MBB->getNumber() + 1)
89 : nullptr;
90
91 if (AllAnalyzable)
92 MBB->updateTerminator(OriginalSuccessor);
93}
94
95namespace {
96// EH pads are selected first regardless of the block comparison order.
97// When only one of the BBs is an EH pad, we give a higher priority to it, to
98// prevent common mismatches between possibly throwing calls and ehpads they
99// unwind to, as in the example below:
100//
101// bb0:
102// call @foo // If this throws, unwind to bb2
103// bb1:
104// call @bar // If this throws, unwind to bb3
105// bb2 (ehpad):
106// handler_bb2
107// bb3 (ehpad):
108// handler_bb3
109// continuing code
110//
111// Because this pass tries to preserve the original BB order, this order will
112// not change. But this will result in this try-catch structure in CFGStackify,
113// resulting in a mismatch:
114// try
115// try
116// call @foo
117// call @bar // This should unwind to bb3, not bb2!
118// catch
119// handler_bb2
120// end
121// catch
122// handler_bb3
123// end
124// continuing code
125//
126// If we give a higher priority to an EH pad whenever it is ready in this
127// example, when both bb1 and bb2 are ready, we would pick up bb2 first.
128
129/// Sort blocks by their number.
130struct CompareBlockNumbers {
131 bool EHPadSort;
132 bool operator()(const MachineBasicBlock *A,
133 const MachineBasicBlock *B) const {
134 if (EHPadSort) {
135 if (A->isEHPad() && !B->isEHPad())
136 return false;
137 if (!A->isEHPad() && B->isEHPad())
138 return true;
139 }
140
141 return A->getNumber() > B->getNumber();
142 }
143};
144/// Sort blocks by their number in the opposite order..
145struct CompareBlockNumbersBackwards {
146 bool EHPadSort;
147 bool operator()(const MachineBasicBlock *A,
148 const MachineBasicBlock *B) const {
149 if (EHPadSort) {
150 if (A->isEHPad() && !B->isEHPad())
151 return false;
152 if (!A->isEHPad() && B->isEHPad())
153 return true;
154 }
155
156 return A->getNumber() < B->getNumber();
157 }
158};
159/// Bookkeeping for a region to help ensure that we don't mix blocks not
160/// dominated by the its header among its blocks.
161struct Entry {
162 const SortRegion *TheRegion;
163 unsigned NumBlocksLeft;
164
165 /// List of blocks not dominated by Loop's header that are deferred until
166 /// after all of Loop's blocks have been seen.
167 std::vector<MachineBasicBlock *> Deferred;
168
169 explicit Entry(const SortRegion *R)
170 : TheRegion(R), NumBlocksLeft(R->getNumBlocks()) {}
171};
172} // end anonymous namespace
173
174/// Sort the blocks, taking special care to make sure that regions are not
175/// interrupted by blocks not dominated by their header.
176/// TODO: There are many opportunities for improving the heuristics here.
177/// Explore them.
178static void sortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
179 const WebAssemblyExceptionInfo &WEI,
181 // Remember original layout ordering, so we can update terminators after
182 // reordering to point to the original layout successor.
183 MF.RenumberBlocks();
184
185 // Prepare for a topological sort: Record the number of predecessors each
186 // block has, ignoring loop backedges.
187 SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
188 for (MachineBasicBlock &MBB : MF) {
189 unsigned N = MBB.pred_size();
190 if (MachineLoop *L = MLI.getLoopFor(&MBB))
191 if (L->getHeader() == &MBB)
192 for (const MachineBasicBlock *Pred : MBB.predecessors())
193 if (L->contains(Pred))
194 --N;
195 NumPredsLeft[MBB.getNumber()] = N;
196 }
197
198 const bool EHPadSort =
199 MF.getSubtarget<WebAssemblySubtarget>().getCLOpts().ehpad_sort;
200 // Topological sort the CFG, with additional constraints:
201 // - Between a region header and the last block in the region, there can be
202 // no blocks not dominated by its header.
203 // - It's desirable to preserve the original block order when possible.
204 // We use two ready lists; Preferred and Ready. Preferred has recently
205 // processed successors, to help preserve block sequences from the original
206 // order. Ready has the remaining ready blocks. EH blocks are picked first
207 // from both queues.
209 CompareBlockNumbers>
210 Preferred(CompareBlockNumbers{EHPadSort});
212 CompareBlockNumbersBackwards>
213 Ready(CompareBlockNumbersBackwards{EHPadSort});
214
215 SortRegionInfo SRI(MLI, WEI);
216 SmallVector<Entry, 4> Entries;
217 for (MachineBasicBlock *MBB = &MF.front();;) {
218 const SortRegion *R = SRI.getRegionFor(MBB);
219 if (R) {
220 // If MBB is a region header, add it to the active region list. We can't
221 // put any blocks that it doesn't dominate until we see the end of the
222 // region.
223 if (R->getHeader() == MBB)
224 Entries.push_back(Entry(R));
225 // For each active region the block is in, decrement the count. If MBB is
226 // the last block in an active region, take it off the list and pick up
227 // any blocks deferred because the header didn't dominate them.
228 for (Entry &E : Entries)
229 if (E.TheRegion->contains(MBB) && --E.NumBlocksLeft == 0)
230 for (auto *DeferredBlock : E.Deferred)
231 Ready.push(DeferredBlock);
232 while (!Entries.empty() && Entries.back().NumBlocksLeft == 0)
233 Entries.pop_back();
234 }
235 // The main topological sort logic.
236 for (MachineBasicBlock *Succ : MBB->successors()) {
237 // Ignore backedges.
238 if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
239 if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
240 continue;
241 // Decrement the predecessor count. If it's now zero, it's ready.
242 if (--NumPredsLeft[Succ->getNumber()] == 0)
243 Preferred.push(Succ);
244 }
245 // Determine the block to follow MBB. First try to find a preferred block,
246 // to preserve the original block order when possible.
247 MachineBasicBlock *Next = nullptr;
248 while (!Preferred.empty()) {
249 Next = Preferred.top();
250 Preferred.pop();
251 // If X isn't dominated by the top active region header, defer it until
252 // that region is done.
253 if (!Entries.empty() &&
254 !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
255 Entries.back().Deferred.push_back(Next);
256 Next = nullptr;
257 continue;
258 }
259 // If Next was originally ordered before MBB, and it isn't because it was
260 // loop-rotated above the header, it's not preferred.
261 if (Next->getNumber() < MBB->getNumber() &&
262 (!EHPadSort || !Next->isEHPad()) &&
263 (!R || !R->contains(Next) ||
264 R->getHeader()->getNumber() < Next->getNumber())) {
265 Ready.push(Next);
266 Next = nullptr;
267 continue;
268 }
269 break;
270 }
271 // If we didn't find a suitable block in the Preferred list, check the
272 // general Ready list.
273 if (!Next) {
274 // If there are no more blocks to process, we're done.
275 if (Ready.empty()) {
277 break;
278 }
279 for (;;) {
280 Next = Ready.top();
281 Ready.pop();
282 // If Next isn't dominated by the top active region header, defer it
283 // until that region is done.
284 if (!Entries.empty() &&
285 !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
286 Entries.back().Deferred.push_back(Next);
287 continue;
288 }
289 break;
290 }
291 }
292 // Move the next block into place and iterate.
293 Next->moveAfter(MBB);
295 MBB = Next;
296 }
297 assert(Entries.empty() && "Active sort region list not finished");
298 MF.RenumberBlocks();
299
300#ifndef NDEBUG
301 for (auto &MBB : MF) {
302 assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
303 const SortRegion *Region = SRI.getRegionFor(&MBB);
304
305 if (Region && &MBB == Region->getHeader()) {
306 // Region header.
307 if (Region->isLoop()) {
308 // Loop header. The loop predecessor should be sorted above, and the
309 // other predecessors should be backedges below.
310 for (auto *Pred : MBB.predecessors())
311 assert(
312 (Pred->getNumber() < MBB.getNumber() || Region->contains(Pred)) &&
313 "Loop header predecessors must be loop predecessors or "
314 "backedges");
315 } else {
316 // Exception header. All predecessors should be sorted above.
317 for (auto *Pred : MBB.predecessors())
318 assert(Pred->getNumber() < MBB.getNumber() &&
319 "Non-loop-header predecessors should be topologically sorted");
320 }
321 } else {
322 // Not a region header. All predecessors should be sorted above.
323 for (auto *Pred : MBB.predecessors())
324 assert(Pred->getNumber() < MBB.getNumber() &&
325 "Non-loop-header predecessors should be topologically sorted");
326 }
327 }
328
330 for (auto &MBB : MF) {
331 const SortRegion *Region = SRI.getRegionFor(&MBB);
332 if (Region)
333 Regions.insert(Region);
334 }
335
336 SmallVector<std::pair<int, int>, 8> RegionIntervals(Regions.size(), {-1, -1});
337
338 unsigned RegionIdx = 0;
339 for (auto *Region : Regions) {
340 assert(Region->getHeader() != &MF.front() &&
341 "The function entry block shouldn't actually be a region header");
342
343 auto *Header = Region->getHeader();
344 auto *Bottom = SRI.getBottom(Region);
345
346 assert(Header && "Regions must have a header");
347 assert(Bottom && "Regions must have a bottom");
348
349 std::pair<int, int> Interval = {Header->getNumber(), Bottom->getNumber()};
350 assert(Interval.first <= Interval.second &&
351 "Region bottoms must be sorted after region headers");
352
353 RegionIntervals[RegionIdx++] = Interval;
354
355 for (auto *MBB : Region->blocks()) {
356 assert(MBB->getNumber() >= Interval.first &&
357 MBB->getNumber() <= Interval.second &&
358 "All blocks within a region must have numbers within the region's "
359 "interval");
360 }
361 }
362
363 for (const auto &IntervalA : RegionIntervals) {
364 for (const auto &IntervalB : RegionIntervals) {
365 auto AContainsB = IntervalA.first <= IntervalB.first &&
366 IntervalA.second >= IntervalB.second;
367 auto BContainsA = IntervalB.first <= IntervalA.first &&
368 IntervalB.second >= IntervalA.second;
369 auto Disjoint = IntervalA.second < IntervalB.first ||
370 IntervalA.first > IntervalB.second;
371 assert((AContainsB || BContainsA || Disjoint) &&
372 "Regions must be fully contained within their parents and not "
373 "overlap their siblings");
374 }
375 }
376#endif
377}
378
381 LLVM_DEBUG(dbgs() << "********** CFG Sorting **********\n"
382 "********** Function: "
383 << MF.getName() << '\n');
384
385 // Liveness is not tracked for VALUE_STACK physreg.
387
388 // Sort the blocks, with contiguous sort regions.
389 sortBlocks(MF, MLI, WEI, MDT);
390
391 return true;
392}
393
394bool WebAssemblyCFGSortLegacy::runOnMachineFunction(MachineFunction &MF) {
395 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
396 WebAssemblyExceptionInfo &WEI =
397 getAnalysis<WebAssemblyExceptionInfoWrapperPass>().getWEI();
398 MachineDominatorTree &MDT =
399 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
400 return sortCFG(MF, MLI, WEI, MDT);
401}
402
403PreservedAnalyses
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< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
std::pair< uint64_t, uint64_t > Interval
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the PriorityQueue class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool sortCFG(MachineFunction &MF, MachineLoopInfo &MLI, WebAssemblyExceptionInfo &WEI, MachineDominatorTree &MDT)
static void maybeUpdateTerminator(MachineBasicBlock *MBB)
This file implements WebAssemblyException information analysis.
This file implements regions used in CFGSort and CFGStackify.
This file declares the WebAssembly-specific subclass of TargetSubtarget.
This file contains the declaration of the WebAssembly-specific utility functions.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
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
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineBasicBlock & front() const
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
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:152
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
block_range blocks()
Returns a range view of the basic blocks in the region.
Definition RegionInfo.h:616
bool contains(const BlockT *BB) const
Check if the region contains a BasicBlock.
size_type size() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Pass manager infrastructure for declaring and invalidating analyses.
@ Entry
Definition COFF.h:862
This is an optimization pass for GlobalISel generic memory operations.
bool sortBlocks(Function &F)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
FunctionPass * createWebAssemblyCFGSortLegacyPass()
#define N