126ab5772STeresa Johnson //===-- ModuleSummaryIndex.cpp - Module Summary Index ---------------------===//
226ab5772STeresa Johnson //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
626ab5772STeresa Johnson //
726ab5772STeresa Johnson //===----------------------------------------------------------------------===//
826ab5772STeresa Johnson //
926ab5772STeresa Johnson // This file implements the module index and summary classes for the
1026ab5772STeresa Johnson // IR library.
1126ab5772STeresa Johnson //
1226ab5772STeresa Johnson //===----------------------------------------------------------------------===//
1326ab5772STeresa Johnson 
1426ab5772STeresa Johnson #include "llvm/IR/ModuleSummaryIndex.h"
15b040fcc6SCharles Saternos #include "llvm/ADT/SCCIterator.h"
168c1915ccSTeresa Johnson #include "llvm/ADT/Statistic.h"
1754a3c2a8STeresa Johnson #include "llvm/Support/CommandLine.h"
1828d8a49fSEugene Leviant #include "llvm/Support/Path.h"
19b040fcc6SCharles Saternos #include "llvm/Support/raw_ostream.h"
2026ab5772STeresa Johnson using namespace llvm;
2126ab5772STeresa Johnson 
228c1915ccSTeresa Johnson #define DEBUG_TYPE "module-summary-index"
238c1915ccSTeresa Johnson 
248c1915ccSTeresa Johnson STATISTIC(ReadOnlyLiveGVars,
258c1915ccSTeresa Johnson           "Number of live global variables marked read only");
263aef3528SEugene Leviant STATISTIC(WriteOnlyLiveGVars,
273aef3528SEugene Leviant           "Number of live global variables marked write only");
288c1915ccSTeresa Johnson 
2954a3c2a8STeresa Johnson static cl::opt<bool> PropagateAttrs("propagate-attrs", cl::init(true),
3054a3c2a8STeresa Johnson                                     cl::Hidden,
3154a3c2a8STeresa Johnson                                     cl::desc("Propagate attributes in index"));
3254a3c2a8STeresa Johnson 
33c45bb326STeresa Johnson static cl::opt<bool> ImportConstantsWithRefs(
342102ef8aSTeresa Johnson     "import-constants-with-refs", cl::init(true), cl::Hidden,
35c45bb326STeresa Johnson     cl::desc("Import constant global variables with references"));
36c45bb326STeresa Johnson 
37e35a5876SAlexey Bataev constexpr uint32_t FunctionSummary::ParamAccess::RangeWidth;
38e35a5876SAlexey Bataev 
39b040fcc6SCharles Saternos FunctionSummary FunctionSummary::ExternalNode =
40b040fcc6SCharles Saternos     FunctionSummary::makeDummyFunctionSummary({});
4137b80122STeresa Johnson 
getELFVisibility() const4254fb3ca9SFangrui Song GlobalValue::VisibilityTypes ValueInfo::getELFVisibility() const {
4354fb3ca9SFangrui Song   bool HasProtected = false;
4454fb3ca9SFangrui Song   for (const auto &S : make_pointee_range(getSummaryList())) {
4554fb3ca9SFangrui Song     if (S.getVisibility() == GlobalValue::HiddenVisibility)
4654fb3ca9SFangrui Song       return GlobalValue::HiddenVisibility;
4754fb3ca9SFangrui Song     if (S.getVisibility() == GlobalValue::ProtectedVisibility)
4854fb3ca9SFangrui Song       HasProtected = true;
4954fb3ca9SFangrui Song   }
5054fb3ca9SFangrui Song   return HasProtected ? GlobalValue::ProtectedVisibility
5154fb3ca9SFangrui Song                       : GlobalValue::DefaultVisibility;
5254fb3ca9SFangrui Song }
5354fb3ca9SFangrui Song 
isDSOLocal(bool WithDSOLocalPropagation) const5480dc0661SWei Wang bool ValueInfo::isDSOLocal(bool WithDSOLocalPropagation) const {
5580dc0661SWei Wang   // With DSOLocal propagation done, the flag in evey summary is the same.
5680dc0661SWei Wang   // Check the first one is enough.
5780dc0661SWei Wang   return WithDSOLocalPropagation
5880dc0661SWei Wang              ? getSummaryList().size() && getSummaryList()[0]->isDSOLocal()
5980dc0661SWei Wang              : getSummaryList().size() &&
6080dc0661SWei Wang                    llvm::all_of(
6180dc0661SWei Wang                        getSummaryList(),
62b4edfb9aSPeter Collingbourne                        [](const std::unique_ptr<GlobalValueSummary> &Summary) {
63b4edfb9aSPeter Collingbourne                          return Summary->isDSOLocal();
64b4edfb9aSPeter Collingbourne                        });
65b4edfb9aSPeter Collingbourne }
66b4edfb9aSPeter Collingbourne 
canAutoHide() const6737b80122STeresa Johnson bool ValueInfo::canAutoHide() const {
6837b80122STeresa Johnson   // Can only auto hide if all copies are eligible to auto hide.
6937b80122STeresa Johnson   return getSummaryList().size() &&
7037b80122STeresa Johnson          llvm::all_of(getSummaryList(),
7137b80122STeresa Johnson                       [](const std::unique_ptr<GlobalValueSummary> &Summary) {
7237b80122STeresa Johnson                         return Summary->canAutoHide();
7337b80122STeresa Johnson                       });
7437b80122STeresa Johnson }
7537b80122STeresa Johnson 
763aef3528SEugene Leviant // Gets the number of readonly and writeonly refs in RefEdgeList
specialRefCounts() const773aef3528SEugene Leviant std::pair<unsigned, unsigned> FunctionSummary::specialRefCounts() const {
783aef3528SEugene Leviant   // Here we take advantage of having all readonly and writeonly references
79bf46e741SEugene Leviant   // located in the end of the RefEdgeList.
80bf46e741SEugene Leviant   auto Refs = refs();
813aef3528SEugene Leviant   unsigned RORefCnt = 0, WORefCnt = 0;
823aef3528SEugene Leviant   int I;
833aef3528SEugene Leviant   for (I = Refs.size() - 1; I >= 0 && Refs[I].isWriteOnly(); --I)
843aef3528SEugene Leviant     WORefCnt++;
853aef3528SEugene Leviant   for (; I >= 0 && Refs[I].isReadOnly(); --I)
863aef3528SEugene Leviant     RORefCnt++;
873aef3528SEugene Leviant   return {RORefCnt, WORefCnt};
88bf46e741SEugene Leviant }
89bf46e741SEugene Leviant 
906a1b5128SAndrew Browne constexpr uint64_t ModuleSummaryIndex::BitcodeSummaryVersion;
916a1b5128SAndrew Browne 
getFlags() const92c85055b2Sevgeny uint64_t ModuleSummaryIndex::getFlags() const {
93c85055b2Sevgeny   uint64_t Flags = 0;
94c85055b2Sevgeny   if (withGlobalValueDeadStripping())
95c85055b2Sevgeny     Flags |= 0x1;
96c85055b2Sevgeny   if (skipModuleByDistributedBackend())
97c85055b2Sevgeny     Flags |= 0x2;
98c85055b2Sevgeny   if (hasSyntheticEntryCounts())
99c85055b2Sevgeny     Flags |= 0x4;
100c85055b2Sevgeny   if (enableSplitLTOUnit())
101c85055b2Sevgeny     Flags |= 0x8;
102c85055b2Sevgeny   if (partiallySplitLTOUnits())
103c85055b2Sevgeny     Flags |= 0x10;
104c85055b2Sevgeny   if (withAttributePropagation())
105c85055b2Sevgeny     Flags |= 0x20;
10680dc0661SWei Wang   if (withDSOLocalPropagation())
10780dc0661SWei Wang     Flags |= 0x40;
108*2eade1dbSArthur Eubanks   if (withWholeProgramVisibility())
109*2eade1dbSArthur Eubanks     Flags |= 0x80;
110c85055b2Sevgeny   return Flags;
111c85055b2Sevgeny }
112c85055b2Sevgeny 
setFlags(uint64_t Flags)113c85055b2Sevgeny void ModuleSummaryIndex::setFlags(uint64_t Flags) {
114*2eade1dbSArthur Eubanks   assert(Flags <= 0xff && "Unexpected bits in flag");
115c85055b2Sevgeny   // 1 bit: WithGlobalValueDeadStripping flag.
116c85055b2Sevgeny   // Set on combined index only.
117c85055b2Sevgeny   if (Flags & 0x1)
118c85055b2Sevgeny     setWithGlobalValueDeadStripping();
119c85055b2Sevgeny   // 1 bit: SkipModuleByDistributedBackend flag.
120c85055b2Sevgeny   // Set on combined index only.
121c85055b2Sevgeny   if (Flags & 0x2)
122c85055b2Sevgeny     setSkipModuleByDistributedBackend();
123c85055b2Sevgeny   // 1 bit: HasSyntheticEntryCounts flag.
124c85055b2Sevgeny   // Set on combined index only.
125c85055b2Sevgeny   if (Flags & 0x4)
126c85055b2Sevgeny     setHasSyntheticEntryCounts();
127c85055b2Sevgeny   // 1 bit: DisableSplitLTOUnit flag.
128c85055b2Sevgeny   // Set on per module indexes. It is up to the client to validate
129c85055b2Sevgeny   // the consistency of this flag across modules being linked.
130c85055b2Sevgeny   if (Flags & 0x8)
131c85055b2Sevgeny     setEnableSplitLTOUnit();
132c85055b2Sevgeny   // 1 bit: PartiallySplitLTOUnits flag.
133c85055b2Sevgeny   // Set on combined index only.
134c85055b2Sevgeny   if (Flags & 0x10)
135c85055b2Sevgeny     setPartiallySplitLTOUnits();
136c85055b2Sevgeny   // 1 bit: WithAttributePropagation flag.
137c85055b2Sevgeny   // Set on combined index only.
138c85055b2Sevgeny   if (Flags & 0x20)
139c85055b2Sevgeny     setWithAttributePropagation();
14080dc0661SWei Wang   // 1 bit: WithDSOLocalPropagation flag.
14180dc0661SWei Wang   // Set on combined index only.
14280dc0661SWei Wang   if (Flags & 0x40)
14380dc0661SWei Wang     setWithDSOLocalPropagation();
144*2eade1dbSArthur Eubanks   // 1 bit: WithWholeProgramVisibility flag.
145*2eade1dbSArthur Eubanks   // Set on combined index only.
146*2eade1dbSArthur Eubanks   if (Flags & 0x80)
147*2eade1dbSArthur Eubanks     setWithWholeProgramVisibility();
148c85055b2Sevgeny }
149c85055b2Sevgeny 
150c86af334STeresa Johnson // Collect for the given module the list of function it defines
151c86af334STeresa Johnson // (GUID -> Summary).
collectDefinedFunctionsForModule(StringRef ModulePath,GVSummaryMapTy & GVSummaryMap) const152c86af334STeresa Johnson void ModuleSummaryIndex::collectDefinedFunctionsForModule(
153c851d216STeresa Johnson     StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const {
154c86af334STeresa Johnson   for (auto &GlobalList : *this) {
155c86af334STeresa Johnson     auto GUID = GlobalList.first;
1569667b91bSPeter Collingbourne     for (auto &GlobSummary : GlobalList.second.SummaryList) {
15728e457bcSTeresa Johnson       auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobSummary.get());
158c86af334STeresa Johnson       if (!Summary)
159c86af334STeresa Johnson         // Ignore global variable, focus on functions
160c86af334STeresa Johnson         continue;
161c86af334STeresa Johnson       // Ignore summaries from other modules.
162c86af334STeresa Johnson       if (Summary->modulePath() != ModulePath)
163c86af334STeresa Johnson         continue;
16428e457bcSTeresa Johnson       GVSummaryMap[GUID] = Summary;
165c86af334STeresa Johnson     }
166c86af334STeresa Johnson   }
167c86af334STeresa Johnson }
168c86af334STeresa Johnson 
16928e457bcSTeresa Johnson GlobalValueSummary *
getGlobalValueSummary(uint64_t ValueGUID,bool PerModuleIndex) const17028e457bcSTeresa Johnson ModuleSummaryIndex::getGlobalValueSummary(uint64_t ValueGUID,
171fb7c7644STeresa Johnson                                           bool PerModuleIndex) const {
1729667b91bSPeter Collingbourne   auto VI = getValueInfo(ValueGUID);
1739667b91bSPeter Collingbourne   assert(VI && "GlobalValue not found in index");
1749667b91bSPeter Collingbourne   assert((!PerModuleIndex || VI.getSummaryList().size() == 1) &&
175fb7c7644STeresa Johnson          "Expected a single entry per global value in per-module index");
1769667b91bSPeter Collingbourne   auto &Summary = VI.getSummaryList()[0];
17728e457bcSTeresa Johnson   return Summary.get();
178fb7c7644STeresa Johnson }
179dbd2fed6SPeter Collingbourne 
isGUIDLive(GlobalValue::GUID GUID) const180dbd2fed6SPeter Collingbourne bool ModuleSummaryIndex::isGUIDLive(GlobalValue::GUID GUID) const {
181dbd2fed6SPeter Collingbourne   auto VI = getValueInfo(GUID);
182dbd2fed6SPeter Collingbourne   if (!VI)
1834d4ee93dSEvgeniy Stepanov     return true;
1844d4ee93dSEvgeniy Stepanov   const auto &SummaryList = VI.getSummaryList();
1854d4ee93dSEvgeniy Stepanov   if (SummaryList.empty())
1864d4ee93dSEvgeniy Stepanov     return true;
1874d4ee93dSEvgeniy Stepanov   for (auto &I : SummaryList)
188dbd2fed6SPeter Collingbourne     if (isGlobalValueLive(I.get()))
189dbd2fed6SPeter Collingbourne       return true;
190dbd2fed6SPeter Collingbourne   return false;
191dbd2fed6SPeter Collingbourne }
19228d8a49fSEugene Leviant 
1931479cdfeSTeresa Johnson static void
propagateAttributesToRefs(GlobalValueSummary * S,DenseSet<ValueInfo> & MarkedNonReadWriteOnly)1941479cdfeSTeresa Johnson propagateAttributesToRefs(GlobalValueSummary *S,
1951479cdfeSTeresa Johnson                           DenseSet<ValueInfo> &MarkedNonReadWriteOnly) {
1963aef3528SEugene Leviant   // If reference is not readonly or writeonly then referenced summary is not
1973aef3528SEugene Leviant   // read/writeonly either. Note that:
198bf46e741SEugene Leviant   // - All references from GlobalVarSummary are conservatively considered as
1993aef3528SEugene Leviant   //   not readonly or writeonly. Tracking them properly requires more complex
2003aef3528SEugene Leviant   //   analysis then we have now.
201bf46e741SEugene Leviant   //
202bf46e741SEugene Leviant   // - AliasSummary objects have no refs at all so this function is a no-op
203bf46e741SEugene Leviant   //   for them.
204bf46e741SEugene Leviant   for (auto &VI : S->refs()) {
2053aef3528SEugene Leviant     assert(VI.getAccessSpecifier() == 0 || isa<FunctionSummary>(S));
2061479cdfeSTeresa Johnson     if (!VI.getAccessSpecifier()) {
2071479cdfeSTeresa Johnson       if (!MarkedNonReadWriteOnly.insert(VI).second)
2081479cdfeSTeresa Johnson         continue;
209805d5959SKazu Hirata     } else if (MarkedNonReadWriteOnly.contains(VI))
2101479cdfeSTeresa Johnson       continue;
211e91f86f0SEugene Leviant     for (auto &Ref : VI.getSummaryList())
2123aef3528SEugene Leviant       // If references to alias is not read/writeonly then aliasee
2133aef3528SEugene Leviant       // is not read/writeonly
2143aef3528SEugene Leviant       if (auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject())) {
2153aef3528SEugene Leviant         if (!VI.isReadOnly())
216e91f86f0SEugene Leviant           GVS->setReadOnly(false);
2173aef3528SEugene Leviant         if (!VI.isWriteOnly())
2183aef3528SEugene Leviant           GVS->setWriteOnly(false);
2193aef3528SEugene Leviant       }
220bf46e741SEugene Leviant   }
221bf46e741SEugene Leviant }
222bf46e741SEugene Leviant 
22380dc0661SWei Wang // Do the access attribute and DSOLocal propagation in combined index.
2243aef3528SEugene Leviant // The goal of attribute propagation is internalization of readonly (RO)
2253aef3528SEugene Leviant // or writeonly (WO) variables. To determine which variables are RO or WO
2263aef3528SEugene Leviant // and which are not we take following steps:
2273aef3528SEugene Leviant // - During analysis we speculatively assign readonly and writeonly
2283aef3528SEugene Leviant //   attribute to all variables which can be internalized. When computing
2293aef3528SEugene Leviant //   function summary we also assign readonly or writeonly attribute to a
2303aef3528SEugene Leviant //   reference if function doesn't modify referenced variable (readonly)
2313aef3528SEugene Leviant //   or doesn't read it (writeonly).
232bf46e741SEugene Leviant //
2333aef3528SEugene Leviant // - After computing dead symbols in combined index we do the attribute
23480dc0661SWei Wang //   and DSOLocal propagation. During this step we:
2353aef3528SEugene Leviant //   a. clear RO and WO attributes from variables which are preserved or
2363aef3528SEugene Leviant //      can't be imported
2373aef3528SEugene Leviant //   b. clear RO and WO attributes from variables referenced by any global
2383aef3528SEugene Leviant //      variable initializer
2393aef3528SEugene Leviant //   c. clear RO attribute from variable referenced by a function when
2403aef3528SEugene Leviant //      reference is not readonly
2413aef3528SEugene Leviant //   d. clear WO attribute from variable referenced by a function when
2423aef3528SEugene Leviant //      reference is not writeonly
24380dc0661SWei Wang //   e. clear IsDSOLocal flag in every summary if any of them is false.
2443aef3528SEugene Leviant //
2453aef3528SEugene Leviant //   Because of (c, d) we don't internalize variables read by function A
2463aef3528SEugene Leviant //   and modified by function B.
247bf46e741SEugene Leviant //
248bf46e741SEugene Leviant // Internalization itself happens in the backend after import is finished
2493aef3528SEugene Leviant // See internalizeGVsAfterImport.
propagateAttributes(const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols)2503aef3528SEugene Leviant void ModuleSummaryIndex::propagateAttributes(
251bf46e741SEugene Leviant     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
25254a3c2a8STeresa Johnson   if (!PropagateAttrs)
25354a3c2a8STeresa Johnson     return;
2541479cdfeSTeresa Johnson   DenseSet<ValueInfo> MarkedNonReadWriteOnly;
25580dc0661SWei Wang   for (auto &P : *this) {
25680dc0661SWei Wang     bool IsDSOLocal = true;
257bf46e741SEugene Leviant     for (auto &S : P.second.SummaryList) {
2581479cdfeSTeresa Johnson       if (!isGlobalValueLive(S.get())) {
25996cb97c4STeresa Johnson         // computeDeadSymbolsAndUpdateIndirectCalls should have marked all
26096cb97c4STeresa Johnson         // copies live. Note that it is possible that there is a GUID collision
26196cb97c4STeresa Johnson         // between internal symbols with the same name in different files of the
26296cb97c4STeresa Johnson         // same name but not enough distinguishing path. Because
26396cb97c4STeresa Johnson         // computeDeadSymbolsAndUpdateIndirectCalls should conservatively mark
26496cb97c4STeresa Johnson         // all copies live we can assert here that all are dead if any copy is
26596cb97c4STeresa Johnson         // dead.
2661479cdfeSTeresa Johnson         assert(llvm::none_of(
2671479cdfeSTeresa Johnson             P.second.SummaryList,
2681479cdfeSTeresa Johnson             [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
2691479cdfeSTeresa Johnson               return isGlobalValueLive(Summary.get());
2701479cdfeSTeresa Johnson             }));
271bf46e741SEugene Leviant         // We don't examine references from dead objects
2721479cdfeSTeresa Johnson         break;
2731479cdfeSTeresa Johnson       }
274bf46e741SEugene Leviant 
2753aef3528SEugene Leviant       // Global variable can't be marked read/writeonly if it is not eligible
2763aef3528SEugene Leviant       // to import since we need to ensure that all external references get
2773aef3528SEugene Leviant       // a local (imported) copy. It also can't be marked read/writeonly if
2783aef3528SEugene Leviant       // it or any alias (since alias points to the same memory) are preserved
2793aef3528SEugene Leviant       // or notEligibleToImport, since either of those means there could be
2803aef3528SEugene Leviant       // writes (or reads in case of writeonly) that are not visible (because
2813aef3528SEugene Leviant       // preserved means it could have external to DSO writes or reads, and
2823aef3528SEugene Leviant       // notEligibleToImport means it could have writes or reads via inline
2833aef3528SEugene Leviant       // assembly leading it to be in the @llvm.*used).
284bf46e741SEugene Leviant       if (auto *GVS = dyn_cast<GlobalVarSummary>(S->getBaseObject()))
285bf46e741SEugene Leviant         // Here we intentionally pass S.get() not GVS, because S could be
286dde58938Sevgeny         // an alias. We don't analyze references here, because we have to
287dde58938Sevgeny         // know exactly if GV is readonly to do so.
288dde58938Sevgeny         if (!canImportGlobalVar(S.get(), /* AnalyzeRefs */ false) ||
2893aef3528SEugene Leviant             GUIDPreservedSymbols.count(P.first)) {
290bf46e741SEugene Leviant           GVS->setReadOnly(false);
2913aef3528SEugene Leviant           GVS->setWriteOnly(false);
2923aef3528SEugene Leviant         }
2931479cdfeSTeresa Johnson       propagateAttributesToRefs(S.get(), MarkedNonReadWriteOnly);
29480dc0661SWei Wang 
29580dc0661SWei Wang       // If the flag from any summary is false, the GV is not DSOLocal.
29680dc0661SWei Wang       IsDSOLocal &= S->isDSOLocal();
29780dc0661SWei Wang     }
29880dc0661SWei Wang     if (!IsDSOLocal)
29980dc0661SWei Wang       // Mark the flag in all summaries false so that we can do quick check
30080dc0661SWei Wang       // without going through the whole list.
3014444b343SKazu Hirata       for (const std::unique_ptr<GlobalValueSummary> &Summary :
3024444b343SKazu Hirata            P.second.SummaryList)
3034444b343SKazu Hirata         Summary->setDSOLocal(false);
304bf46e741SEugene Leviant   }
30554a3c2a8STeresa Johnson   setWithAttributePropagation();
30680dc0661SWei Wang   setWithDSOLocalPropagation();
3075b9bb25cSTeresa Johnson   if (llvm::AreStatisticsEnabled())
3088c1915ccSTeresa Johnson     for (auto &P : *this)
3098c1915ccSTeresa Johnson       if (P.second.SummaryList.size())
3108c1915ccSTeresa Johnson         if (auto *GVS = dyn_cast<GlobalVarSummary>(
3118c1915ccSTeresa Johnson                 P.second.SummaryList[0]->getBaseObject()))
3123aef3528SEugene Leviant           if (isGlobalValueLive(GVS)) {
3133aef3528SEugene Leviant             if (GVS->maybeReadOnly())
3148c1915ccSTeresa Johnson               ReadOnlyLiveGVars++;
3153aef3528SEugene Leviant             if (GVS->maybeWriteOnly())
3163aef3528SEugene Leviant               WriteOnlyLiveGVars++;
3173aef3528SEugene Leviant           }
318bf46e741SEugene Leviant }
319bf46e741SEugene Leviant 
canImportGlobalVar(GlobalValueSummary * S,bool AnalyzeRefs) const320dde58938Sevgeny bool ModuleSummaryIndex::canImportGlobalVar(GlobalValueSummary *S,
321dde58938Sevgeny                                             bool AnalyzeRefs) const {
322dde58938Sevgeny   auto HasRefsPreventingImport = [this](const GlobalVarSummary *GVS) {
3237f92d66fSevgeny     // We don't analyze GV references during attribute propagation, so
3247f92d66fSevgeny     // GV with non-trivial initializer can be marked either read or
3257f92d66fSevgeny     // write-only.
3267f92d66fSevgeny     // Importing definiton of readonly GV with non-trivial initializer
3277f92d66fSevgeny     // allows us doing some extra optimizations (like converting indirect
3287f92d66fSevgeny     // calls to direct).
3297f92d66fSevgeny     // Definition of writeonly GV with non-trivial initializer should also
3307f92d66fSevgeny     // be imported. Not doing so will result in:
3317f92d66fSevgeny     // a) GV internalization in source module (because it's writeonly)
3327f92d66fSevgeny     // b) Importing of GV declaration to destination module as a result
3337f92d66fSevgeny     //    of promotion.
3347f92d66fSevgeny     // c) Link error (external declaration with internal definition).
3357f92d66fSevgeny     // However we do not promote objects referenced by writeonly GV
3367f92d66fSevgeny     // initializer by means of converting it to 'zeroinitializer'
337c45bb326STeresa Johnson     return !(ImportConstantsWithRefs && GVS->isConstant()) &&
338c45bb326STeresa Johnson            !isReadOnly(GVS) && !isWriteOnly(GVS) && GVS->refs().size();
339dde58938Sevgeny   };
340dde58938Sevgeny   auto *GVS = cast<GlobalVarSummary>(S->getBaseObject());
341dde58938Sevgeny 
342dde58938Sevgeny   // Global variable with non-trivial initializer can be imported
343dde58938Sevgeny   // if it's readonly. This gives us extra opportunities for constant
344dde58938Sevgeny   // folding and converting indirect calls to direct calls. We don't
345dde58938Sevgeny   // analyze GV references during attribute propagation, because we
346dde58938Sevgeny   // don't know yet if it is readonly or not.
347dde58938Sevgeny   return !GlobalValue::isInterposableLinkage(S->linkage()) &&
348dde58938Sevgeny          !S->notEligibleToImport() &&
349dde58938Sevgeny          (!AnalyzeRefs || !HasRefsPreventingImport(GVS));
350dde58938Sevgeny }
351dde58938Sevgeny 
352b040fcc6SCharles Saternos // TODO: write a graphviz dumper for SCCs (see ModuleSummaryIndex::exportToDot)
353b040fcc6SCharles Saternos // then delete this function and update its tests
354b040fcc6SCharles Saternos LLVM_DUMP_METHOD
dumpSCCs(raw_ostream & O)355b040fcc6SCharles Saternos void ModuleSummaryIndex::dumpSCCs(raw_ostream &O) {
356b040fcc6SCharles Saternos   for (scc_iterator<ModuleSummaryIndex *> I =
357b040fcc6SCharles Saternos            scc_begin<ModuleSummaryIndex *>(this);
358b040fcc6SCharles Saternos        !I.isAtEnd(); ++I) {
359b040fcc6SCharles Saternos     O << "SCC (" << utostr(I->size()) << " node" << (I->size() == 1 ? "" : "s")
360b040fcc6SCharles Saternos       << ") {\n";
3611a8ff896SMark de Wever     for (const ValueInfo &V : *I) {
362b040fcc6SCharles Saternos       FunctionSummary *F = nullptr;
363b040fcc6SCharles Saternos       if (V.getSummaryList().size())
364b040fcc6SCharles Saternos         F = cast<FunctionSummary>(V.getSummaryList().front().get());
365b040fcc6SCharles Saternos       O << " " << (F == nullptr ? "External" : "") << " " << utostr(V.getGUID())
36621390eabSStefanos Baziotis         << (I.hasCycle() ? " (has cycle)" : "") << "\n";
367b040fcc6SCharles Saternos     }
368b040fcc6SCharles Saternos     O << "}\n";
369b040fcc6SCharles Saternos   }
370b040fcc6SCharles Saternos }
371b040fcc6SCharles Saternos 
37228d8a49fSEugene Leviant namespace {
37328d8a49fSEugene Leviant struct Attributes {
37428d8a49fSEugene Leviant   void add(const Twine &Name, const Twine &Value,
37528d8a49fSEugene Leviant            const Twine &Comment = Twine());
376bf46e741SEugene Leviant   void addComment(const Twine &Comment);
37728d8a49fSEugene Leviant   std::string getAsString() const;
37828d8a49fSEugene Leviant 
37928d8a49fSEugene Leviant   std::vector<std::string> Attrs;
38028d8a49fSEugene Leviant   std::string Comments;
38128d8a49fSEugene Leviant };
38228d8a49fSEugene Leviant 
38328d8a49fSEugene Leviant struct Edge {
38428d8a49fSEugene Leviant   uint64_t SrcMod;
38528d8a49fSEugene Leviant   int Hotness;
38628d8a49fSEugene Leviant   GlobalValue::GUID Src;
38728d8a49fSEugene Leviant   GlobalValue::GUID Dst;
38828d8a49fSEugene Leviant };
38928d8a49fSEugene Leviant }
39028d8a49fSEugene Leviant 
add(const Twine & Name,const Twine & Value,const Twine & Comment)39128d8a49fSEugene Leviant void Attributes::add(const Twine &Name, const Twine &Value,
39228d8a49fSEugene Leviant                      const Twine &Comment) {
39328d8a49fSEugene Leviant   std::string A = Name.str();
39428d8a49fSEugene Leviant   A += "=\"";
39528d8a49fSEugene Leviant   A += Value.str();
39628d8a49fSEugene Leviant   A += "\"";
39728d8a49fSEugene Leviant   Attrs.push_back(A);
398bf46e741SEugene Leviant   addComment(Comment);
399bf46e741SEugene Leviant }
400bf46e741SEugene Leviant 
addComment(const Twine & Comment)401bf46e741SEugene Leviant void Attributes::addComment(const Twine &Comment) {
40228d8a49fSEugene Leviant   if (!Comment.isTriviallyEmpty()) {
40328d8a49fSEugene Leviant     if (Comments.empty())
40428d8a49fSEugene Leviant       Comments = " // ";
40528d8a49fSEugene Leviant     else
40628d8a49fSEugene Leviant       Comments += ", ";
40728d8a49fSEugene Leviant     Comments += Comment.str();
40828d8a49fSEugene Leviant   }
40928d8a49fSEugene Leviant }
41028d8a49fSEugene Leviant 
getAsString() const41128d8a49fSEugene Leviant std::string Attributes::getAsString() const {
41228d8a49fSEugene Leviant   if (Attrs.empty())
41328d8a49fSEugene Leviant     return "";
41428d8a49fSEugene Leviant 
41528d8a49fSEugene Leviant   std::string Ret = "[";
41628d8a49fSEugene Leviant   for (auto &A : Attrs)
41728d8a49fSEugene Leviant     Ret += A + ",";
41828d8a49fSEugene Leviant   Ret.pop_back();
41928d8a49fSEugene Leviant   Ret += "];";
42028d8a49fSEugene Leviant   Ret += Comments;
42128d8a49fSEugene Leviant   return Ret;
42228d8a49fSEugene Leviant }
42328d8a49fSEugene Leviant 
linkageToString(GlobalValue::LinkageTypes LT)42428d8a49fSEugene Leviant static std::string linkageToString(GlobalValue::LinkageTypes LT) {
42528d8a49fSEugene Leviant   switch (LT) {
42628d8a49fSEugene Leviant   case GlobalValue::ExternalLinkage:
42728d8a49fSEugene Leviant     return "extern";
42828d8a49fSEugene Leviant   case GlobalValue::AvailableExternallyLinkage:
42928d8a49fSEugene Leviant     return "av_ext";
43028d8a49fSEugene Leviant   case GlobalValue::LinkOnceAnyLinkage:
43128d8a49fSEugene Leviant     return "linkonce";
43228d8a49fSEugene Leviant   case GlobalValue::LinkOnceODRLinkage:
43328d8a49fSEugene Leviant     return "linkonce_odr";
43428d8a49fSEugene Leviant   case GlobalValue::WeakAnyLinkage:
43528d8a49fSEugene Leviant     return "weak";
43628d8a49fSEugene Leviant   case GlobalValue::WeakODRLinkage:
43728d8a49fSEugene Leviant     return "weak_odr";
43828d8a49fSEugene Leviant   case GlobalValue::AppendingLinkage:
43928d8a49fSEugene Leviant     return "appending";
44028d8a49fSEugene Leviant   case GlobalValue::InternalLinkage:
44128d8a49fSEugene Leviant     return "internal";
44228d8a49fSEugene Leviant   case GlobalValue::PrivateLinkage:
44328d8a49fSEugene Leviant     return "private";
44428d8a49fSEugene Leviant   case GlobalValue::ExternalWeakLinkage:
44528d8a49fSEugene Leviant     return "extern_weak";
44628d8a49fSEugene Leviant   case GlobalValue::CommonLinkage:
44728d8a49fSEugene Leviant     return "common";
44828d8a49fSEugene Leviant   }
44928d8a49fSEugene Leviant 
45028d8a49fSEugene Leviant   return "<unknown>";
45128d8a49fSEugene Leviant }
45228d8a49fSEugene Leviant 
fflagsToString(FunctionSummary::FFlags F)45328d8a49fSEugene Leviant static std::string fflagsToString(FunctionSummary::FFlags F) {
45428d8a49fSEugene Leviant   auto FlagValue = [](unsigned V) { return V ? '1' : '0'; };
45509a704c5SMingming Liu   char FlagRep[] = {FlagValue(F.ReadNone),
45609a704c5SMingming Liu                     FlagValue(F.ReadOnly),
45709a704c5SMingming Liu                     FlagValue(F.NoRecurse),
45809a704c5SMingming Liu                     FlagValue(F.ReturnDoesNotAlias),
45909a704c5SMingming Liu                     FlagValue(F.NoInline),
46009a704c5SMingming Liu                     FlagValue(F.AlwaysInline),
46109a704c5SMingming Liu                     FlagValue(F.NoUnwind),
46209a704c5SMingming Liu                     FlagValue(F.MayThrow),
46309a704c5SMingming Liu                     FlagValue(F.HasUnknownCall),
46409a704c5SMingming Liu                     FlagValue(F.MustBeUnreachable),
46509a704c5SMingming Liu                     0};
46628d8a49fSEugene Leviant 
46728d8a49fSEugene Leviant   return FlagRep;
46828d8a49fSEugene Leviant }
46928d8a49fSEugene Leviant 
47028d8a49fSEugene Leviant // Get string representation of function instruction count and flags.
getSummaryAttributes(GlobalValueSummary * GVS)47128d8a49fSEugene Leviant static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
47228d8a49fSEugene Leviant   auto *FS = dyn_cast_or_null<FunctionSummary>(GVS);
47328d8a49fSEugene Leviant   if (!FS)
47428d8a49fSEugene Leviant     return "";
47528d8a49fSEugene Leviant 
47628d8a49fSEugene Leviant   return std::string("inst: ") + std::to_string(FS->instCount()) +
47728d8a49fSEugene Leviant          ", ffl: " + fflagsToString(FS->fflags());
47828d8a49fSEugene Leviant }
47928d8a49fSEugene Leviant 
getNodeVisualName(GlobalValue::GUID Id)4807a92bc3eSTeresa Johnson static std::string getNodeVisualName(GlobalValue::GUID Id) {
4817a92bc3eSTeresa Johnson   return std::string("@") + std::to_string(Id);
4827a92bc3eSTeresa Johnson }
4837a92bc3eSTeresa Johnson 
getNodeVisualName(const ValueInfo & VI)48428d8a49fSEugene Leviant static std::string getNodeVisualName(const ValueInfo &VI) {
4857a92bc3eSTeresa Johnson   return VI.name().empty() ? getNodeVisualName(VI.getGUID()) : VI.name().str();
48628d8a49fSEugene Leviant }
48728d8a49fSEugene Leviant 
getNodeLabel(const ValueInfo & VI,GlobalValueSummary * GVS)48828d8a49fSEugene Leviant static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS) {
48928d8a49fSEugene Leviant   if (isa<AliasSummary>(GVS))
49028d8a49fSEugene Leviant     return getNodeVisualName(VI);
49128d8a49fSEugene Leviant 
49228d8a49fSEugene Leviant   std::string Attrs = getSummaryAttributes(GVS);
49328d8a49fSEugene Leviant   std::string Label =
49428d8a49fSEugene Leviant       getNodeVisualName(VI) + "|" + linkageToString(GVS->linkage());
49528d8a49fSEugene Leviant   if (!Attrs.empty())
49628d8a49fSEugene Leviant     Label += std::string(" (") + Attrs + ")";
49728d8a49fSEugene Leviant   Label += "}";
49828d8a49fSEugene Leviant 
49928d8a49fSEugene Leviant   return Label;
50028d8a49fSEugene Leviant }
50128d8a49fSEugene Leviant 
50228d8a49fSEugene Leviant // Write definition of external node, which doesn't have any
50328d8a49fSEugene Leviant // specific module associated with it. Typically this is function
50428d8a49fSEugene Leviant // or variable defined in native object or library.
defineExternalNode(raw_ostream & OS,const char * Pfx,const ValueInfo & VI,GlobalValue::GUID Id)50528d8a49fSEugene Leviant static void defineExternalNode(raw_ostream &OS, const char *Pfx,
5067a92bc3eSTeresa Johnson                                const ValueInfo &VI, GlobalValue::GUID Id) {
5077a92bc3eSTeresa Johnson   auto StrId = std::to_string(Id);
5087a92bc3eSTeresa Johnson   OS << "  " << StrId << " [label=\"";
5097a92bc3eSTeresa Johnson 
5107a92bc3eSTeresa Johnson   if (VI) {
5117a92bc3eSTeresa Johnson     OS << getNodeVisualName(VI);
5127a92bc3eSTeresa Johnson   } else {
5137a92bc3eSTeresa Johnson     OS << getNodeVisualName(Id);
5147a92bc3eSTeresa Johnson   }
5157a92bc3eSTeresa Johnson   OS << "\"]; // defined externally\n";
51628d8a49fSEugene Leviant }
51728d8a49fSEugene Leviant 
hasReadOnlyFlag(const GlobalValueSummary * S)518bf46e741SEugene Leviant static bool hasReadOnlyFlag(const GlobalValueSummary *S) {
519bf46e741SEugene Leviant   if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
5203aef3528SEugene Leviant     return GVS->maybeReadOnly();
5213aef3528SEugene Leviant   return false;
5223aef3528SEugene Leviant }
5233aef3528SEugene Leviant 
hasWriteOnlyFlag(const GlobalValueSummary * S)5243aef3528SEugene Leviant static bool hasWriteOnlyFlag(const GlobalValueSummary *S) {
5253aef3528SEugene Leviant   if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
5263aef3528SEugene Leviant     return GVS->maybeWriteOnly();
527bf46e741SEugene Leviant   return false;
528bf46e741SEugene Leviant }
529bf46e741SEugene Leviant 
hasConstantFlag(const GlobalValueSummary * S)53010cadee5Sevgeny static bool hasConstantFlag(const GlobalValueSummary *S) {
53110cadee5Sevgeny   if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
53210cadee5Sevgeny     return GVS->isConstant();
53310cadee5Sevgeny   return false;
53410cadee5Sevgeny }
53510cadee5Sevgeny 
exportToDot(raw_ostream & OS,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols) const536ad364956Sevgeny void ModuleSummaryIndex::exportToDot(
537ad364956Sevgeny     raw_ostream &OS,
538ad364956Sevgeny     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const {
53928d8a49fSEugene Leviant   std::vector<Edge> CrossModuleEdges;
54028d8a49fSEugene Leviant   DenseMap<GlobalValue::GUID, std::vector<uint64_t>> NodeMap;
54124b3d258SEugene Leviant   using GVSOrderedMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>;
54224b3d258SEugene Leviant   std::map<StringRef, GVSOrderedMapTy> ModuleToDefinedGVS;
54328d8a49fSEugene Leviant   collectDefinedGVSummariesPerModule(ModuleToDefinedGVS);
54428d8a49fSEugene Leviant 
54528d8a49fSEugene Leviant   // Get node identifier in form MXXX_<GUID>. The MXXX prefix is required,
54628d8a49fSEugene Leviant   // because we may have multiple linkonce functions summaries.
54728d8a49fSEugene Leviant   auto NodeId = [](uint64_t ModId, GlobalValue::GUID Id) {
54828d8a49fSEugene Leviant     return ModId == (uint64_t)-1 ? std::to_string(Id)
54928d8a49fSEugene Leviant                                  : std::string("M") + std::to_string(ModId) +
55028d8a49fSEugene Leviant                                        "_" + std::to_string(Id);
55128d8a49fSEugene Leviant   };
55228d8a49fSEugene Leviant 
5531f54500aSEugene Leviant   auto DrawEdge = [&](const char *Pfx, uint64_t SrcMod, GlobalValue::GUID SrcId,
554bf46e741SEugene Leviant                       uint64_t DstMod, GlobalValue::GUID DstId,
555bf46e741SEugene Leviant                       int TypeOrHotness) {
556bf46e741SEugene Leviant     // 0 - alias
557bf46e741SEugene Leviant     // 1 - reference
558bf46e741SEugene Leviant     // 2 - constant reference
5593aef3528SEugene Leviant     // 3 - writeonly reference
5603aef3528SEugene Leviant     // Other value: (hotness - 4).
5613aef3528SEugene Leviant     TypeOrHotness += 4;
56228d8a49fSEugene Leviant     static const char *EdgeAttrs[] = {
56328d8a49fSEugene Leviant         " [style=dotted]; // alias",
56428d8a49fSEugene Leviant         " [style=dashed]; // ref",
565bf46e741SEugene Leviant         " [style=dashed,color=forestgreen]; // const-ref",
5663aef3528SEugene Leviant         " [style=dashed,color=violetred]; // writeOnly-ref",
56728d8a49fSEugene Leviant         " // call (hotness : Unknown)",
56828d8a49fSEugene Leviant         " [color=blue]; // call (hotness : Cold)",
56928d8a49fSEugene Leviant         " // call (hotness : None)",
57028d8a49fSEugene Leviant         " [color=brown]; // call (hotness : Hot)",
57128d8a49fSEugene Leviant         " [style=bold,color=red]; // call (hotness : Critical)"};
57228d8a49fSEugene Leviant 
57328d8a49fSEugene Leviant     assert(static_cast<size_t>(TypeOrHotness) <
57428d8a49fSEugene Leviant            sizeof(EdgeAttrs) / sizeof(EdgeAttrs[0]));
57528d8a49fSEugene Leviant     OS << Pfx << NodeId(SrcMod, SrcId) << " -> " << NodeId(DstMod, DstId)
57628d8a49fSEugene Leviant        << EdgeAttrs[TypeOrHotness] << "\n";
57728d8a49fSEugene Leviant   };
57828d8a49fSEugene Leviant 
57928d8a49fSEugene Leviant   OS << "digraph Summary {\n";
58028d8a49fSEugene Leviant   for (auto &ModIt : ModuleToDefinedGVS) {
58124b3d258SEugene Leviant     auto ModId = getModuleId(ModIt.first);
58224b3d258SEugene Leviant     OS << "  // Module: " << ModIt.first << "\n";
58328d8a49fSEugene Leviant     OS << "  subgraph cluster_" << std::to_string(ModId) << " {\n";
58428d8a49fSEugene Leviant     OS << "    style = filled;\n";
58528d8a49fSEugene Leviant     OS << "    color = lightgrey;\n";
58624b3d258SEugene Leviant     OS << "    label = \"" << sys::path::filename(ModIt.first) << "\";\n";
58728d8a49fSEugene Leviant     OS << "    node [style=filled,fillcolor=lightblue];\n";
58828d8a49fSEugene Leviant 
58928d8a49fSEugene Leviant     auto &GVSMap = ModIt.second;
59028d8a49fSEugene Leviant     auto Draw = [&](GlobalValue::GUID IdFrom, GlobalValue::GUID IdTo, int Hotness) {
59128d8a49fSEugene Leviant       if (!GVSMap.count(IdTo)) {
59228d8a49fSEugene Leviant         CrossModuleEdges.push_back({ModId, Hotness, IdFrom, IdTo});
59328d8a49fSEugene Leviant         return;
59428d8a49fSEugene Leviant       }
59528d8a49fSEugene Leviant       DrawEdge("    ", ModId, IdFrom, ModId, IdTo, Hotness);
59628d8a49fSEugene Leviant     };
59728d8a49fSEugene Leviant 
59828d8a49fSEugene Leviant     for (auto &SummaryIt : GVSMap) {
59928d8a49fSEugene Leviant       NodeMap[SummaryIt.first].push_back(ModId);
60028d8a49fSEugene Leviant       auto Flags = SummaryIt.second->flags();
60128d8a49fSEugene Leviant       Attributes A;
60228d8a49fSEugene Leviant       if (isa<FunctionSummary>(SummaryIt.second)) {
60328d8a49fSEugene Leviant         A.add("shape", "record", "function");
60428d8a49fSEugene Leviant       } else if (isa<AliasSummary>(SummaryIt.second)) {
60528d8a49fSEugene Leviant         A.add("style", "dotted,filled", "alias");
60628d8a49fSEugene Leviant         A.add("shape", "box");
60728d8a49fSEugene Leviant       } else {
60828d8a49fSEugene Leviant         A.add("shape", "Mrecord", "variable");
609bf46e741SEugene Leviant         if (Flags.Live && hasReadOnlyFlag(SummaryIt.second))
610bf46e741SEugene Leviant           A.addComment("immutable");
6113aef3528SEugene Leviant         if (Flags.Live && hasWriteOnlyFlag(SummaryIt.second))
6123aef3528SEugene Leviant           A.addComment("writeOnly");
61310cadee5Sevgeny         if (Flags.Live && hasConstantFlag(SummaryIt.second))
61410cadee5Sevgeny           A.addComment("constant");
61528d8a49fSEugene Leviant       }
61654fb3ca9SFangrui Song       if (Flags.Visibility)
61754fb3ca9SFangrui Song         A.addComment("visibility");
61837b80122STeresa Johnson       if (Flags.DSOLocal)
61937b80122STeresa Johnson         A.addComment("dsoLocal");
62037b80122STeresa Johnson       if (Flags.CanAutoHide)
62137b80122STeresa Johnson         A.addComment("canAutoHide");
622ad364956Sevgeny       if (GUIDPreservedSymbols.count(SummaryIt.first))
623ad364956Sevgeny         A.addComment("preserved");
62428d8a49fSEugene Leviant 
62528d8a49fSEugene Leviant       auto VI = getValueInfo(SummaryIt.first);
62628d8a49fSEugene Leviant       A.add("label", getNodeLabel(VI, SummaryIt.second));
62728d8a49fSEugene Leviant       if (!Flags.Live)
62828d8a49fSEugene Leviant         A.add("fillcolor", "red", "dead");
62928d8a49fSEugene Leviant       else if (Flags.NotEligibleToImport)
63028d8a49fSEugene Leviant         A.add("fillcolor", "yellow", "not eligible to import");
63128d8a49fSEugene Leviant 
63228d8a49fSEugene Leviant       OS << "    " << NodeId(ModId, SummaryIt.first) << " " << A.getAsString()
63328d8a49fSEugene Leviant          << "\n";
63428d8a49fSEugene Leviant     }
63528d8a49fSEugene Leviant     OS << "    // Edges:\n";
63628d8a49fSEugene Leviant 
63728d8a49fSEugene Leviant     for (auto &SummaryIt : GVSMap) {
63828d8a49fSEugene Leviant       auto *GVS = SummaryIt.second;
63928d8a49fSEugene Leviant       for (auto &R : GVS->refs())
6403aef3528SEugene Leviant         Draw(SummaryIt.first, R.getGUID(),
6413aef3528SEugene Leviant              R.isWriteOnly() ? -1 : (R.isReadOnly() ? -2 : -3));
64228d8a49fSEugene Leviant 
64328d8a49fSEugene Leviant       if (auto *AS = dyn_cast_or_null<AliasSummary>(SummaryIt.second)) {
6443aef3528SEugene Leviant         Draw(SummaryIt.first, AS->getAliaseeGUID(), -4);
64528d8a49fSEugene Leviant         continue;
64628d8a49fSEugene Leviant       }
64728d8a49fSEugene Leviant 
64828d8a49fSEugene Leviant       if (auto *FS = dyn_cast_or_null<FunctionSummary>(SummaryIt.second))
64928d8a49fSEugene Leviant         for (auto &CGEdge : FS->calls())
65028d8a49fSEugene Leviant           Draw(SummaryIt.first, CGEdge.first.getGUID(),
65128d8a49fSEugene Leviant                static_cast<int>(CGEdge.second.Hotness));
65228d8a49fSEugene Leviant     }
65328d8a49fSEugene Leviant     OS << "  }\n";
65428d8a49fSEugene Leviant   }
65528d8a49fSEugene Leviant 
65628d8a49fSEugene Leviant   OS << "  // Cross-module edges:\n";
65728d8a49fSEugene Leviant   for (auto &E : CrossModuleEdges) {
65828d8a49fSEugene Leviant     auto &ModList = NodeMap[E.Dst];
65928d8a49fSEugene Leviant     if (ModList.empty()) {
6607a92bc3eSTeresa Johnson       defineExternalNode(OS, "  ", getValueInfo(E.Dst), E.Dst);
66128d8a49fSEugene Leviant       // Add fake module to the list to draw an edge to an external node
66228d8a49fSEugene Leviant       // in the loop below.
66328d8a49fSEugene Leviant       ModList.push_back(-1);
66428d8a49fSEugene Leviant     }
66528d8a49fSEugene Leviant     for (auto DstMod : ModList)
66628d8a49fSEugene Leviant       // The edge representing call or ref is drawn to every module where target
66728d8a49fSEugene Leviant       // symbol is defined. When target is a linkonce symbol there can be
66828d8a49fSEugene Leviant       // multiple edges representing a single call or ref, both intra-module and
66928d8a49fSEugene Leviant       // cross-module. As we've already drawn all intra-module edges before we
67028d8a49fSEugene Leviant       // skip it here.
67128d8a49fSEugene Leviant       if (DstMod != E.SrcMod)
67228d8a49fSEugene Leviant         DrawEdge("  ", E.SrcMod, E.Src, DstMod, E.Dst, E.Hotness);
67328d8a49fSEugene Leviant   }
67428d8a49fSEugene Leviant 
67528d8a49fSEugene Leviant   OS << "}";
67628d8a49fSEugene Leviant }
677