xref: /freebsd/contrib/llvm-project/llvm/lib/IR/ModuleSummaryIndex.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
10b57cec5SDimitry Andric //===-- ModuleSummaryIndex.cpp - Module Summary Index ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the module index and summary classes for the
100b57cec5SDimitry Andric // IR library.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SCCIterator.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
170b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
18*480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
190b57cec5SDimitry Andric #include "llvm/Support/Path.h"
200b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
210b57cec5SDimitry Andric using namespace llvm;
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric #define DEBUG_TYPE "module-summary-index"
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric STATISTIC(ReadOnlyLiveGVars,
260b57cec5SDimitry Andric           "Number of live global variables marked read only");
270b57cec5SDimitry Andric STATISTIC(WriteOnlyLiveGVars,
280b57cec5SDimitry Andric           "Number of live global variables marked write only");
290b57cec5SDimitry Andric 
30*480093f4SDimitry Andric static cl::opt<bool> PropagateAttrs("propagate-attrs", cl::init(true),
31*480093f4SDimitry Andric                                     cl::Hidden,
32*480093f4SDimitry Andric                                     cl::desc("Propagate attributes in index"));
33*480093f4SDimitry Andric 
340b57cec5SDimitry Andric FunctionSummary FunctionSummary::ExternalNode =
350b57cec5SDimitry Andric     FunctionSummary::makeDummyFunctionSummary({});
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric bool ValueInfo::isDSOLocal() const {
380b57cec5SDimitry Andric   // Need to check all summaries are local in case of hash collisions.
390b57cec5SDimitry Andric   return getSummaryList().size() &&
400b57cec5SDimitry Andric          llvm::all_of(getSummaryList(),
410b57cec5SDimitry Andric                       [](const std::unique_ptr<GlobalValueSummary> &Summary) {
420b57cec5SDimitry Andric                         return Summary->isDSOLocal();
430b57cec5SDimitry Andric                       });
440b57cec5SDimitry Andric }
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric bool ValueInfo::canAutoHide() const {
470b57cec5SDimitry Andric   // Can only auto hide if all copies are eligible to auto hide.
480b57cec5SDimitry Andric   return getSummaryList().size() &&
490b57cec5SDimitry Andric          llvm::all_of(getSummaryList(),
500b57cec5SDimitry Andric                       [](const std::unique_ptr<GlobalValueSummary> &Summary) {
510b57cec5SDimitry Andric                         return Summary->canAutoHide();
520b57cec5SDimitry Andric                       });
530b57cec5SDimitry Andric }
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric // Gets the number of readonly and writeonly refs in RefEdgeList
560b57cec5SDimitry Andric std::pair<unsigned, unsigned> FunctionSummary::specialRefCounts() const {
570b57cec5SDimitry Andric   // Here we take advantage of having all readonly and writeonly references
580b57cec5SDimitry Andric   // located in the end of the RefEdgeList.
590b57cec5SDimitry Andric   auto Refs = refs();
600b57cec5SDimitry Andric   unsigned RORefCnt = 0, WORefCnt = 0;
610b57cec5SDimitry Andric   int I;
620b57cec5SDimitry Andric   for (I = Refs.size() - 1; I >= 0 && Refs[I].isWriteOnly(); --I)
630b57cec5SDimitry Andric     WORefCnt++;
640b57cec5SDimitry Andric   for (; I >= 0 && Refs[I].isReadOnly(); --I)
650b57cec5SDimitry Andric     RORefCnt++;
660b57cec5SDimitry Andric   return {RORefCnt, WORefCnt};
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
69*480093f4SDimitry Andric constexpr uint64_t ModuleSummaryIndex::BitcodeSummaryVersion;
70*480093f4SDimitry Andric 
710b57cec5SDimitry Andric // Collect for the given module the list of function it defines
720b57cec5SDimitry Andric // (GUID -> Summary).
730b57cec5SDimitry Andric void ModuleSummaryIndex::collectDefinedFunctionsForModule(
740b57cec5SDimitry Andric     StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const {
750b57cec5SDimitry Andric   for (auto &GlobalList : *this) {
760b57cec5SDimitry Andric     auto GUID = GlobalList.first;
770b57cec5SDimitry Andric     for (auto &GlobSummary : GlobalList.second.SummaryList) {
780b57cec5SDimitry Andric       auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobSummary.get());
790b57cec5SDimitry Andric       if (!Summary)
800b57cec5SDimitry Andric         // Ignore global variable, focus on functions
810b57cec5SDimitry Andric         continue;
820b57cec5SDimitry Andric       // Ignore summaries from other modules.
830b57cec5SDimitry Andric       if (Summary->modulePath() != ModulePath)
840b57cec5SDimitry Andric         continue;
850b57cec5SDimitry Andric       GVSummaryMap[GUID] = Summary;
860b57cec5SDimitry Andric     }
870b57cec5SDimitry Andric   }
880b57cec5SDimitry Andric }
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric GlobalValueSummary *
910b57cec5SDimitry Andric ModuleSummaryIndex::getGlobalValueSummary(uint64_t ValueGUID,
920b57cec5SDimitry Andric                                           bool PerModuleIndex) const {
930b57cec5SDimitry Andric   auto VI = getValueInfo(ValueGUID);
940b57cec5SDimitry Andric   assert(VI && "GlobalValue not found in index");
950b57cec5SDimitry Andric   assert((!PerModuleIndex || VI.getSummaryList().size() == 1) &&
960b57cec5SDimitry Andric          "Expected a single entry per global value in per-module index");
970b57cec5SDimitry Andric   auto &Summary = VI.getSummaryList()[0];
980b57cec5SDimitry Andric   return Summary.get();
990b57cec5SDimitry Andric }
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric bool ModuleSummaryIndex::isGUIDLive(GlobalValue::GUID GUID) const {
1020b57cec5SDimitry Andric   auto VI = getValueInfo(GUID);
1030b57cec5SDimitry Andric   if (!VI)
1040b57cec5SDimitry Andric     return true;
1050b57cec5SDimitry Andric   const auto &SummaryList = VI.getSummaryList();
1060b57cec5SDimitry Andric   if (SummaryList.empty())
1070b57cec5SDimitry Andric     return true;
1080b57cec5SDimitry Andric   for (auto &I : SummaryList)
1090b57cec5SDimitry Andric     if (isGlobalValueLive(I.get()))
1100b57cec5SDimitry Andric       return true;
1110b57cec5SDimitry Andric   return false;
1120b57cec5SDimitry Andric }
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric static void propagateAttributesToRefs(GlobalValueSummary *S) {
1150b57cec5SDimitry Andric   // If reference is not readonly or writeonly then referenced summary is not
1160b57cec5SDimitry Andric   // read/writeonly either. Note that:
1170b57cec5SDimitry Andric   // - All references from GlobalVarSummary are conservatively considered as
1180b57cec5SDimitry Andric   //   not readonly or writeonly. Tracking them properly requires more complex
1190b57cec5SDimitry Andric   //   analysis then we have now.
1200b57cec5SDimitry Andric   //
1210b57cec5SDimitry Andric   // - AliasSummary objects have no refs at all so this function is a no-op
1220b57cec5SDimitry Andric   //   for them.
1230b57cec5SDimitry Andric   for (auto &VI : S->refs()) {
1240b57cec5SDimitry Andric     assert(VI.getAccessSpecifier() == 0 || isa<FunctionSummary>(S));
1250b57cec5SDimitry Andric     for (auto &Ref : VI.getSummaryList())
1260b57cec5SDimitry Andric       // If references to alias is not read/writeonly then aliasee
1270b57cec5SDimitry Andric       // is not read/writeonly
1280b57cec5SDimitry Andric       if (auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject())) {
1290b57cec5SDimitry Andric         if (!VI.isReadOnly())
1300b57cec5SDimitry Andric           GVS->setReadOnly(false);
1310b57cec5SDimitry Andric         if (!VI.isWriteOnly())
1320b57cec5SDimitry Andric           GVS->setWriteOnly(false);
1330b57cec5SDimitry Andric       }
1340b57cec5SDimitry Andric   }
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric // Do the access attribute propagation in combined index.
1380b57cec5SDimitry Andric // The goal of attribute propagation is internalization of readonly (RO)
1390b57cec5SDimitry Andric // or writeonly (WO) variables. To determine which variables are RO or WO
1400b57cec5SDimitry Andric // and which are not we take following steps:
1410b57cec5SDimitry Andric // - During analysis we speculatively assign readonly and writeonly
1420b57cec5SDimitry Andric //   attribute to all variables which can be internalized. When computing
1430b57cec5SDimitry Andric //   function summary we also assign readonly or writeonly attribute to a
1440b57cec5SDimitry Andric //   reference if function doesn't modify referenced variable (readonly)
1450b57cec5SDimitry Andric //   or doesn't read it (writeonly).
1460b57cec5SDimitry Andric //
1470b57cec5SDimitry Andric // - After computing dead symbols in combined index we do the attribute
1480b57cec5SDimitry Andric //   propagation. During this step we:
1490b57cec5SDimitry Andric //   a. clear RO and WO attributes from variables which are preserved or
1500b57cec5SDimitry Andric //      can't be imported
1510b57cec5SDimitry Andric //   b. clear RO and WO attributes from variables referenced by any global
1520b57cec5SDimitry Andric //      variable initializer
1530b57cec5SDimitry Andric //   c. clear RO attribute from variable referenced by a function when
1540b57cec5SDimitry Andric //      reference is not readonly
1550b57cec5SDimitry Andric //   d. clear WO attribute from variable referenced by a function when
1560b57cec5SDimitry Andric //      reference is not writeonly
1570b57cec5SDimitry Andric //
1580b57cec5SDimitry Andric //   Because of (c, d) we don't internalize variables read by function A
1590b57cec5SDimitry Andric //   and modified by function B.
1600b57cec5SDimitry Andric //
1610b57cec5SDimitry Andric // Internalization itself happens in the backend after import is finished
1620b57cec5SDimitry Andric // See internalizeGVsAfterImport.
1630b57cec5SDimitry Andric void ModuleSummaryIndex::propagateAttributes(
1640b57cec5SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
165*480093f4SDimitry Andric   if (!PropagateAttrs)
166*480093f4SDimitry Andric     return;
1670b57cec5SDimitry Andric   for (auto &P : *this)
1680b57cec5SDimitry Andric     for (auto &S : P.second.SummaryList) {
1690b57cec5SDimitry Andric       if (!isGlobalValueLive(S.get()))
1700b57cec5SDimitry Andric         // We don't examine references from dead objects
1710b57cec5SDimitry Andric         continue;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric       // Global variable can't be marked read/writeonly if it is not eligible
1740b57cec5SDimitry Andric       // to import since we need to ensure that all external references get
1750b57cec5SDimitry Andric       // a local (imported) copy. It also can't be marked read/writeonly if
1760b57cec5SDimitry Andric       // it or any alias (since alias points to the same memory) are preserved
1770b57cec5SDimitry Andric       // or notEligibleToImport, since either of those means there could be
1780b57cec5SDimitry Andric       // writes (or reads in case of writeonly) that are not visible (because
1790b57cec5SDimitry Andric       // preserved means it could have external to DSO writes or reads, and
1800b57cec5SDimitry Andric       // notEligibleToImport means it could have writes or reads via inline
1810b57cec5SDimitry Andric       // assembly leading it to be in the @llvm.*used).
1820b57cec5SDimitry Andric       if (auto *GVS = dyn_cast<GlobalVarSummary>(S->getBaseObject()))
1830b57cec5SDimitry Andric         // Here we intentionally pass S.get() not GVS, because S could be
184*480093f4SDimitry Andric         // an alias. We don't analyze references here, because we have to
185*480093f4SDimitry Andric         // know exactly if GV is readonly to do so.
186*480093f4SDimitry Andric         if (!canImportGlobalVar(S.get(), /* AnalyzeRefs */ false) ||
1870b57cec5SDimitry Andric             GUIDPreservedSymbols.count(P.first)) {
1880b57cec5SDimitry Andric           GVS->setReadOnly(false);
1890b57cec5SDimitry Andric           GVS->setWriteOnly(false);
1900b57cec5SDimitry Andric         }
1910b57cec5SDimitry Andric       propagateAttributesToRefs(S.get());
1920b57cec5SDimitry Andric     }
193*480093f4SDimitry Andric   setWithAttributePropagation();
1940b57cec5SDimitry Andric   if (llvm::AreStatisticsEnabled())
1950b57cec5SDimitry Andric     for (auto &P : *this)
1960b57cec5SDimitry Andric       if (P.second.SummaryList.size())
1970b57cec5SDimitry Andric         if (auto *GVS = dyn_cast<GlobalVarSummary>(
1980b57cec5SDimitry Andric                 P.second.SummaryList[0]->getBaseObject()))
1990b57cec5SDimitry Andric           if (isGlobalValueLive(GVS)) {
2000b57cec5SDimitry Andric             if (GVS->maybeReadOnly())
2010b57cec5SDimitry Andric               ReadOnlyLiveGVars++;
2020b57cec5SDimitry Andric             if (GVS->maybeWriteOnly())
2030b57cec5SDimitry Andric               WriteOnlyLiveGVars++;
2040b57cec5SDimitry Andric           }
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
207*480093f4SDimitry Andric bool ModuleSummaryIndex::canImportGlobalVar(GlobalValueSummary *S,
208*480093f4SDimitry Andric                                             bool AnalyzeRefs) const {
209*480093f4SDimitry Andric   auto HasRefsPreventingImport = [this](const GlobalVarSummary *GVS) {
210*480093f4SDimitry Andric     // We don't analyze GV references during attribute propagation, so
211*480093f4SDimitry Andric     // GV with non-trivial initializer can be marked either read or
212*480093f4SDimitry Andric     // write-only.
213*480093f4SDimitry Andric     // Importing definiton of readonly GV with non-trivial initializer
214*480093f4SDimitry Andric     // allows us doing some extra optimizations (like converting indirect
215*480093f4SDimitry Andric     // calls to direct).
216*480093f4SDimitry Andric     // Definition of writeonly GV with non-trivial initializer should also
217*480093f4SDimitry Andric     // be imported. Not doing so will result in:
218*480093f4SDimitry Andric     // a) GV internalization in source module (because it's writeonly)
219*480093f4SDimitry Andric     // b) Importing of GV declaration to destination module as a result
220*480093f4SDimitry Andric     //    of promotion.
221*480093f4SDimitry Andric     // c) Link error (external declaration with internal definition).
222*480093f4SDimitry Andric     // However we do not promote objects referenced by writeonly GV
223*480093f4SDimitry Andric     // initializer by means of converting it to 'zeroinitializer'
224*480093f4SDimitry Andric     return !isReadOnly(GVS) && !isWriteOnly(GVS) && GVS->refs().size();
225*480093f4SDimitry Andric   };
226*480093f4SDimitry Andric   auto *GVS = cast<GlobalVarSummary>(S->getBaseObject());
227*480093f4SDimitry Andric 
228*480093f4SDimitry Andric   // Global variable with non-trivial initializer can be imported
229*480093f4SDimitry Andric   // if it's readonly. This gives us extra opportunities for constant
230*480093f4SDimitry Andric   // folding and converting indirect calls to direct calls. We don't
231*480093f4SDimitry Andric   // analyze GV references during attribute propagation, because we
232*480093f4SDimitry Andric   // don't know yet if it is readonly or not.
233*480093f4SDimitry Andric   return !GlobalValue::isInterposableLinkage(S->linkage()) &&
234*480093f4SDimitry Andric          !S->notEligibleToImport() &&
235*480093f4SDimitry Andric          (!AnalyzeRefs || !HasRefsPreventingImport(GVS));
236*480093f4SDimitry Andric }
237*480093f4SDimitry Andric 
2380b57cec5SDimitry Andric // TODO: write a graphviz dumper for SCCs (see ModuleSummaryIndex::exportToDot)
2390b57cec5SDimitry Andric // then delete this function and update its tests
2400b57cec5SDimitry Andric LLVM_DUMP_METHOD
2410b57cec5SDimitry Andric void ModuleSummaryIndex::dumpSCCs(raw_ostream &O) {
2420b57cec5SDimitry Andric   for (scc_iterator<ModuleSummaryIndex *> I =
2430b57cec5SDimitry Andric            scc_begin<ModuleSummaryIndex *>(this);
2440b57cec5SDimitry Andric        !I.isAtEnd(); ++I) {
2450b57cec5SDimitry Andric     O << "SCC (" << utostr(I->size()) << " node" << (I->size() == 1 ? "" : "s")
2460b57cec5SDimitry Andric       << ") {\n";
247*480093f4SDimitry Andric     for (const ValueInfo &V : *I) {
2480b57cec5SDimitry Andric       FunctionSummary *F = nullptr;
2490b57cec5SDimitry Andric       if (V.getSummaryList().size())
2500b57cec5SDimitry Andric         F = cast<FunctionSummary>(V.getSummaryList().front().get());
2510b57cec5SDimitry Andric       O << " " << (F == nullptr ? "External" : "") << " " << utostr(V.getGUID())
2520b57cec5SDimitry Andric         << (I.hasLoop() ? " (has loop)" : "") << "\n";
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric     O << "}\n";
2550b57cec5SDimitry Andric   }
2560b57cec5SDimitry Andric }
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric namespace {
2590b57cec5SDimitry Andric struct Attributes {
2600b57cec5SDimitry Andric   void add(const Twine &Name, const Twine &Value,
2610b57cec5SDimitry Andric            const Twine &Comment = Twine());
2620b57cec5SDimitry Andric   void addComment(const Twine &Comment);
2630b57cec5SDimitry Andric   std::string getAsString() const;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   std::vector<std::string> Attrs;
2660b57cec5SDimitry Andric   std::string Comments;
2670b57cec5SDimitry Andric };
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric struct Edge {
2700b57cec5SDimitry Andric   uint64_t SrcMod;
2710b57cec5SDimitry Andric   int Hotness;
2720b57cec5SDimitry Andric   GlobalValue::GUID Src;
2730b57cec5SDimitry Andric   GlobalValue::GUID Dst;
2740b57cec5SDimitry Andric };
2750b57cec5SDimitry Andric }
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric void Attributes::add(const Twine &Name, const Twine &Value,
2780b57cec5SDimitry Andric                      const Twine &Comment) {
2790b57cec5SDimitry Andric   std::string A = Name.str();
2800b57cec5SDimitry Andric   A += "=\"";
2810b57cec5SDimitry Andric   A += Value.str();
2820b57cec5SDimitry Andric   A += "\"";
2830b57cec5SDimitry Andric   Attrs.push_back(A);
2840b57cec5SDimitry Andric   addComment(Comment);
2850b57cec5SDimitry Andric }
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric void Attributes::addComment(const Twine &Comment) {
2880b57cec5SDimitry Andric   if (!Comment.isTriviallyEmpty()) {
2890b57cec5SDimitry Andric     if (Comments.empty())
2900b57cec5SDimitry Andric       Comments = " // ";
2910b57cec5SDimitry Andric     else
2920b57cec5SDimitry Andric       Comments += ", ";
2930b57cec5SDimitry Andric     Comments += Comment.str();
2940b57cec5SDimitry Andric   }
2950b57cec5SDimitry Andric }
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric std::string Attributes::getAsString() const {
2980b57cec5SDimitry Andric   if (Attrs.empty())
2990b57cec5SDimitry Andric     return "";
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   std::string Ret = "[";
3020b57cec5SDimitry Andric   for (auto &A : Attrs)
3030b57cec5SDimitry Andric     Ret += A + ",";
3040b57cec5SDimitry Andric   Ret.pop_back();
3050b57cec5SDimitry Andric   Ret += "];";
3060b57cec5SDimitry Andric   Ret += Comments;
3070b57cec5SDimitry Andric   return Ret;
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric static std::string linkageToString(GlobalValue::LinkageTypes LT) {
3110b57cec5SDimitry Andric   switch (LT) {
3120b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
3130b57cec5SDimitry Andric     return "extern";
3140b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
3150b57cec5SDimitry Andric     return "av_ext";
3160b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
3170b57cec5SDimitry Andric     return "linkonce";
3180b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
3190b57cec5SDimitry Andric     return "linkonce_odr";
3200b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
3210b57cec5SDimitry Andric     return "weak";
3220b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
3230b57cec5SDimitry Andric     return "weak_odr";
3240b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
3250b57cec5SDimitry Andric     return "appending";
3260b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
3270b57cec5SDimitry Andric     return "internal";
3280b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
3290b57cec5SDimitry Andric     return "private";
3300b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
3310b57cec5SDimitry Andric     return "extern_weak";
3320b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
3330b57cec5SDimitry Andric     return "common";
3340b57cec5SDimitry Andric   }
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   return "<unknown>";
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric static std::string fflagsToString(FunctionSummary::FFlags F) {
3400b57cec5SDimitry Andric   auto FlagValue = [](unsigned V) { return V ? '1' : '0'; };
3410b57cec5SDimitry Andric   char FlagRep[] = {FlagValue(F.ReadNone),     FlagValue(F.ReadOnly),
3420b57cec5SDimitry Andric                     FlagValue(F.NoRecurse),    FlagValue(F.ReturnDoesNotAlias),
343*480093f4SDimitry Andric                     FlagValue(F.NoInline), FlagValue(F.AlwaysInline), 0};
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   return FlagRep;
3460b57cec5SDimitry Andric }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric // Get string representation of function instruction count and flags.
3490b57cec5SDimitry Andric static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
3500b57cec5SDimitry Andric   auto *FS = dyn_cast_or_null<FunctionSummary>(GVS);
3510b57cec5SDimitry Andric   if (!FS)
3520b57cec5SDimitry Andric     return "";
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric   return std::string("inst: ") + std::to_string(FS->instCount()) +
3550b57cec5SDimitry Andric          ", ffl: " + fflagsToString(FS->fflags());
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric static std::string getNodeVisualName(GlobalValue::GUID Id) {
3590b57cec5SDimitry Andric   return std::string("@") + std::to_string(Id);
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric static std::string getNodeVisualName(const ValueInfo &VI) {
3630b57cec5SDimitry Andric   return VI.name().empty() ? getNodeVisualName(VI.getGUID()) : VI.name().str();
3640b57cec5SDimitry Andric }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS) {
3670b57cec5SDimitry Andric   if (isa<AliasSummary>(GVS))
3680b57cec5SDimitry Andric     return getNodeVisualName(VI);
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   std::string Attrs = getSummaryAttributes(GVS);
3710b57cec5SDimitry Andric   std::string Label =
3720b57cec5SDimitry Andric       getNodeVisualName(VI) + "|" + linkageToString(GVS->linkage());
3730b57cec5SDimitry Andric   if (!Attrs.empty())
3740b57cec5SDimitry Andric     Label += std::string(" (") + Attrs + ")";
3750b57cec5SDimitry Andric   Label += "}";
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   return Label;
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric // Write definition of external node, which doesn't have any
3810b57cec5SDimitry Andric // specific module associated with it. Typically this is function
3820b57cec5SDimitry Andric // or variable defined in native object or library.
3830b57cec5SDimitry Andric static void defineExternalNode(raw_ostream &OS, const char *Pfx,
3840b57cec5SDimitry Andric                                const ValueInfo &VI, GlobalValue::GUID Id) {
3850b57cec5SDimitry Andric   auto StrId = std::to_string(Id);
3860b57cec5SDimitry Andric   OS << "  " << StrId << " [label=\"";
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   if (VI) {
3890b57cec5SDimitry Andric     OS << getNodeVisualName(VI);
3900b57cec5SDimitry Andric   } else {
3910b57cec5SDimitry Andric     OS << getNodeVisualName(Id);
3920b57cec5SDimitry Andric   }
3930b57cec5SDimitry Andric   OS << "\"]; // defined externally\n";
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric static bool hasReadOnlyFlag(const GlobalValueSummary *S) {
3970b57cec5SDimitry Andric   if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
3980b57cec5SDimitry Andric     return GVS->maybeReadOnly();
3990b57cec5SDimitry Andric   return false;
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric static bool hasWriteOnlyFlag(const GlobalValueSummary *S) {
4030b57cec5SDimitry Andric   if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
4040b57cec5SDimitry Andric     return GVS->maybeWriteOnly();
4050b57cec5SDimitry Andric   return false;
4060b57cec5SDimitry Andric }
4070b57cec5SDimitry Andric 
408*480093f4SDimitry Andric void ModuleSummaryIndex::exportToDot(
409*480093f4SDimitry Andric     raw_ostream &OS,
410*480093f4SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const {
4110b57cec5SDimitry Andric   std::vector<Edge> CrossModuleEdges;
4120b57cec5SDimitry Andric   DenseMap<GlobalValue::GUID, std::vector<uint64_t>> NodeMap;
4130b57cec5SDimitry Andric   using GVSOrderedMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>;
4140b57cec5SDimitry Andric   std::map<StringRef, GVSOrderedMapTy> ModuleToDefinedGVS;
4150b57cec5SDimitry Andric   collectDefinedGVSummariesPerModule(ModuleToDefinedGVS);
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   // Get node identifier in form MXXX_<GUID>. The MXXX prefix is required,
4180b57cec5SDimitry Andric   // because we may have multiple linkonce functions summaries.
4190b57cec5SDimitry Andric   auto NodeId = [](uint64_t ModId, GlobalValue::GUID Id) {
4200b57cec5SDimitry Andric     return ModId == (uint64_t)-1 ? std::to_string(Id)
4210b57cec5SDimitry Andric                                  : std::string("M") + std::to_string(ModId) +
4220b57cec5SDimitry Andric                                        "_" + std::to_string(Id);
4230b57cec5SDimitry Andric   };
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   auto DrawEdge = [&](const char *Pfx, uint64_t SrcMod, GlobalValue::GUID SrcId,
4260b57cec5SDimitry Andric                       uint64_t DstMod, GlobalValue::GUID DstId,
4270b57cec5SDimitry Andric                       int TypeOrHotness) {
4280b57cec5SDimitry Andric     // 0 - alias
4290b57cec5SDimitry Andric     // 1 - reference
4300b57cec5SDimitry Andric     // 2 - constant reference
4310b57cec5SDimitry Andric     // 3 - writeonly reference
4320b57cec5SDimitry Andric     // Other value: (hotness - 4).
4330b57cec5SDimitry Andric     TypeOrHotness += 4;
4340b57cec5SDimitry Andric     static const char *EdgeAttrs[] = {
4350b57cec5SDimitry Andric         " [style=dotted]; // alias",
4360b57cec5SDimitry Andric         " [style=dashed]; // ref",
4370b57cec5SDimitry Andric         " [style=dashed,color=forestgreen]; // const-ref",
4380b57cec5SDimitry Andric         " [style=dashed,color=violetred]; // writeOnly-ref",
4390b57cec5SDimitry Andric         " // call (hotness : Unknown)",
4400b57cec5SDimitry Andric         " [color=blue]; // call (hotness : Cold)",
4410b57cec5SDimitry Andric         " // call (hotness : None)",
4420b57cec5SDimitry Andric         " [color=brown]; // call (hotness : Hot)",
4430b57cec5SDimitry Andric         " [style=bold,color=red]; // call (hotness : Critical)"};
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric     assert(static_cast<size_t>(TypeOrHotness) <
4460b57cec5SDimitry Andric            sizeof(EdgeAttrs) / sizeof(EdgeAttrs[0]));
4470b57cec5SDimitry Andric     OS << Pfx << NodeId(SrcMod, SrcId) << " -> " << NodeId(DstMod, DstId)
4480b57cec5SDimitry Andric        << EdgeAttrs[TypeOrHotness] << "\n";
4490b57cec5SDimitry Andric   };
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   OS << "digraph Summary {\n";
4520b57cec5SDimitry Andric   for (auto &ModIt : ModuleToDefinedGVS) {
4530b57cec5SDimitry Andric     auto ModId = getModuleId(ModIt.first);
4540b57cec5SDimitry Andric     OS << "  // Module: " << ModIt.first << "\n";
4550b57cec5SDimitry Andric     OS << "  subgraph cluster_" << std::to_string(ModId) << " {\n";
4560b57cec5SDimitry Andric     OS << "    style = filled;\n";
4570b57cec5SDimitry Andric     OS << "    color = lightgrey;\n";
4580b57cec5SDimitry Andric     OS << "    label = \"" << sys::path::filename(ModIt.first) << "\";\n";
4590b57cec5SDimitry Andric     OS << "    node [style=filled,fillcolor=lightblue];\n";
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric     auto &GVSMap = ModIt.second;
4620b57cec5SDimitry Andric     auto Draw = [&](GlobalValue::GUID IdFrom, GlobalValue::GUID IdTo, int Hotness) {
4630b57cec5SDimitry Andric       if (!GVSMap.count(IdTo)) {
4640b57cec5SDimitry Andric         CrossModuleEdges.push_back({ModId, Hotness, IdFrom, IdTo});
4650b57cec5SDimitry Andric         return;
4660b57cec5SDimitry Andric       }
4670b57cec5SDimitry Andric       DrawEdge("    ", ModId, IdFrom, ModId, IdTo, Hotness);
4680b57cec5SDimitry Andric     };
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric     for (auto &SummaryIt : GVSMap) {
4710b57cec5SDimitry Andric       NodeMap[SummaryIt.first].push_back(ModId);
4720b57cec5SDimitry Andric       auto Flags = SummaryIt.second->flags();
4730b57cec5SDimitry Andric       Attributes A;
4740b57cec5SDimitry Andric       if (isa<FunctionSummary>(SummaryIt.second)) {
4750b57cec5SDimitry Andric         A.add("shape", "record", "function");
4760b57cec5SDimitry Andric       } else if (isa<AliasSummary>(SummaryIt.second)) {
4770b57cec5SDimitry Andric         A.add("style", "dotted,filled", "alias");
4780b57cec5SDimitry Andric         A.add("shape", "box");
4790b57cec5SDimitry Andric       } else {
4800b57cec5SDimitry Andric         A.add("shape", "Mrecord", "variable");
4810b57cec5SDimitry Andric         if (Flags.Live && hasReadOnlyFlag(SummaryIt.second))
4820b57cec5SDimitry Andric           A.addComment("immutable");
4830b57cec5SDimitry Andric         if (Flags.Live && hasWriteOnlyFlag(SummaryIt.second))
4840b57cec5SDimitry Andric           A.addComment("writeOnly");
4850b57cec5SDimitry Andric       }
4860b57cec5SDimitry Andric       if (Flags.DSOLocal)
4870b57cec5SDimitry Andric         A.addComment("dsoLocal");
4880b57cec5SDimitry Andric       if (Flags.CanAutoHide)
4890b57cec5SDimitry Andric         A.addComment("canAutoHide");
490*480093f4SDimitry Andric       if (GUIDPreservedSymbols.count(SummaryIt.first))
491*480093f4SDimitry Andric         A.addComment("preserved");
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric       auto VI = getValueInfo(SummaryIt.first);
4940b57cec5SDimitry Andric       A.add("label", getNodeLabel(VI, SummaryIt.second));
4950b57cec5SDimitry Andric       if (!Flags.Live)
4960b57cec5SDimitry Andric         A.add("fillcolor", "red", "dead");
4970b57cec5SDimitry Andric       else if (Flags.NotEligibleToImport)
4980b57cec5SDimitry Andric         A.add("fillcolor", "yellow", "not eligible to import");
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric       OS << "    " << NodeId(ModId, SummaryIt.first) << " " << A.getAsString()
5010b57cec5SDimitry Andric          << "\n";
5020b57cec5SDimitry Andric     }
5030b57cec5SDimitry Andric     OS << "    // Edges:\n";
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric     for (auto &SummaryIt : GVSMap) {
5060b57cec5SDimitry Andric       auto *GVS = SummaryIt.second;
5070b57cec5SDimitry Andric       for (auto &R : GVS->refs())
5080b57cec5SDimitry Andric         Draw(SummaryIt.first, R.getGUID(),
5090b57cec5SDimitry Andric              R.isWriteOnly() ? -1 : (R.isReadOnly() ? -2 : -3));
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric       if (auto *AS = dyn_cast_or_null<AliasSummary>(SummaryIt.second)) {
5120b57cec5SDimitry Andric         Draw(SummaryIt.first, AS->getAliaseeGUID(), -4);
5130b57cec5SDimitry Andric         continue;
5140b57cec5SDimitry Andric       }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric       if (auto *FS = dyn_cast_or_null<FunctionSummary>(SummaryIt.second))
5170b57cec5SDimitry Andric         for (auto &CGEdge : FS->calls())
5180b57cec5SDimitry Andric           Draw(SummaryIt.first, CGEdge.first.getGUID(),
5190b57cec5SDimitry Andric                static_cast<int>(CGEdge.second.Hotness));
5200b57cec5SDimitry Andric     }
5210b57cec5SDimitry Andric     OS << "  }\n";
5220b57cec5SDimitry Andric   }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   OS << "  // Cross-module edges:\n";
5250b57cec5SDimitry Andric   for (auto &E : CrossModuleEdges) {
5260b57cec5SDimitry Andric     auto &ModList = NodeMap[E.Dst];
5270b57cec5SDimitry Andric     if (ModList.empty()) {
5280b57cec5SDimitry Andric       defineExternalNode(OS, "  ", getValueInfo(E.Dst), E.Dst);
5290b57cec5SDimitry Andric       // Add fake module to the list to draw an edge to an external node
5300b57cec5SDimitry Andric       // in the loop below.
5310b57cec5SDimitry Andric       ModList.push_back(-1);
5320b57cec5SDimitry Andric     }
5330b57cec5SDimitry Andric     for (auto DstMod : ModList)
5340b57cec5SDimitry Andric       // The edge representing call or ref is drawn to every module where target
5350b57cec5SDimitry Andric       // symbol is defined. When target is a linkonce symbol there can be
5360b57cec5SDimitry Andric       // multiple edges representing a single call or ref, both intra-module and
5370b57cec5SDimitry Andric       // cross-module. As we've already drawn all intra-module edges before we
5380b57cec5SDimitry Andric       // skip it here.
5390b57cec5SDimitry Andric       if (DstMod != E.SrcMod)
5400b57cec5SDimitry Andric         DrawEdge("  ", E.SrcMod, E.Src, DstMod, E.Dst, E.Hotness);
5410b57cec5SDimitry Andric   }
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   OS << "}";
5440b57cec5SDimitry Andric }
545