ModuleSummaryIndex.cpp 24 KB

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