LLVM 24.0.0git
CFGMST.h
Go to the documentation of this file.
1//===-- CFGMST.h - Minimum Spanning Tree for CFG ----------------*- C++ -*-===//
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 file implements a Union-find algorithm to compute Minimum Spanning Tree
10// for a given CFG.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_INSTRUMENTATION_CFGMST_H
15#define LLVM_TRANSFORMS_INSTRUMENTATION_CFGMST_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/Analysis/CFG.h"
27#include "llvm/Support/Debug.h"
30#include <utility>
31#include <vector>
32
33#define DEBUG_TYPE "cfgmst"
34
35namespace llvm {
36
37/// An union-find based Minimum Spanning Tree for CFG
38///
39/// Implements a Union-find algorithm to compute Minimum Spanning Tree
40/// for a given CFG.
41template <class Edge, class BBInfo> class CFGMST {
42 Function &F;
43
44 // Store all the edges in CFG. It may contain some stale edges
45 // when Removed is set.
46 std::vector<std::unique_ptr<Edge>> AllEdges;
47
48 // This map records the auxiliary information for each BB.
50
51 // Whehter the function has an exit block with no successors.
52 // (For function with an infinite loop, this block may be absent)
53 bool ExitBlockFound = false;
54
55 BranchProbabilityInfo *const BPI;
56 BlockFrequencyInfo *const BFI;
57 LoopInfo *const LI;
58
59 // If function entry will be always instrumented.
60 const bool InstrumentFuncEntry;
61
62 // If true loop entries will be always instrumented.
63 const bool InstrumentLoopEntries;
64
65 // Find the root group of the G and compress the path from G to the root.
66 BBInfo *findAndCompressGroup(BBInfo *G) {
67 if (G->Group != G)
68 G->Group = findAndCompressGroup(static_cast<BBInfo *>(G->Group));
69 return static_cast<BBInfo *>(G->Group);
70 }
71
72 // Union BB1 and BB2 into the same group and return true.
73 // Returns false if BB1 and BB2 are already in the same group.
74 bool unionGroups(const BasicBlock *BB1, const BasicBlock *BB2) {
75 BBInfo *BB1G = findAndCompressGroup(&getBBInfo(BB1));
76 BBInfo *BB2G = findAndCompressGroup(&getBBInfo(BB2));
77
78 if (BB1G == BB2G)
79 return false;
80
81 // Make the smaller rank tree a direct child or the root of high rank tree.
82 if (BB1G->Rank < BB2G->Rank)
83 BB1G->Group = BB2G;
84 else {
85 BB2G->Group = BB1G;
86 // If the ranks are the same, increment root of one tree by one.
87 if (BB1G->Rank == BB2G->Rank)
88 BB1G->Rank++;
89 }
90 return true;
91 }
92
93 void handleCoroSuspendEdge(Edge *E) {
94 // We must not add instrumentation to the BB representing the
95 // "suspend" path, else CoroSplit won't be able to lower
96 // llvm.coro.suspend to a tail call. We do want profiling info for
97 // the other branches (resume/destroy). So we do 2 things:
98 // 1. we prefer instrumenting those other edges by setting the weight
99 // of the "suspend" edge to max, and
100 // 2. we mark the edge as "Removed" to guarantee it is not considered
101 // for instrumentation. That could technically happen:
102 // (from test/Transforms/Coroutines/coro-split-musttail.ll)
103 //
104 // %suspend = call i8 @llvm.coro.suspend(token %save, i1 false)
105 // switch i8 %suspend, label %exit [
106 // i8 0, label %await.ready
107 // i8 1, label %exit
108 // ]
109 if (!E->DestBB)
110 return;
111 assert(E->SrcBB);
112 if (llvm::isPresplitCoroSuspendExitEdge(*E->SrcBB, *E->DestBB))
113 E->Removed = true;
114 }
115
116 // Traverse the CFG using a stack. Find all the edges and assign the weight.
117 // Edges with large weight will be put into MST first so they are less likely
118 // to be instrumented.
119 void buildEdges() {
120 LLVM_DEBUG(dbgs() << "Build Edge on " << F.getName() << "\n");
121
122 BasicBlock *Entry = &(F.getEntryBlock());
123 uint64_t EntryWeight =
124 (BFI != nullptr ? BFI->getEntryFreq().getFrequency() : 2);
125 // If we want to instrument the entry count, lower the weight to 0.
126 if (InstrumentFuncEntry)
127 EntryWeight = 0;
128 Edge *EntryIncoming = nullptr, *EntryOutgoing = nullptr,
129 *ExitOutgoing = nullptr, *ExitIncoming = nullptr;
130 uint64_t MaxEntryOutWeight = 0, MaxExitOutWeight = 0, MaxExitInWeight = 0;
131
132 // Add a fake edge to the entry.
133 EntryIncoming = &addEdge(nullptr, Entry, EntryWeight);
134 LLVM_DEBUG(dbgs() << " Edge: from fake node to " << Entry->getName()
135 << " w = " << EntryWeight << "\n");
136
137 // Special handling for single BB functions.
138 if (succ_empty(Entry)) {
139 addEdge(Entry, nullptr, EntryWeight);
140 return;
141 }
142
143 static const uint32_t CriticalEdgeMultiplier = 1000;
144
145 for (BasicBlock &BB : F) {
146 Instruction *TI = BB.getTerminator();
147 uint64_t BBWeight =
148 (BFI != nullptr ? BFI->getBlockFreq(&BB).getFrequency() : 2);
149 uint64_t Weight = 2;
150 if (int successors = TI->getNumSuccessors()) {
151 for (int i = 0; i != successors; ++i) {
152 BasicBlock *TargetBB = TI->getSuccessor(i);
153 bool Critical = isCriticalEdge(TI, i);
154 uint64_t scaleFactor = BBWeight;
155 if (Critical) {
156 if (scaleFactor < UINT64_MAX / CriticalEdgeMultiplier)
157 scaleFactor *= CriticalEdgeMultiplier;
158 else
159 scaleFactor = UINT64_MAX;
160 }
161 if (BPI != nullptr)
162 Weight = BPI->getEdgeProbability(&BB, TargetBB).scale(scaleFactor);
163 // If InstrumentLoopEntries is on and the current edge leads to a loop
164 // (i.e., TargetBB is a loop head and BB is outside its loop), set
165 // Weight to be minimal, so that the edge won't be chosen for the MST
166 // and will be instrumented.
167 if (InstrumentLoopEntries && LI->isLoopHeader(TargetBB)) {
168 Loop *TargetLoop = LI->getLoopFor(TargetBB);
169 assert(TargetLoop);
170 if (!TargetLoop->contains(&BB))
171 Weight = 0;
172 }
173 if (Weight == 0)
174 Weight++;
175 auto *E = &addEdge(&BB, TargetBB, Weight);
176 E->IsCritical = Critical;
177 handleCoroSuspendEdge(E);
178 LLVM_DEBUG(dbgs() << " Edge: from " << BB.getName() << " to "
179 << TargetBB->getName() << " w=" << Weight << "\n");
180
181 // Keep track of entry/exit edges:
182 if (&BB == Entry) {
183 if (Weight > MaxEntryOutWeight) {
184 MaxEntryOutWeight = Weight;
185 EntryOutgoing = E;
186 }
187 }
188
189 if (!TargetBB->getTerminator()->getNumSuccessors()) {
190 if (Weight > MaxExitInWeight) {
191 MaxExitInWeight = Weight;
192 ExitIncoming = E;
193 }
194 }
195 }
196 } else {
197 ExitBlockFound = true;
198 Edge *ExitO = &addEdge(&BB, nullptr, BBWeight);
199 if (BBWeight > MaxExitOutWeight) {
200 MaxExitOutWeight = BBWeight;
201 ExitOutgoing = ExitO;
202 }
203 LLVM_DEBUG(dbgs() << " Edge: from " << BB.getName() << " to fake exit"
204 << " w = " << BBWeight << "\n");
205 }
206 }
207
208 // Entry/exit edge adjustment heurisitic:
209 // prefer instrumenting entry edge over exit edge
210 // if possible. Those exit edges may never have a chance to be
211 // executed (for instance the program is an event handling loop)
212 // before the profile is asynchronously dumped.
213 //
214 // If EntryIncoming and ExitOutgoing has similar weight, make sure
215 // ExitOutging is selected as the min-edge. Similarly, if EntryOutgoing
216 // and ExitIncoming has similar weight, make sure ExitIncoming becomes
217 // the min-edge.
218 uint64_t EntryInWeight = EntryWeight;
219
220 if (EntryInWeight >= MaxExitOutWeight &&
221 EntryInWeight * 2 < MaxExitOutWeight * 3) {
222 EntryIncoming->Weight = MaxExitOutWeight;
223 ExitOutgoing->Weight = EntryInWeight + 1;
224 }
225
226 if (MaxEntryOutWeight >= MaxExitInWeight &&
227 MaxEntryOutWeight * 2 < MaxExitInWeight * 3) {
228 EntryOutgoing->Weight = MaxExitInWeight;
229 ExitIncoming->Weight = MaxEntryOutWeight + 1;
230 }
231 }
232
233 // Sort CFG edges based on its weight.
234 void sortEdgesByWeight() {
235 llvm::stable_sort(AllEdges, [](const std::unique_ptr<Edge> &Edge1,
236 const std::unique_ptr<Edge> &Edge2) {
237 return Edge1->Weight > Edge2->Weight;
238 });
239 }
240
241 // Traverse all the edges and compute the Minimum Weight Spanning Tree
242 // using union-find algorithm.
243 void computeMinimumSpanningTree() {
244 // First, put all the critical edge with landing-pad as the Dest to MST.
245 // This works around the insufficient support of critical edges split
246 // when destination BB is a landing pad.
247 for (auto &Ei : AllEdges) {
248 if (Ei->Removed)
249 continue;
250 if (Ei->IsCritical) {
251 if (Ei->DestBB && Ei->DestBB->isLandingPad()) {
252 if (unionGroups(Ei->SrcBB, Ei->DestBB))
253 Ei->InMST = true;
254 }
255 }
256 }
257
258 for (auto &Ei : AllEdges) {
259 if (Ei->Removed)
260 continue;
261 // If we detect infinite loops, force
262 // instrumenting the entry edge:
263 if (!ExitBlockFound && Ei->SrcBB == nullptr)
264 continue;
265 if (unionGroups(Ei->SrcBB, Ei->DestBB))
266 Ei->InMST = true;
267 }
268 }
269
270 [[maybe_unused]] bool validateLoopEntryInstrumentation() {
271 if (!InstrumentLoopEntries)
272 return true;
273 for (auto &Ei : AllEdges) {
274 if (Ei->Removed)
275 continue;
276 if (Ei->DestBB && LI->isLoopHeader(Ei->DestBB) &&
277 !LI->getLoopFor(Ei->DestBB)->contains(Ei->SrcBB) && Ei->InMST)
278 return false;
279 }
280 return true;
281 }
282
283public:
284 // Dump the Debug information about the instrumentation.
285 void dumpEdges(raw_ostream &OS, const Twine &Message) const {
286 if (!Message.str().empty())
287 OS << Message << "\n";
288 OS << " Number of Basic Blocks: " << BBInfos.size() << "\n";
289 // Collect and sort BBInfos deterministically by their assigned Index.
290 std::vector<std::pair<const BasicBlock *, const BBInfo *>> SortedBBInfos;
291 SortedBBInfos.reserve(BBInfos.size());
292 for (const auto &BI : BBInfos)
293 SortedBBInfos.emplace_back(BI.first, BI.second.get());
294
295#ifndef NDEBUG
296 SmallDenseSet<uint32_t, 16> SeenIndices;
297 for (const auto &P : SortedBBInfos)
298 assert(SeenIndices.insert(P.second->Index).second &&
299 "BBInfo indices should be unique");
300#endif
301
302 llvm::sort(SortedBBInfos, [](const auto &A, const auto &B) {
303 // Primary key: BBInfo Index
304 if (A.second->Index != B.second->Index)
305 return A.second->Index < B.second->Index;
306 // Secondary key: name string to keep a stable order even if
307 // indices tie (ties shouldn't happen, but this makes ordering
308 // explicit).
309 StringRef NameA = A.first ? A.first->getName() : StringRef("FakeNode");
310 StringRef NameB = B.first ? B.first->getName() : StringRef("FakeNode");
311 return NameA < NameB;
312 });
313
314 for (const auto &P : SortedBBInfos) {
315 const BasicBlock *BB = P.first;
316 const BBInfo *Info = P.second;
317 OS << " BB: " << (BB == nullptr ? "FakeNode" : BB->getName()) << " "
318 << Info->infoString() << "\n";
319 }
320 OS << " Number of Edges: " << AllEdges.size()
321 << " (*: Instrument, C: CriticalEdge, -: Removed)\n";
322 uint32_t Count = 0;
323 for (auto &EI : AllEdges)
324 OS << " Edge " << Count++ << ": " << getBBInfo(EI->SrcBB).Index << "-->"
325 << getBBInfo(EI->DestBB).Index << EI->infoString() << "\n";
326 }
327
328 // Add an edge to AllEdges with weight W.
329 Edge &addEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W) {
330 uint32_t Index = BBInfos.size();
331 auto Iter = BBInfos.end();
332 bool Inserted;
333 std::tie(Iter, Inserted) = BBInfos.try_emplace(Src);
334 if (Inserted) {
335 // Newly inserted, update the real info.
336 Iter->second = std::make_unique<BBInfo>(Index);
337 Index++;
338 }
339 std::tie(Iter, Inserted) = BBInfos.try_emplace(Dest);
340 if (Inserted)
341 // Newly inserted, update the real info.
342 Iter->second = std::make_unique<BBInfo>(Index);
343 AllEdges.emplace_back(new Edge(Src, Dest, W));
344 return *AllEdges.back();
345 }
346
347 CFGMST(Function &Func, bool InstrumentFuncEntry, bool InstrumentLoopEntries,
348 BranchProbabilityInfo *BPI = nullptr,
349 BlockFrequencyInfo *BFI = nullptr, LoopInfo *LI = nullptr)
350 : F(Func), BPI(BPI), BFI(BFI), LI(LI),
351 InstrumentFuncEntry(InstrumentFuncEntry),
352 InstrumentLoopEntries(InstrumentLoopEntries) {
353 assert(!(InstrumentLoopEntries && !LI) &&
354 "expected a LoopInfo to instrumenting loop entries");
355 buildEdges();
356 sortEdgesByWeight();
357 computeMinimumSpanningTree();
358 assert(validateLoopEntryInstrumentation() &&
359 "Loop entries should not be in MST when "
360 "InstrumentLoopEntries is on");
361 if (AllEdges.size() > 1 && InstrumentFuncEntry)
362 std::iter_swap(std::move(AllEdges.begin()),
363 std::move(AllEdges.begin() + AllEdges.size() - 1));
364 }
365
366 const std::vector<std::unique_ptr<Edge>> &allEdges() const {
367 return AllEdges;
368 }
369
370 std::vector<std::unique_ptr<Edge>> &allEdges() { return AllEdges; }
371
372 size_t numEdges() const { return AllEdges.size(); }
373
374 size_t bbInfoSize() const { return BBInfos.size(); }
375
376 // Give BB, return the auxiliary information.
377 BBInfo &getBBInfo(const BasicBlock *BB) const {
378 auto It = BBInfos.find(BB);
379 assert(It->second.get() != nullptr);
380 return *It->second.get();
381 }
382
383 // Give BB, return the auxiliary information if it's available.
384 BBInfo *findBBInfo(const BasicBlock *BB) const {
385 auto It = BBInfos.find(BB);
386 if (It == BBInfos.end())
387 return nullptr;
388 return It->second.get();
389 }
390};
391
392} // end namespace llvm
393
394#undef DEBUG_TYPE // "cfgmst"
395
396#endif // LLVM_TRANSFORMS_INSTRUMENTATION_CFGMST_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
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")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
#define G(x, y, z)
Definition MD5.cpp:55
#define P(N)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
std::vector< std::unique_ptr< Edge > > & allEdges()
Definition CFGMST.h:370
Edge & addEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W)
Definition CFGMST.h:329
const std::vector< std::unique_ptr< Edge > > & allEdges() const
Definition CFGMST.h:366
size_t bbInfoSize() const
Definition CFGMST.h:374
size_t numEdges() const
Definition CFGMST.h:372
CFGMST(Function &Func, bool InstrumentFuncEntry, bool InstrumentLoopEntries, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, LoopInfo *LI=nullptr)
Definition CFGMST.h:347
BBInfo * findBBInfo(const BasicBlock *BB) const
Definition CFGMST.h:384
BBInfo & getBBInfo(const BasicBlock *BB) const
Definition CFGMST.h:377
void dumpEdges(raw_ostream &OS, const Twine &Message) const
Definition CFGMST.h:285
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define UINT64_MAX
Definition DataTypes.h:77
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool succ_empty(const Instruction *I)
Definition CFG.h:141
auto successors(const MachineBasicBlock *BB)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
LLVM_ABI bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
Definition CFG.cpp:424