1//===-- ModuleSummaryIndex.cpp - Module Summary Index ---------------------===//
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 the module index and summary classes for the
10// IR library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/IR/ModuleSummaryIndex.h"
15#include "llvm/ADT/SCCIterator.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Path.h"
19#include "llvm/Support/raw_ostream.h"
20using namespace llvm;
21
22#define DEBUG_TYPE "module-summary-index"
23
24STATISTIC(ReadOnlyLiveGVars,
25 "Number of live global variables marked read only");
26STATISTIC(WriteOnlyLiveGVars,
27 "Number of live global variables marked write only");
28
29namespace llvm {
30cl::opt<bool>
31 AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(Val: true),
32 cl::Hidden,
33 cl::desc("Always rename promoted locals."));
34} // namespace llvm
35
36static cl::opt<bool> PropagateAttrs("propagate-attrs", cl::init(Val: true),
37 cl::Hidden,
38 cl::desc("Propagate attributes in index"));
39
40static cl::opt<bool> ImportConstantsWithRefs(
41 "import-constants-with-refs", cl::init(Val: true), cl::Hidden,
42 cl::desc("Import constant global variables with references"));
43
44FunctionSummary FunctionSummary::ExternalNode =
45 FunctionSummary::makeDummyFunctionSummary(
46 Edges: SmallVector<FunctionSummary::EdgeTy, 0>());
47
48GlobalValue::VisibilityTypes ValueInfo::getELFVisibility() const {
49 bool HasProtected = false;
50 for (const auto &S : make_pointee_range(Range: getSummaryList())) {
51 if (S.getVisibility() == GlobalValue::HiddenVisibility)
52 return GlobalValue::HiddenVisibility;
53 if (S.getVisibility() == GlobalValue::ProtectedVisibility)
54 HasProtected = true;
55 }
56 return HasProtected ? GlobalValue::ProtectedVisibility
57 : GlobalValue::DefaultVisibility;
58}
59
60bool ValueInfo::isDSOLocal(bool WithDSOLocalPropagation) const {
61 // With DSOLocal propagation done, the flag in evey summary is the same.
62 // Check the first one is enough.
63 return WithDSOLocalPropagation
64 ? getSummaryList().size() && getSummaryList()[0]->isDSOLocal()
65 : getSummaryList().size() &&
66 llvm::all_of(
67 Range: getSummaryList(),
68 P: [](const std::unique_ptr<GlobalValueSummary> &Summary) {
69 return Summary->isDSOLocal();
70 });
71}
72
73bool ValueInfo::canAutoHide() const {
74 // Can only auto hide if all copies are eligible to auto hide.
75 return getSummaryList().size() &&
76 llvm::all_of(Range: getSummaryList(),
77 P: [](const std::unique_ptr<GlobalValueSummary> &Summary) {
78 return Summary->canAutoHide();
79 });
80}
81
82// Gets the number of readonly and writeonly refs in RefEdgeList
83std::pair<unsigned, unsigned> FunctionSummary::specialRefCounts() const {
84 // Here we take advantage of having all readonly and writeonly references
85 // located in the end of the RefEdgeList.
86 auto Refs = refs();
87 unsigned RORefCnt = 0, WORefCnt = 0;
88 int I;
89 for (I = Refs.size() - 1; I >= 0 && Refs[I].isWriteOnly(); --I)
90 WORefCnt++;
91 for (; I >= 0 && Refs[I].isReadOnly(); --I)
92 RORefCnt++;
93 return {RORefCnt, WORefCnt};
94}
95
96uint64_t ModuleSummaryIndex::getFlags() const {
97 uint64_t Flags = 0;
98 // Flags & 0x4 is reserved. DO NOT REUSE.
99 if (withGlobalValueDeadStripping())
100 Flags |= 0x1;
101 if (skipModuleByDistributedBackend())
102 Flags |= 0x2;
103 if (enableSplitLTOUnit())
104 Flags |= 0x8;
105 if (partiallySplitLTOUnits())
106 Flags |= 0x10;
107 if (withAttributePropagation())
108 Flags |= 0x20;
109 if (withDSOLocalPropagation())
110 Flags |= 0x40;
111 if (withWholeProgramVisibility())
112 Flags |= 0x80;
113 if (withSupportsHotColdNew())
114 Flags |= 0x100;
115 if (hasUnifiedLTO())
116 Flags |= 0x200;
117 if (withInternalizeAndPromote())
118 Flags |= 0x400;
119 if (withSpeculativeDevirt())
120 Flags |= 0x800;
121 return Flags;
122}
123
124void ModuleSummaryIndex::setFlags(uint64_t Flags) {
125 assert(Flags <= 0xfff && "Unexpected bits in flag");
126 // 1 bit: WithGlobalValueDeadStripping flag.
127 // Set on combined index only.
128 if (Flags & 0x1)
129 setWithGlobalValueDeadStripping();
130 // 1 bit: SkipModuleByDistributedBackend flag.
131 // Set on combined index only.
132 if (Flags & 0x2)
133 setSkipModuleByDistributedBackend();
134 // Flags & 0x4 is reserved. DO NOT REUSE.
135 // 1 bit: DisableSplitLTOUnit flag.
136 // Set on per module indexes. It is up to the client to validate
137 // the consistency of this flag across modules being linked.
138 if (Flags & 0x8)
139 setEnableSplitLTOUnit();
140 // 1 bit: PartiallySplitLTOUnits flag.
141 // Set on combined index only.
142 if (Flags & 0x10)
143 setPartiallySplitLTOUnits();
144 // 1 bit: WithAttributePropagation flag.
145 // Set on combined index only.
146 if (Flags & 0x20)
147 setWithAttributePropagation();
148 // 1 bit: WithDSOLocalPropagation flag.
149 // Set on combined index only.
150 if (Flags & 0x40)
151 setWithDSOLocalPropagation();
152 // 1 bit: WithWholeProgramVisibility flag.
153 // Set on combined index only.
154 if (Flags & 0x80)
155 setWithWholeProgramVisibility();
156 // 1 bit: WithSupportsHotColdNew flag.
157 // Set on combined index only.
158 if (Flags & 0x100)
159 setWithSupportsHotColdNew();
160 // 1 bit: WithUnifiedLTO flag.
161 // Set on combined index only.
162 if (Flags & 0x200)
163 setUnifiedLTO();
164 // 1 bit: WithInternalizeAndPromote flag.
165 // Set on combined index only.
166 if (Flags & 0x400)
167 setWithInternalizeAndPromote();
168 // 1 bit: WithSpeculativeDevirt flag.
169 // Set on combined index only.
170 if (Flags & 0x800)
171 setWithSpeculativeDevirt();
172}
173
174// Collect for the given module the list of function it defines
175// (GUID -> Summary).
176void ModuleSummaryIndex::collectDefinedFunctionsForModule(
177 StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const {
178 for (auto &GlobalList : *this) {
179 auto GUID = GlobalList.first;
180 for (auto &GlobSummary : GlobalList.second.getSummaryList()) {
181 auto *Summary = dyn_cast_or_null<FunctionSummary>(Val: GlobSummary.get());
182 if (!Summary)
183 // Ignore global variable, focus on functions
184 continue;
185 // Ignore summaries from other modules.
186 if (Summary->modulePath() != ModulePath)
187 continue;
188 GVSummaryMap[GUID] = Summary;
189 }
190 }
191}
192
193GlobalValueSummary *
194ModuleSummaryIndex::getGlobalValueSummary(uint64_t ValueGUID,
195 bool PerModuleIndex) const {
196 auto VI = getValueInfo(GUID: ValueGUID);
197 assert(VI && "GlobalValue not found in index");
198 assert((!PerModuleIndex || VI.getSummaryList().size() == 1) &&
199 "Expected a single entry per global value in per-module index");
200 auto &Summary = VI.getSummaryList()[0];
201 return Summary.get();
202}
203
204bool ModuleSummaryIndex::isGUIDLive(GlobalValue::GUID GUID) const {
205 auto VI = getValueInfo(GUID);
206 if (!VI)
207 return true;
208 const auto &SummaryList = VI.getSummaryList();
209 if (SummaryList.empty())
210 return true;
211 for (auto &I : SummaryList)
212 if (isGlobalValueLive(GVS: I.get()))
213 return true;
214 return false;
215}
216
217static void
218propagateAttributesToRefs(GlobalValueSummary *S,
219 DenseSet<ValueInfo> &MarkedNonReadWriteOnly) {
220 // If reference is not readonly or writeonly then referenced summary is not
221 // read/writeonly either. Note that:
222 // - All references from GlobalVarSummary are conservatively considered as
223 // not readonly or writeonly. Tracking them properly requires more complex
224 // analysis then we have now.
225 //
226 // - AliasSummary objects have no refs at all so this function is a no-op
227 // for them.
228 for (auto &VI : S->refs()) {
229 assert(VI.getAccessSpecifier() == 0 || isa<FunctionSummary>(S));
230 if (!VI.getAccessSpecifier()) {
231 if (!MarkedNonReadWriteOnly.insert(V: VI).second)
232 continue;
233 } else if (MarkedNonReadWriteOnly.contains(V: VI))
234 continue;
235 bool HasNonGVar = false;
236 for (auto &Ref : VI.getSummaryList()) {
237 // If references to alias is not read/writeonly then aliasee
238 // is not read/writeonly
239 if (auto *GVS = dyn_cast<GlobalVarSummary>(Val: Ref->getBaseObject())) {
240 if (!VI.isReadOnly())
241 GVS->setReadOnly(false);
242 if (!VI.isWriteOnly())
243 GVS->setWriteOnly(false);
244 } else {
245 // Note that this needs special processing.
246 HasNonGVar = true;
247 break;
248 }
249 }
250 // In the case where we have a reference to a VI that is a function not a
251 // variable, conservatively mark all summaries as non-read or write only.
252 // In most cases that would have happened in the above loop. However,
253 // this will make a difference in a few rare cases where there are same
254 // named locals in modules without enough distinguishing path, which end up
255 // with the same GUID. If these are a mix of variables and functions we want
256 // to handle the variables conservatively.
257 if (HasNonGVar) {
258 for (auto &Ref : VI.getSummaryList()) {
259 auto *GVS = dyn_cast<GlobalVarSummary>(Val: Ref->getBaseObject());
260 if (!GVS)
261 continue;
262 GVS->setReadOnly(false);
263 GVS->setWriteOnly(false);
264 }
265 MarkedNonReadWriteOnly.insert(V: VI);
266 }
267 }
268}
269
270// Do the access attribute and DSOLocal propagation in combined index.
271// The goal of attribute propagation is internalization of readonly (RO)
272// or writeonly (WO) variables. To determine which variables are RO or WO
273// and which are not we take following steps:
274// - During analysis we speculatively assign readonly and writeonly
275// attribute to all variables which can be internalized. When computing
276// function summary we also assign readonly or writeonly attribute to a
277// reference if function doesn't modify referenced variable (readonly)
278// or doesn't read it (writeonly).
279//
280// - After computing dead symbols in combined index we do the attribute
281// and DSOLocal propagation. During this step we:
282// a. clear RO and WO attributes from variables which are preserved or
283// can't be imported
284// b. clear RO and WO attributes from variables referenced by any global
285// variable initializer
286// c. clear RO attribute from variable referenced by a function when
287// reference is not readonly
288// d. clear WO attribute from variable referenced by a function when
289// reference is not writeonly
290// e. clear RO and WO attributes from variables with the same GUID as
291// a non-variable.
292// f. clear IsDSOLocal flag in every summary if any of them is false.
293//
294// Because of (c, d) we don't internalize variables read by function A
295// and modified by function B.
296//
297// Internalization itself happens in the backend after import is finished
298// See internalizeGVsAfterImport.
299void ModuleSummaryIndex::propagateAttributes(
300 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
301 if (!PropagateAttrs)
302 return;
303 DenseSet<ValueInfo> MarkedNonReadWriteOnly;
304 for (auto &P : *this) {
305 bool IsDSOLocal = true;
306 for (auto &S : P.second.getSummaryList()) {
307 if (!isGlobalValueLive(GVS: S.get())) {
308 // computeDeadSymbolsAndUpdateIndirectCalls should have marked all
309 // copies live. Note that it is possible that there is a GUID collision
310 // between internal symbols with the same name in different files of the
311 // same name but not enough distinguishing path. Because
312 // computeDeadSymbolsAndUpdateIndirectCalls should conservatively mark
313 // all copies live we can assert here that all are dead if any copy is
314 // dead.
315 assert(llvm::none_of(
316 P.second.getSummaryList(),
317 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
318 return isGlobalValueLive(Summary.get());
319 }));
320 // We don't examine references from dead objects
321 break;
322 }
323
324 // Global variable can't be marked read/writeonly if it is not eligible
325 // to import since we need to ensure that all external references get
326 // a local (imported) copy. It also can't be marked read/writeonly if
327 // it or any alias (since alias points to the same memory) are preserved
328 // or notEligibleToImport, since either of those means there could be
329 // writes (or reads in case of writeonly) that are not visible (because
330 // preserved means it could have external to DSO writes or reads, and
331 // notEligibleToImport means it could have writes or reads via inline
332 // assembly leading it to be in the @llvm.*used).
333 if (auto *GVS = dyn_cast<GlobalVarSummary>(Val: S->getBaseObject()))
334 // Here we intentionally pass S.get() not GVS, because S could be
335 // an alias. We don't analyze references here, because we have to
336 // know exactly if GV is readonly to do so.
337 if (!canImportGlobalVar(S: S.get(), /* AnalyzeRefs */ false) ||
338 GUIDPreservedSymbols.count(V: P.first)) {
339 GVS->setReadOnly(false);
340 GVS->setWriteOnly(false);
341 }
342 propagateAttributesToRefs(S: S.get(), MarkedNonReadWriteOnly);
343
344 // If the flag from any summary is false, the GV is not DSOLocal.
345 IsDSOLocal &= S->isDSOLocal();
346 }
347 if (!IsDSOLocal)
348 // Mark the flag in all summaries false so that we can do quick check
349 // without going through the whole list.
350 for (const std::unique_ptr<GlobalValueSummary> &Summary :
351 P.second.getSummaryList())
352 Summary->setDSOLocal(false);
353 }
354 setWithAttributePropagation();
355 setWithDSOLocalPropagation();
356 if (llvm::AreStatisticsEnabled())
357 for (auto &P : *this)
358 if (P.second.getSummaryList().size())
359 if (auto *GVS = dyn_cast<GlobalVarSummary>(
360 Val: P.second.getSummaryList()[0]->getBaseObject()))
361 if (isGlobalValueLive(GVS)) {
362 if (GVS->maybeReadOnly())
363 ReadOnlyLiveGVars++;
364 if (GVS->maybeWriteOnly())
365 WriteOnlyLiveGVars++;
366 }
367}
368
369bool ModuleSummaryIndex::canImportGlobalVar(const GlobalValueSummary *S,
370 bool AnalyzeRefs) const {
371 bool CanImportDecl;
372 return canImportGlobalVar(S, AnalyzeRefs, CanImportDecl);
373}
374
375bool ModuleSummaryIndex::canImportGlobalVar(const GlobalValueSummary *S,
376 bool AnalyzeRefs,
377 bool &CanImportDecl) const {
378 auto HasRefsPreventingImport = [this](const GlobalVarSummary *GVS) {
379 // We don't analyze GV references during attribute propagation, so
380 // GV with non-trivial initializer can be marked either read or
381 // write-only.
382 // Importing definiton of readonly GV with non-trivial initializer
383 // allows us doing some extra optimizations (like converting indirect
384 // calls to direct).
385 // Definition of writeonly GV with non-trivial initializer should also
386 // be imported. Not doing so will result in:
387 // a) GV internalization in source module (because it's writeonly)
388 // b) Importing of GV declaration to destination module as a result
389 // of promotion.
390 // c) Link error (external declaration with internal definition).
391 // However we do not promote objects referenced by writeonly GV
392 // initializer by means of converting it to 'zeroinitializer'
393 return !(ImportConstantsWithRefs && GVS->isConstant()) &&
394 !isReadOnly(GVS) && !isWriteOnly(GVS) && GVS->refs().size();
395 };
396 auto *GVS = cast<GlobalVarSummary>(Val: S->getBaseObject());
397
398 const bool nonInterposable =
399 !GlobalValue::isInterposableLinkage(Linkage: S->linkage());
400 const bool eligibleToImport = !S->notEligibleToImport();
401
402 // It's correct to import a global variable only when it is not interposable
403 // and eligible to import.
404 CanImportDecl = (nonInterposable && eligibleToImport);
405
406 // Global variable with non-trivial initializer can be imported
407 // if it's readonly. This gives us extra opportunities for constant
408 // folding and converting indirect calls to direct calls. We don't
409 // analyze GV references during attribute propagation, because we
410 // don't know yet if it is readonly or not.
411 return nonInterposable && eligibleToImport &&
412 (!AnalyzeRefs || !HasRefsPreventingImport(GVS));
413}
414
415// TODO: write a graphviz dumper for SCCs (see ModuleSummaryIndex::exportToDot)
416// then delete this function and update its tests
417LLVM_DUMP_METHOD
418void ModuleSummaryIndex::dumpSCCs(raw_ostream &O) {
419 for (scc_iterator<ModuleSummaryIndex *> I =
420 scc_begin<ModuleSummaryIndex *>(G: this);
421 !I.isAtEnd(); ++I) {
422 O << "SCC (" << utostr(X: I->size()) << " node" << (I->size() == 1 ? "" : "s")
423 << ") {\n";
424 for (const ValueInfo &V : *I) {
425 FunctionSummary *F = nullptr;
426 if (V.getSummaryList().size())
427 F = cast<FunctionSummary>(Val: V.getSummaryList().front().get());
428 O << " " << (F == nullptr ? "External" : "") << " " << utostr(X: V.getGUID())
429 << (I.hasCycle() ? " (has cycle)" : "") << "\n";
430 }
431 O << "}\n";
432 }
433}
434
435namespace {
436struct Attributes {
437 void add(const Twine &Name, const Twine &Value,
438 const Twine &Comment = Twine());
439 void addComment(const Twine &Comment);
440 std::string getAsString() const;
441
442 std::vector<std::string> Attrs;
443 std::string Comments;
444};
445
446struct Edge {
447 uint64_t SrcMod;
448 int Hotness;
449 GlobalValue::GUID Src;
450 GlobalValue::GUID Dst;
451};
452} // namespace
453
454void Attributes::add(const Twine &Name, const Twine &Value,
455 const Twine &Comment) {
456 std::string A = Name.str();
457 A += "=\"";
458 A += Value.str();
459 A += "\"";
460 Attrs.push_back(x: A);
461 addComment(Comment);
462}
463
464void Attributes::addComment(const Twine &Comment) {
465 if (!Comment.isTriviallyEmpty()) {
466 if (Comments.empty())
467 Comments = " // ";
468 else
469 Comments += ", ";
470 Comments += Comment.str();
471 }
472}
473
474std::string Attributes::getAsString() const {
475 if (Attrs.empty())
476 return "";
477
478 std::string Ret = "[";
479 for (auto &A : Attrs)
480 Ret += A + ",";
481 Ret.pop_back();
482 Ret += "];";
483 Ret += Comments;
484 return Ret;
485}
486
487static std::string linkageToString(GlobalValue::LinkageTypes LT) {
488 switch (LT) {
489 case GlobalValue::ExternalLinkage:
490 return "extern";
491 case GlobalValue::AvailableExternallyLinkage:
492 return "av_ext";
493 case GlobalValue::LinkOnceAnyLinkage:
494 return "linkonce";
495 case GlobalValue::LinkOnceODRLinkage:
496 return "linkonce_odr";
497 case GlobalValue::WeakAnyLinkage:
498 return "weak";
499 case GlobalValue::WeakODRLinkage:
500 return "weak_odr";
501 case GlobalValue::AppendingLinkage:
502 return "appending";
503 case GlobalValue::InternalLinkage:
504 return "internal";
505 case GlobalValue::PrivateLinkage:
506 return "private";
507 case GlobalValue::ExternalWeakLinkage:
508 return "extern_weak";
509 case GlobalValue::CommonLinkage:
510 return "common";
511 }
512
513 return "<unknown>";
514}
515
516static std::string fflagsToString(FunctionSummary::FFlags F) {
517 auto FlagValue = [](unsigned V) { return V ? '1' : '0'; };
518 char FlagRep[] = {FlagValue(F.ReadNone),
519 FlagValue(F.ReadOnly),
520 FlagValue(F.NoRecurse),
521 FlagValue(F.ReturnDoesNotAlias),
522 FlagValue(F.NoInline),
523 FlagValue(F.AlwaysInline),
524 FlagValue(F.NoUnwind),
525 FlagValue(F.MayThrow),
526 FlagValue(F.HasUnknownCall),
527 FlagValue(F.MustBeUnreachable),
528 0};
529
530 return FlagRep;
531}
532
533// Get string representation of function instruction count and flags.
534static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
535 auto *FS = dyn_cast_or_null<FunctionSummary>(Val: GVS);
536 if (!FS)
537 return "";
538
539 return std::string("inst: ") + std::to_string(val: FS->instCount()) +
540 ", ffl: " + fflagsToString(F: FS->fflags());
541}
542
543static std::string getNodeVisualName(GlobalValue::GUID Id) {
544 return std::string("@") + std::to_string(val: Id);
545}
546
547static std::string getNodeVisualName(const ValueInfo &VI) {
548 return VI.name().empty() ? getNodeVisualName(Id: VI.getGUID()) : VI.name().str();
549}
550
551static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS) {
552 if (isa<AliasSummary>(Val: GVS))
553 return getNodeVisualName(VI);
554
555 std::string Attrs = getSummaryAttributes(GVS);
556 std::string Label =
557 getNodeVisualName(VI) + "|" + linkageToString(LT: GVS->linkage());
558 if (!Attrs.empty())
559 Label += std::string(" (") + Attrs + ")";
560 Label += "}";
561
562 return Label;
563}
564
565// Write definition of external node, which doesn't have any
566// specific module associated with it. Typically this is function
567// or variable defined in native object or library.
568static void defineExternalNode(raw_ostream &OS, const char *Pfx,
569 const ValueInfo &VI, GlobalValue::GUID Id) {
570 auto StrId = std::to_string(val: Id);
571 OS << " " << StrId << " [label=\"";
572
573 if (VI) {
574 OS << getNodeVisualName(VI);
575 } else {
576 OS << getNodeVisualName(Id);
577 }
578 OS << "\"]; // defined externally\n";
579}
580
581static bool hasReadOnlyFlag(const GlobalValueSummary *S) {
582 if (auto *GVS = dyn_cast<GlobalVarSummary>(Val: S))
583 return GVS->maybeReadOnly();
584 return false;
585}
586
587static bool hasWriteOnlyFlag(const GlobalValueSummary *S) {
588 if (auto *GVS = dyn_cast<GlobalVarSummary>(Val: S))
589 return GVS->maybeWriteOnly();
590 return false;
591}
592
593static bool hasConstantFlag(const GlobalValueSummary *S) {
594 if (auto *GVS = dyn_cast<GlobalVarSummary>(Val: S))
595 return GVS->isConstant();
596 return false;
597}
598
599void ModuleSummaryIndex::exportToDot(
600 raw_ostream &OS,
601 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const {
602 std::vector<Edge> CrossModuleEdges;
603 DenseMap<GlobalValue::GUID, std::vector<uint64_t>> NodeMap;
604 using GVSOrderedMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>;
605 std::map<StringRef, GVSOrderedMapTy> ModuleToDefinedGVS;
606 collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries&: ModuleToDefinedGVS);
607
608 // Assign an id to each module path for use in graph labels. Since the
609 // StringMap iteration order isn't guaranteed, order by path string before
610 // assigning ids.
611 std::vector<StringRef> ModulePaths;
612 for (auto &[ModPath, _] : modulePaths())
613 ModulePaths.push_back(x: ModPath);
614 llvm::sort(C&: ModulePaths);
615 DenseMap<StringRef, uint64_t> ModuleIdMap;
616 for (auto &ModPath : ModulePaths)
617 ModuleIdMap.try_emplace(Key: ModPath, Args: ModuleIdMap.size());
618
619 // Get node identifier in form MXXX_<GUID>. The MXXX prefix is required,
620 // because we may have multiple linkonce functions summaries.
621 auto NodeId = [](uint64_t ModId, GlobalValue::GUID Id) {
622 return ModId == (uint64_t)-1 ? std::to_string(val: Id)
623 : std::string("M") + std::to_string(val: ModId) +
624 "_" + std::to_string(val: Id);
625 };
626
627 auto DrawEdge = [&](const char *Pfx, uint64_t SrcMod, GlobalValue::GUID SrcId,
628 uint64_t DstMod, GlobalValue::GUID DstId,
629 int TypeOrHotness) {
630 // 0 - alias
631 // 1 - reference
632 // 2 - constant reference
633 // 3 - writeonly reference
634 // Other value: (hotness - 4).
635 TypeOrHotness += 4;
636 static const char *EdgeAttrs[] = {
637 " [style=dotted]; // alias",
638 " [style=dashed]; // ref",
639 " [style=dashed,color=forestgreen]; // const-ref",
640 " [style=dashed,color=violetred]; // writeOnly-ref",
641 " // call (hotness : Unknown)",
642 " [color=blue]; // call (hotness : Cold)",
643 " // call (hotness : None)",
644 " [color=brown]; // call (hotness : Hot)",
645 " [style=bold,color=red]; // call (hotness : Critical)"};
646
647 assert(static_cast<size_t>(TypeOrHotness) < std::size(EdgeAttrs));
648 OS << Pfx << NodeId(SrcMod, SrcId) << " -> " << NodeId(DstMod, DstId)
649 << EdgeAttrs[TypeOrHotness] << "\n";
650 };
651
652 OS << "digraph Summary {\n";
653 for (auto &ModIt : ModuleToDefinedGVS) {
654 // Will be empty for a just built per-module index, which doesn't setup a
655 // module paths table. In that case use 0 as the module id.
656 assert(ModuleIdMap.count(ModIt.first) || ModuleIdMap.empty());
657 auto ModId = ModuleIdMap.empty() ? 0 : ModuleIdMap[ModIt.first];
658 OS << " // Module: " << ModIt.first << "\n";
659 OS << " subgraph cluster_" << std::to_string(val: ModId) << " {\n";
660 OS << " style = filled;\n";
661 OS << " color = lightgrey;\n";
662 OS << " label = \"" << sys::path::filename(path: ModIt.first) << "\";\n";
663 OS << " node [style=filled,fillcolor=lightblue];\n";
664
665 auto &GVSMap = ModIt.second;
666 auto Draw = [&](GlobalValue::GUID IdFrom, GlobalValue::GUID IdTo, int Hotness) {
667 if (!GVSMap.count(x: IdTo)) {
668 CrossModuleEdges.push_back(x: {.SrcMod: ModId, .Hotness: Hotness, .Src: IdFrom, .Dst: IdTo});
669 return;
670 }
671 DrawEdge(" ", ModId, IdFrom, ModId, IdTo, Hotness);
672 };
673
674 for (auto &SummaryIt : GVSMap) {
675 NodeMap[SummaryIt.first].push_back(x: ModId);
676 auto Flags = SummaryIt.second->flags();
677 Attributes A;
678 if (isa<FunctionSummary>(Val: SummaryIt.second)) {
679 A.add(Name: "shape", Value: "record", Comment: "function");
680 } else if (isa<AliasSummary>(Val: SummaryIt.second)) {
681 A.add(Name: "style", Value: "dotted,filled", Comment: "alias");
682 A.add(Name: "shape", Value: "box");
683 } else {
684 A.add(Name: "shape", Value: "Mrecord", Comment: "variable");
685 if (Flags.Live && hasReadOnlyFlag(S: SummaryIt.second))
686 A.addComment(Comment: "immutable");
687 if (Flags.Live && hasWriteOnlyFlag(S: SummaryIt.second))
688 A.addComment(Comment: "writeOnly");
689 if (Flags.Live && hasConstantFlag(S: SummaryIt.second))
690 A.addComment(Comment: "constant");
691 }
692 if (Flags.Visibility)
693 A.addComment(Comment: "visibility");
694 if (Flags.DSOLocal)
695 A.addComment(Comment: "dsoLocal");
696 if (Flags.CanAutoHide)
697 A.addComment(Comment: "canAutoHide");
698 switch (SummaryIt.second->importType()) {
699 case GlobalValueSummary::ImportKind::Definition:
700 A.addComment(Comment: "definition");
701 break;
702 case GlobalValueSummary::ImportKind::Declaration:
703 A.addComment(Comment: "declaration");
704 break;
705 }
706 if (Flags.NoRenameOnPromotion)
707 A.addComment(Comment: "noRenameOnPromotion");
708 if (GUIDPreservedSymbols.count(V: SummaryIt.first))
709 A.addComment(Comment: "preserved");
710
711 auto VI = getValueInfo(GUID: SummaryIt.first);
712 A.add(Name: "label", Value: getNodeLabel(VI, GVS: SummaryIt.second));
713 if (!Flags.Live)
714 A.add(Name: "fillcolor", Value: "red", Comment: "dead");
715 else if (Flags.NotEligibleToImport)
716 A.add(Name: "fillcolor", Value: "yellow", Comment: "not eligible to import");
717
718 OS << " " << NodeId(ModId, SummaryIt.first) << " " << A.getAsString()
719 << "\n";
720 }
721 OS << " // Edges:\n";
722
723 for (auto &SummaryIt : GVSMap) {
724 auto *GVS = SummaryIt.second;
725 for (auto &R : GVS->refs())
726 Draw(SummaryIt.first, R.getGUID(),
727 R.isWriteOnly() ? -1 : (R.isReadOnly() ? -2 : -3));
728
729 if (auto *AS = dyn_cast_or_null<AliasSummary>(Val: SummaryIt.second)) {
730 Draw(SummaryIt.first, AS->getAliaseeGUID(), -4);
731 continue;
732 }
733
734 if (auto *FS = dyn_cast_or_null<FunctionSummary>(Val: SummaryIt.second))
735 for (auto &CGEdge : FS->calls())
736 Draw(SummaryIt.first, CGEdge.first.getGUID(),
737 static_cast<int>(CGEdge.second.Hotness));
738 }
739 OS << " }\n";
740 }
741
742 OS << " // Cross-module edges:\n";
743 for (auto &E : CrossModuleEdges) {
744 auto &ModList = NodeMap[E.Dst];
745 if (ModList.empty()) {
746 defineExternalNode(OS, Pfx: " ", VI: getValueInfo(GUID: E.Dst), Id: E.Dst);
747 // Add fake module to the list to draw an edge to an external node
748 // in the loop below.
749 ModList.push_back(x: -1);
750 }
751 for (auto DstMod : ModList)
752 // The edge representing call or ref is drawn to every module where target
753 // symbol is defined. When target is a linkonce symbol there can be
754 // multiple edges representing a single call or ref, both intra-module and
755 // cross-module. As we've already drawn all intra-module edges before we
756 // skip it here.
757 if (DstMod != E.SrcMod)
758 DrawEdge(" ", E.SrcMod, E.Src, DstMod, E.Dst, E.Hotness);
759 }
760
761 OS << "}";
762}
763