LLVM 23.0.0git
ModuleSummaryIndex.cpp
Go to the documentation of this file.
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
16#include "llvm/ADT/Statistic.h"
18#include "llvm/Support/Path.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 {
31 AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true),
33 cl::desc("Always rename promoted locals."));
34} // namespace llvm
35
36static cl::opt<bool> PropagateAttrs("propagate-attrs", cl::init(true),
38 cl::desc("Propagate attributes in index"));
39
41 "import-constants-with-refs", cl::init(true), cl::Hidden,
42 cl::desc("Import constant global variables with references"));
43
47
49 bool HasProtected = false;
50 for (const auto &S : make_pointee_range(getSummaryList())) {
51 if (S.getVisibility() == GlobalValue::HiddenVisibility)
53 if (S.getVisibility() == GlobalValue::ProtectedVisibility)
54 HasProtected = true;
55 }
56 return HasProtected ? GlobalValue::ProtectedVisibility
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() &&
68 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
69 return Summary->isDSOLocal();
70 });
71}
72
74 // Can only auto hide if all copies are eligible to auto hide.
75 return getSummaryList().size() &&
77 [](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
97 uint64_t Flags = 0;
98 // Flags & 0x4 is reserved. DO NOT REUSE.
100 Flags |= 0x1;
102 Flags |= 0x2;
103 if (enableSplitLTOUnit())
104 Flags |= 0x8;
106 Flags |= 0x10;
108 Flags |= 0x20;
110 Flags |= 0x40;
112 Flags |= 0x80;
114 Flags |= 0x100;
115 if (hasUnifiedLTO())
116 Flags |= 0x200;
118 Flags |= 0x400;
119 return Flags;
120}
121
123 assert(Flags <= 0x7ff && "Unexpected bits in flag");
124 // 1 bit: WithGlobalValueDeadStripping flag.
125 // Set on combined index only.
126 if (Flags & 0x1)
128 // 1 bit: SkipModuleByDistributedBackend flag.
129 // Set on combined index only.
130 if (Flags & 0x2)
132 // Flags & 0x4 is reserved. DO NOT REUSE.
133 // 1 bit: DisableSplitLTOUnit flag.
134 // Set on per module indexes. It is up to the client to validate
135 // the consistency of this flag across modules being linked.
136 if (Flags & 0x8)
138 // 1 bit: PartiallySplitLTOUnits flag.
139 // Set on combined index only.
140 if (Flags & 0x10)
142 // 1 bit: WithAttributePropagation flag.
143 // Set on combined index only.
144 if (Flags & 0x20)
146 // 1 bit: WithDSOLocalPropagation flag.
147 // Set on combined index only.
148 if (Flags & 0x40)
150 // 1 bit: WithWholeProgramVisibility flag.
151 // Set on combined index only.
152 if (Flags & 0x80)
154 // 1 bit: WithSupportsHotColdNew flag.
155 // Set on combined index only.
156 if (Flags & 0x100)
158 // 1 bit: WithUnifiedLTO flag.
159 // Set on combined index only.
160 if (Flags & 0x200)
162 // 1 bit: WithInternalizeAndPromote flag.
163 // Set on combined index only.
164 if (Flags & 0x400)
166}
167
168// Collect for the given module the list of function it defines
169// (GUID -> Summary).
171 StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const {
172 for (auto &GlobalList : *this) {
173 auto GUID = GlobalList.first;
174 for (auto &GlobSummary : GlobalList.second.getSummaryList()) {
175 auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobSummary.get());
176 if (!Summary)
177 // Ignore global variable, focus on functions
178 continue;
179 // Ignore summaries from other modules.
180 if (Summary->modulePath() != ModulePath)
181 continue;
182 GVSummaryMap[GUID] = Summary;
183 }
184 }
185}
186
189 bool PerModuleIndex) const {
190 auto VI = getValueInfo(ValueGUID);
191 assert(VI && "GlobalValue not found in index");
192 assert((!PerModuleIndex || VI.getSummaryList().size() == 1) &&
193 "Expected a single entry per global value in per-module index");
194 auto &Summary = VI.getSummaryList()[0];
195 return Summary.get();
196}
197
199 auto VI = getValueInfo(GUID);
200 if (!VI)
201 return true;
202 const auto &SummaryList = VI.getSummaryList();
203 if (SummaryList.empty())
204 return true;
205 for (auto &I : SummaryList)
206 if (isGlobalValueLive(I.get()))
207 return true;
208 return false;
209}
210
211static void
213 DenseSet<ValueInfo> &MarkedNonReadWriteOnly) {
214 // If reference is not readonly or writeonly then referenced summary is not
215 // read/writeonly either. Note that:
216 // - All references from GlobalVarSummary are conservatively considered as
217 // not readonly or writeonly. Tracking them properly requires more complex
218 // analysis then we have now.
219 //
220 // - AliasSummary objects have no refs at all so this function is a no-op
221 // for them.
222 for (auto &VI : S->refs()) {
223 assert(VI.getAccessSpecifier() == 0 || isa<FunctionSummary>(S));
224 if (!VI.getAccessSpecifier()) {
225 if (!MarkedNonReadWriteOnly.insert(VI).second)
226 continue;
227 } else if (MarkedNonReadWriteOnly.contains(VI))
228 continue;
229 bool HasNonGVar = false;
230 for (auto &Ref : VI.getSummaryList()) {
231 // If references to alias is not read/writeonly then aliasee
232 // is not read/writeonly
233 if (auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject())) {
234 if (!VI.isReadOnly())
235 GVS->setReadOnly(false);
236 if (!VI.isWriteOnly())
237 GVS->setWriteOnly(false);
238 } else {
239 // Note that this needs special processing.
240 HasNonGVar = true;
241 break;
242 }
243 }
244 // In the case where we have a reference to a VI that is a function not a
245 // variable, conservatively mark all summaries as non-read or write only.
246 // In most cases that would have happened in the above loop. However,
247 // this will make a difference in a few rare cases where there are same
248 // named locals in modules without enough distinguishing path, which end up
249 // with the same GUID. If these are a mix of variables and functions we want
250 // to handle the variables conservatively.
251 if (HasNonGVar) {
252 for (auto &Ref : VI.getSummaryList()) {
253 auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject());
254 if (!GVS)
255 continue;
256 GVS->setReadOnly(false);
257 GVS->setWriteOnly(false);
258 }
259 MarkedNonReadWriteOnly.insert(VI);
260 }
261 }
262}
263
264// Do the access attribute and DSOLocal propagation in combined index.
265// The goal of attribute propagation is internalization of readonly (RO)
266// or writeonly (WO) variables. To determine which variables are RO or WO
267// and which are not we take following steps:
268// - During analysis we speculatively assign readonly and writeonly
269// attribute to all variables which can be internalized. When computing
270// function summary we also assign readonly or writeonly attribute to a
271// reference if function doesn't modify referenced variable (readonly)
272// or doesn't read it (writeonly).
273//
274// - After computing dead symbols in combined index we do the attribute
275// and DSOLocal propagation. During this step we:
276// a. clear RO and WO attributes from variables which are preserved or
277// can't be imported
278// b. clear RO and WO attributes from variables referenced by any global
279// variable initializer
280// c. clear RO attribute from variable referenced by a function when
281// reference is not readonly
282// d. clear WO attribute from variable referenced by a function when
283// reference is not writeonly
284// e. clear RO and WO attributes from variables with the same GUID as
285// a non-variable.
286// f. clear IsDSOLocal flag in every summary if any of them is false.
287//
288// Because of (c, d) we don't internalize variables read by function A
289// and modified by function B.
290//
291// Internalization itself happens in the backend after import is finished
292// See internalizeGVsAfterImport.
294 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
295 if (!PropagateAttrs)
296 return;
297 DenseSet<ValueInfo> MarkedNonReadWriteOnly;
298 for (auto &P : *this) {
299 bool IsDSOLocal = true;
300 for (auto &S : P.second.getSummaryList()) {
301 if (!isGlobalValueLive(S.get())) {
302 // computeDeadSymbolsAndUpdateIndirectCalls should have marked all
303 // copies live. Note that it is possible that there is a GUID collision
304 // between internal symbols with the same name in different files of the
305 // same name but not enough distinguishing path. Because
306 // computeDeadSymbolsAndUpdateIndirectCalls should conservatively mark
307 // all copies live we can assert here that all are dead if any copy is
308 // dead.
310 P.second.getSummaryList(),
311 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
312 return isGlobalValueLive(Summary.get());
313 }));
314 // We don't examine references from dead objects
315 break;
316 }
317
318 // Global variable can't be marked read/writeonly if it is not eligible
319 // to import since we need to ensure that all external references get
320 // a local (imported) copy. It also can't be marked read/writeonly if
321 // it or any alias (since alias points to the same memory) are preserved
322 // or notEligibleToImport, since either of those means there could be
323 // writes (or reads in case of writeonly) that are not visible (because
324 // preserved means it could have external to DSO writes or reads, and
325 // notEligibleToImport means it could have writes or reads via inline
326 // assembly leading it to be in the @llvm.*used).
327 if (auto *GVS = dyn_cast<GlobalVarSummary>(S->getBaseObject()))
328 // Here we intentionally pass S.get() not GVS, because S could be
329 // an alias. We don't analyze references here, because we have to
330 // know exactly if GV is readonly to do so.
331 if (!canImportGlobalVar(S.get(), /* AnalyzeRefs */ false) ||
332 GUIDPreservedSymbols.count(P.first)) {
333 GVS->setReadOnly(false);
334 GVS->setWriteOnly(false);
335 }
336 propagateAttributesToRefs(S.get(), MarkedNonReadWriteOnly);
337
338 // If the flag from any summary is false, the GV is not DSOLocal.
339 IsDSOLocal &= S->isDSOLocal();
340 }
341 if (!IsDSOLocal)
342 // Mark the flag in all summaries false so that we can do quick check
343 // without going through the whole list.
344 for (const std::unique_ptr<GlobalValueSummary> &Summary :
345 P.second.getSummaryList())
346 Summary->setDSOLocal(false);
347 }
351 for (auto &P : *this)
352 if (P.second.getSummaryList().size())
353 if (auto *GVS = dyn_cast<GlobalVarSummary>(
354 P.second.getSummaryList()[0]->getBaseObject()))
355 if (isGlobalValueLive(GVS)) {
356 if (GVS->maybeReadOnly())
357 ReadOnlyLiveGVars++;
358 if (GVS->maybeWriteOnly())
359 WriteOnlyLiveGVars++;
360 }
361}
362
364 bool AnalyzeRefs) const {
365 bool CanImportDecl;
366 return canImportGlobalVar(S, AnalyzeRefs, CanImportDecl);
367}
368
370 bool AnalyzeRefs,
371 bool &CanImportDecl) const {
372 auto HasRefsPreventingImport = [this](const GlobalVarSummary *GVS) {
373 // We don't analyze GV references during attribute propagation, so
374 // GV with non-trivial initializer can be marked either read or
375 // write-only.
376 // Importing definiton of readonly GV with non-trivial initializer
377 // allows us doing some extra optimizations (like converting indirect
378 // calls to direct).
379 // Definition of writeonly GV with non-trivial initializer should also
380 // be imported. Not doing so will result in:
381 // a) GV internalization in source module (because it's writeonly)
382 // b) Importing of GV declaration to destination module as a result
383 // of promotion.
384 // c) Link error (external declaration with internal definition).
385 // However we do not promote objects referenced by writeonly GV
386 // initializer by means of converting it to 'zeroinitializer'
387 return !(ImportConstantsWithRefs && GVS->isConstant()) &&
388 !isReadOnly(GVS) && !isWriteOnly(GVS) && GVS->refs().size();
389 };
390 auto *GVS = cast<GlobalVarSummary>(S->getBaseObject());
391
392 const bool nonInterposable =
394 const bool eligibleToImport = !S->notEligibleToImport();
395
396 // It's correct to import a global variable only when it is not interposable
397 // and eligible to import.
398 CanImportDecl = (nonInterposable && eligibleToImport);
399
400 // Global variable with non-trivial initializer can be imported
401 // if it's readonly. This gives us extra opportunities for constant
402 // folding and converting indirect calls to direct calls. We don't
403 // analyze GV references during attribute propagation, because we
404 // don't know yet if it is readonly or not.
405 return nonInterposable && eligibleToImport &&
406 (!AnalyzeRefs || !HasRefsPreventingImport(GVS));
407}
408
409// TODO: write a graphviz dumper for SCCs (see ModuleSummaryIndex::exportToDot)
410// then delete this function and update its tests
415 !I.isAtEnd(); ++I) {
416 O << "SCC (" << utostr(I->size()) << " node" << (I->size() == 1 ? "" : "s")
417 << ") {\n";
418 for (const ValueInfo &V : *I) {
419 FunctionSummary *F = nullptr;
420 if (V.getSummaryList().size())
421 F = cast<FunctionSummary>(V.getSummaryList().front().get());
422 O << " " << (F == nullptr ? "External" : "") << " " << utostr(V.getGUID())
423 << (I.hasCycle() ? " (has cycle)" : "") << "\n";
424 }
425 O << "}\n";
426 }
427}
428
429namespace {
430struct Attributes {
431 void add(const Twine &Name, const Twine &Value,
432 const Twine &Comment = Twine());
433 void addComment(const Twine &Comment);
434 std::string getAsString() const;
435
436 std::vector<std::string> Attrs;
437 std::string Comments;
438};
439
440struct Edge {
441 uint64_t SrcMod;
442 int Hotness;
445};
446} // namespace
447
448void Attributes::add(const Twine &Name, const Twine &Value,
449 const Twine &Comment) {
450 std::string A = Name.str();
451 A += "=\"";
452 A += Value.str();
453 A += "\"";
454 Attrs.push_back(A);
455 addComment(Comment);
456}
457
458void Attributes::addComment(const Twine &Comment) {
459 if (!Comment.isTriviallyEmpty()) {
460 if (Comments.empty())
461 Comments = " // ";
462 else
463 Comments += ", ";
464 Comments += Comment.str();
465 }
466}
467
468std::string Attributes::getAsString() const {
469 if (Attrs.empty())
470 return "";
471
472 std::string Ret = "[";
473 for (auto &A : Attrs)
474 Ret += A + ",";
475 Ret.pop_back();
476 Ret += "];";
477 Ret += Comments;
478 return Ret;
479}
480
482 switch (LT) {
484 return "extern";
486 return "av_ext";
488 return "linkonce";
490 return "linkonce_odr";
492 return "weak";
494 return "weak_odr";
496 return "appending";
498 return "internal";
500 return "private";
502 return "extern_weak";
504 return "common";
505 }
506
507 return "<unknown>";
508}
509
511 auto FlagValue = [](unsigned V) { return V ? '1' : '0'; };
512 char FlagRep[] = {FlagValue(F.ReadNone),
513 FlagValue(F.ReadOnly),
514 FlagValue(F.NoRecurse),
515 FlagValue(F.ReturnDoesNotAlias),
516 FlagValue(F.NoInline),
517 FlagValue(F.AlwaysInline),
518 FlagValue(F.NoUnwind),
519 FlagValue(F.MayThrow),
520 FlagValue(F.HasUnknownCall),
521 FlagValue(F.MustBeUnreachable),
522 0};
523
524 return FlagRep;
525}
526
527// Get string representation of function instruction count and flags.
528static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
529 auto *FS = dyn_cast_or_null<FunctionSummary>(GVS);
530 if (!FS)
531 return "";
532
533 return std::string("inst: ") + std::to_string(FS->instCount()) +
534 ", ffl: " + fflagsToString(FS->fflags());
535}
536
537static std::string getNodeVisualName(GlobalValue::GUID Id) {
538 return std::string("@") + std::to_string(Id);
539}
540
541static std::string getNodeVisualName(const ValueInfo &VI) {
542 return VI.name().empty() ? getNodeVisualName(VI.getGUID()) : VI.name().str();
543}
544
545static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS) {
546 if (isa<AliasSummary>(GVS))
547 return getNodeVisualName(VI);
548
549 std::string Attrs = getSummaryAttributes(GVS);
550 std::string Label =
551 getNodeVisualName(VI) + "|" + linkageToString(GVS->linkage());
552 if (!Attrs.empty())
553 Label += std::string(" (") + Attrs + ")";
554 Label += "}";
555
556 return Label;
557}
558
559// Write definition of external node, which doesn't have any
560// specific module associated with it. Typically this is function
561// or variable defined in native object or library.
562static void defineExternalNode(raw_ostream &OS, const char *Pfx,
563 const ValueInfo &VI, GlobalValue::GUID Id) {
564 auto StrId = std::to_string(Id);
565 OS << " " << StrId << " [label=\"";
566
567 if (VI) {
568 OS << getNodeVisualName(VI);
569 } else {
570 OS << getNodeVisualName(Id);
571 }
572 OS << "\"]; // defined externally\n";
573}
574
575static bool hasReadOnlyFlag(const GlobalValueSummary *S) {
576 if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
577 return GVS->maybeReadOnly();
578 return false;
579}
580
582 if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
583 return GVS->maybeWriteOnly();
584 return false;
585}
586
587static bool hasConstantFlag(const GlobalValueSummary *S) {
588 if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
589 return GVS->isConstant();
590 return false;
591}
592
594 raw_ostream &OS,
595 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const {
596 std::vector<Edge> CrossModuleEdges;
598 using GVSOrderedMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>;
599 std::map<StringRef, GVSOrderedMapTy> ModuleToDefinedGVS;
600 collectDefinedGVSummariesPerModule(ModuleToDefinedGVS);
601
602 // Assign an id to each module path for use in graph labels. Since the
603 // StringMap iteration order isn't guaranteed, order by path string before
604 // assigning ids.
605 std::vector<StringRef> ModulePaths;
606 for (auto &[ModPath, _] : modulePaths())
607 ModulePaths.push_back(ModPath);
608 llvm::sort(ModulePaths);
610 for (auto &ModPath : ModulePaths)
611 ModuleIdMap.try_emplace(ModPath, ModuleIdMap.size());
612
613 // Get node identifier in form MXXX_<GUID>. The MXXX prefix is required,
614 // because we may have multiple linkonce functions summaries.
615 auto NodeId = [](uint64_t ModId, GlobalValue::GUID Id) {
616 return ModId == (uint64_t)-1 ? std::to_string(Id)
617 : std::string("M") + std::to_string(ModId) +
618 "_" + std::to_string(Id);
619 };
620
621 auto DrawEdge = [&](const char *Pfx, uint64_t SrcMod, GlobalValue::GUID SrcId,
622 uint64_t DstMod, GlobalValue::GUID DstId,
623 int TypeOrHotness) {
624 // 0 - alias
625 // 1 - reference
626 // 2 - constant reference
627 // 3 - writeonly reference
628 // Other value: (hotness - 4).
629 TypeOrHotness += 4;
630 static const char *EdgeAttrs[] = {
631 " [style=dotted]; // alias",
632 " [style=dashed]; // ref",
633 " [style=dashed,color=forestgreen]; // const-ref",
634 " [style=dashed,color=violetred]; // writeOnly-ref",
635 " // call (hotness : Unknown)",
636 " [color=blue]; // call (hotness : Cold)",
637 " // call (hotness : None)",
638 " [color=brown]; // call (hotness : Hot)",
639 " [style=bold,color=red]; // call (hotness : Critical)"};
640
641 assert(static_cast<size_t>(TypeOrHotness) < std::size(EdgeAttrs));
642 OS << Pfx << NodeId(SrcMod, SrcId) << " -> " << NodeId(DstMod, DstId)
643 << EdgeAttrs[TypeOrHotness] << "\n";
644 };
645
646 OS << "digraph Summary {\n";
647 for (auto &ModIt : ModuleToDefinedGVS) {
648 // Will be empty for a just built per-module index, which doesn't setup a
649 // module paths table. In that case use 0 as the module id.
650 assert(ModuleIdMap.count(ModIt.first) || ModuleIdMap.empty());
651 auto ModId = ModuleIdMap.empty() ? 0 : ModuleIdMap[ModIt.first];
652 OS << " // Module: " << ModIt.first << "\n";
653 OS << " subgraph cluster_" << std::to_string(ModId) << " {\n";
654 OS << " style = filled;\n";
655 OS << " color = lightgrey;\n";
656 OS << " label = \"" << sys::path::filename(ModIt.first) << "\";\n";
657 OS << " node [style=filled,fillcolor=lightblue];\n";
658
659 auto &GVSMap = ModIt.second;
660 auto Draw = [&](GlobalValue::GUID IdFrom, GlobalValue::GUID IdTo, int Hotness) {
661 if (!GVSMap.count(IdTo)) {
662 CrossModuleEdges.push_back({ModId, Hotness, IdFrom, IdTo});
663 return;
664 }
665 DrawEdge(" ", ModId, IdFrom, ModId, IdTo, Hotness);
666 };
667
668 for (auto &SummaryIt : GVSMap) {
669 NodeMap[SummaryIt.first].push_back(ModId);
670 auto Flags = SummaryIt.second->flags();
671 Attributes A;
672 if (isa<FunctionSummary>(SummaryIt.second)) {
673 A.add("shape", "record", "function");
674 } else if (isa<AliasSummary>(SummaryIt.second)) {
675 A.add("style", "dotted,filled", "alias");
676 A.add("shape", "box");
677 } else {
678 A.add("shape", "Mrecord", "variable");
679 if (Flags.Live && hasReadOnlyFlag(SummaryIt.second))
680 A.addComment("immutable");
681 if (Flags.Live && hasWriteOnlyFlag(SummaryIt.second))
682 A.addComment("writeOnly");
683 if (Flags.Live && hasConstantFlag(SummaryIt.second))
684 A.addComment("constant");
685 }
686 if (Flags.Visibility)
687 A.addComment("visibility");
688 if (Flags.DSOLocal)
689 A.addComment("dsoLocal");
690 if (Flags.CanAutoHide)
691 A.addComment("canAutoHide");
692 if (Flags.ImportType == GlobalValueSummary::ImportKind::Definition)
693 A.addComment("definition");
694 else if (Flags.ImportType == GlobalValueSummary::ImportKind::Declaration)
695 A.addComment("declaration");
696 if (Flags.NoRenameOnPromotion)
697 A.addComment("noRenameOnPromotion");
698 if (GUIDPreservedSymbols.count(SummaryIt.first))
699 A.addComment("preserved");
700
701 auto VI = getValueInfo(SummaryIt.first);
702 A.add("label", getNodeLabel(VI, SummaryIt.second));
703 if (!Flags.Live)
704 A.add("fillcolor", "red", "dead");
705 else if (Flags.NotEligibleToImport)
706 A.add("fillcolor", "yellow", "not eligible to import");
707
708 OS << " " << NodeId(ModId, SummaryIt.first) << " " << A.getAsString()
709 << "\n";
710 }
711 OS << " // Edges:\n";
712
713 for (auto &SummaryIt : GVSMap) {
714 auto *GVS = SummaryIt.second;
715 for (auto &R : GVS->refs())
716 Draw(SummaryIt.first, R.getGUID(),
717 R.isWriteOnly() ? -1 : (R.isReadOnly() ? -2 : -3));
718
719 if (auto *AS = dyn_cast_or_null<AliasSummary>(SummaryIt.second)) {
720 Draw(SummaryIt.first, AS->getAliaseeGUID(), -4);
721 continue;
722 }
723
724 if (auto *FS = dyn_cast_or_null<FunctionSummary>(SummaryIt.second))
725 for (auto &CGEdge : FS->calls())
726 Draw(SummaryIt.first, CGEdge.first.getGUID(),
727 static_cast<int>(CGEdge.second.Hotness));
728 }
729 OS << " }\n";
730 }
731
732 OS << " // Cross-module edges:\n";
733 for (auto &E : CrossModuleEdges) {
734 auto &ModList = NodeMap[E.Dst];
735 if (ModList.empty()) {
736 defineExternalNode(OS, " ", getValueInfo(E.Dst), E.Dst);
737 // Add fake module to the list to draw an edge to an external node
738 // in the loop below.
739 ModList.push_back(-1);
740 }
741 for (auto DstMod : ModList)
742 // The edge representing call or ref is drawn to every module where target
743 // symbol is defined. When target is a linkonce symbol there can be
744 // multiple edges representing a single call or ref, both intra-module and
745 // cross-module. As we've already drawn all intra-module edges before we
746 // skip it here.
747 if (DstMod != E.SrcMod)
748 DrawEdge(" ", E.SrcMod, E.Src, DstMod, E.Dst, E.Hotness);
749 }
750
751 OS << "}";
752}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
#define _
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static std::string getNodeVisualName(GlobalValue::GUID Id)
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
static std::string getSummaryAttributes(GlobalValueSummary *GVS)
static cl::opt< bool > ImportConstantsWithRefs("import-constants-with-refs", cl::init(true), cl::Hidden, cl::desc("Import constant global variables with references"))
static std::string fflagsToString(FunctionSummary::FFlags F)
static bool hasWriteOnlyFlag(const GlobalValueSummary *S)
static void propagateAttributesToRefs(GlobalValueSummary *S, DenseSet< ValueInfo > &MarkedNonReadWriteOnly)
static std::string linkageToString(GlobalValue::LinkageTypes LT)
static void defineExternalNode(raw_ostream &OS, const char *Pfx, const ValueInfo &VI, GlobalValue::GUID Id)
static cl::opt< bool > PropagateAttrs("propagate-attrs", cl::init(true), cl::Hidden, cl::desc("Propagate attributes in index"))
static bool hasReadOnlyFlag(const GlobalValueSummary *S)
static bool hasConstantFlag(const GlobalValueSummary *S)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
#define P(N)
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:256
unsigned size() const
Definition DenseMap.h:110
bool empty() const
Definition DenseMap.h:109
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:174
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Function summary information to aid decisions and implementation of importing.
static LLVM_ABI FunctionSummary ExternalNode
A dummy node to reference external functions that aren't in the index.
static FunctionSummary makeDummyFunctionSummary(SmallVectorImpl< FunctionSummary::EdgeTy > &&Edges)
Create an empty FunctionSummary (with specified call edges).
LLVM_ABI std::pair< unsigned, unsigned > specialRefCounts() const
Function and variable summary information to aid decisions and implementation of importing.
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
GlobalValue::LinkageTypes linkage() const
Return linkage type recorded for this global value.
bool notEligibleToImport() const
Return true if this global value can't be imported.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Global variable summary information to aid decisions and implementation of importing.
LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const
bool isReadOnly(const GlobalVarSummary *GVS) const
LLVM_ABI void setFlags(uint64_t Flags)
bool isWriteOnly(const GlobalVarSummary *GVS) const
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
LLVM_ABI void collectDefinedFunctionsForModule(StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const
Collect for the given module the list of functions it defines (GUID -> Summary).
LLVM_ABI void dumpSCCs(raw_ostream &OS)
Print out strongly connected components for debugging.
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
LLVM_ABI void propagateAttributes(const DenseSet< GlobalValue::GUID > &PreservedSymbols)
Do the access attribute and DSOLocal propagation in combined index.
const StringMap< ModuleHash > & modulePaths() const
Table of modules, containing module hash and id.
void collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
LLVM_ABI void exportToDot(raw_ostream &OS, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols) const
Export summary to dot file for GraphViz.
bool skipModuleByDistributedBackend() const
LLVM_ABI uint64_t getFlags() const
GlobalValueSummary * getGlobalValueSummary(const GlobalValue &GV, bool PerModuleIndex=true) const
Returns the first GlobalValueSummary for GV, asserting that there is only one if PerModuleIndex.
LLVM_ABI bool canImportGlobalVar(const GlobalValueSummary *S, bool AnalyzeRefs) const
Checks if we can import global variable from another module.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Definition SCCIterator.h:49
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
initializer< Ty > init(const Ty &Val)
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:584
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
std::string utostr(uint64_t X, bool isNeg=false)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
iterator_range< pointee_iterator< WrappedIteratorT > > make_pointee_range(RangeT &&Range)
Definition iterator.h:341
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
Definition LTO.cpp:113
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Flags specific to function summaries.
Struct that holds a reference to a particular GUID in a global value summary.
LLVM_ABI GlobalValue::VisibilityTypes getELFVisibility() const
Returns the most constraining visibility among summaries.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
LLVM_ABI bool canAutoHide() const
Checks if all copies are eligible for auto-hiding (have flag set).
LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation=false) const
Checks if all summaries are DSO local (have the flag set).