17d523365SDimitry Andric //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
27d523365SDimitry Andric //
37d523365SDimitry Andric //                     The LLVM Compiler Infrastructure
47d523365SDimitry Andric //
57d523365SDimitry Andric // This file is distributed under the University of Illinois Open Source
67d523365SDimitry Andric // License. See LICENSE.TXT for details.
77d523365SDimitry Andric //
87d523365SDimitry Andric //===----------------------------------------------------------------------===//
97d523365SDimitry Andric //
107d523365SDimitry Andric // This file implements Function import based on summaries.
117d523365SDimitry Andric //
127d523365SDimitry Andric //===----------------------------------------------------------------------===//
137d523365SDimitry Andric 
147d523365SDimitry Andric #include "llvm/Transforms/IPO/FunctionImport.h"
152cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
162cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
172cab237bSDimitry Andric #include "llvm/ADT/SetVector.h"
183ca95b02SDimitry Andric #include "llvm/ADT/SmallVector.h"
193ca95b02SDimitry Andric #include "llvm/ADT/Statistic.h"
202cab237bSDimitry Andric #include "llvm/ADT/StringMap.h"
212cab237bSDimitry Andric #include "llvm/ADT/StringRef.h"
224ba319b5SDimitry Andric #include "llvm/ADT/StringSet.h"
23f37b6182SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
247d523365SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
252cab237bSDimitry Andric #include "llvm/IR/Constants.h"
262cab237bSDimitry Andric #include "llvm/IR/Function.h"
272cab237bSDimitry Andric #include "llvm/IR/GlobalAlias.h"
282cab237bSDimitry Andric #include "llvm/IR/GlobalObject.h"
292cab237bSDimitry Andric #include "llvm/IR/GlobalValue.h"
302cab237bSDimitry Andric #include "llvm/IR/GlobalVariable.h"
312cab237bSDimitry Andric #include "llvm/IR/Metadata.h"
327d523365SDimitry Andric #include "llvm/IR/Module.h"
332cab237bSDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
347d523365SDimitry Andric #include "llvm/IRReader/IRReader.h"
352cab237bSDimitry Andric #include "llvm/Linker/IRMover.h"
362cab237bSDimitry Andric #include "llvm/Object/ModuleSymbolTable.h"
372cab237bSDimitry Andric #include "llvm/Object/SymbolicFile.h"
382cab237bSDimitry Andric #include "llvm/Pass.h"
392cab237bSDimitry Andric #include "llvm/Support/Casting.h"
407d523365SDimitry Andric #include "llvm/Support/CommandLine.h"
417d523365SDimitry Andric #include "llvm/Support/Debug.h"
422cab237bSDimitry Andric #include "llvm/Support/Error.h"
432cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
442cab237bSDimitry Andric #include "llvm/Support/FileSystem.h"
457d523365SDimitry Andric #include "llvm/Support/SourceMgr.h"
462cab237bSDimitry Andric #include "llvm/Support/raw_ostream.h"
473ca95b02SDimitry Andric #include "llvm/Transforms/IPO/Internalize.h"
482cab237bSDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
493ca95b02SDimitry Andric #include "llvm/Transforms/Utils/FunctionImportUtils.h"
502cab237bSDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
512cab237bSDimitry Andric #include <cassert>
522cab237bSDimitry Andric #include <memory>
532cab237bSDimitry Andric #include <set>
542cab237bSDimitry Andric #include <string>
552cab237bSDimitry Andric #include <system_error>
562cab237bSDimitry Andric #include <tuple>
572cab237bSDimitry Andric #include <utility>
587d523365SDimitry Andric 
597d523365SDimitry Andric using namespace llvm;
607d523365SDimitry Andric 
612cab237bSDimitry Andric #define DEBUG_TYPE "function-import"
622cab237bSDimitry Andric 
63*b5893f02SDimitry Andric STATISTIC(NumImportedFunctionsThinLink,
64*b5893f02SDimitry Andric           "Number of functions thin link decided to import");
65*b5893f02SDimitry Andric STATISTIC(NumImportedHotFunctionsThinLink,
66*b5893f02SDimitry Andric           "Number of hot functions thin link decided to import");
67*b5893f02SDimitry Andric STATISTIC(NumImportedCriticalFunctionsThinLink,
68*b5893f02SDimitry Andric           "Number of critical functions thin link decided to import");
69*b5893f02SDimitry Andric STATISTIC(NumImportedGlobalVarsThinLink,
70*b5893f02SDimitry Andric           "Number of global variables thin link decided to import");
71*b5893f02SDimitry Andric STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
72*b5893f02SDimitry Andric STATISTIC(NumImportedGlobalVars,
73*b5893f02SDimitry Andric           "Number of global variables imported in backend");
7495ec533aSDimitry Andric STATISTIC(NumImportedModules, "Number of modules imported from");
7595ec533aSDimitry Andric STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
7695ec533aSDimitry Andric STATISTIC(NumLiveSymbols, "Number of live symbols in index");
777d523365SDimitry Andric 
787d523365SDimitry Andric /// Limit on instruction count of imported functions.
797d523365SDimitry Andric static cl::opt<unsigned> ImportInstrLimit(
807d523365SDimitry Andric     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
817d523365SDimitry Andric     cl::desc("Only import functions with less than N instructions"));
827d523365SDimitry Andric 
834ba319b5SDimitry Andric static cl::opt<int> ImportCutoff(
844ba319b5SDimitry Andric     "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
854ba319b5SDimitry Andric     cl::desc("Only import first N functions if N>=0 (default -1)"));
864ba319b5SDimitry Andric 
873ca95b02SDimitry Andric static cl::opt<float>
883ca95b02SDimitry Andric     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
893ca95b02SDimitry Andric                       cl::Hidden, cl::value_desc("x"),
903ca95b02SDimitry Andric                       cl::desc("As we import functions, multiply the "
913ca95b02SDimitry Andric                                "`import-instr-limit` threshold by this factor "
923ca95b02SDimitry Andric                                "before processing newly imported functions"));
933ca95b02SDimitry Andric 
94d88c1a5aSDimitry Andric static cl::opt<float> ImportHotInstrFactor(
95d88c1a5aSDimitry Andric     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
96d88c1a5aSDimitry Andric     cl::value_desc("x"),
97d88c1a5aSDimitry Andric     cl::desc("As we import functions called from hot callsite, multiply the "
98d88c1a5aSDimitry Andric              "`import-instr-limit` threshold by this factor "
99d88c1a5aSDimitry Andric              "before processing newly imported functions"));
100d88c1a5aSDimitry Andric 
101d88c1a5aSDimitry Andric static cl::opt<float> ImportHotMultiplier(
1022cab237bSDimitry Andric     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
103d88c1a5aSDimitry Andric     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
104d88c1a5aSDimitry Andric 
105c4394386SDimitry Andric static cl::opt<float> ImportCriticalMultiplier(
106c4394386SDimitry Andric     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
107c4394386SDimitry Andric     cl::value_desc("x"),
108c4394386SDimitry Andric     cl::desc(
109c4394386SDimitry Andric         "Multiply the `import-instr-limit` threshold for critical callsites"));
110c4394386SDimitry Andric 
111d88c1a5aSDimitry Andric // FIXME: This multiplier was not really tuned up.
112d88c1a5aSDimitry Andric static cl::opt<float> ImportColdMultiplier(
113d88c1a5aSDimitry Andric     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
114d88c1a5aSDimitry Andric     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
115d88c1a5aSDimitry Andric 
1163ca95b02SDimitry Andric static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
1173ca95b02SDimitry Andric                                   cl::desc("Print imported functions"));
1183ca95b02SDimitry Andric 
119*b5893f02SDimitry Andric static cl::opt<bool> PrintImportFailures(
120*b5893f02SDimitry Andric     "print-import-failures", cl::init(false), cl::Hidden,
121*b5893f02SDimitry Andric     cl::desc("Print information for functions rejected for importing"));
122*b5893f02SDimitry Andric 
12395ec533aSDimitry Andric static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
12495ec533aSDimitry Andric                                  cl::desc("Compute dead symbols"));
12595ec533aSDimitry Andric 
1263ca95b02SDimitry Andric static cl::opt<bool> EnableImportMetadata(
1273ca95b02SDimitry Andric     "enable-import-metadata", cl::init(
1283ca95b02SDimitry Andric #if !defined(NDEBUG)
1293ca95b02SDimitry Andric                                   true /*Enabled with asserts.*/
1303ca95b02SDimitry Andric #else
1313ca95b02SDimitry Andric                                   false
1323ca95b02SDimitry Andric #endif
1333ca95b02SDimitry Andric                                   ),
1343ca95b02SDimitry Andric     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
1353ca95b02SDimitry Andric 
1362cab237bSDimitry Andric /// Summary file to use for function importing when using -function-import from
1372cab237bSDimitry Andric /// the command line.
1382cab237bSDimitry Andric static cl::opt<std::string>
1392cab237bSDimitry Andric     SummaryFile("summary-file",
1402cab237bSDimitry Andric                 cl::desc("The summary file to use for function importing."));
1412cab237bSDimitry Andric 
1422cab237bSDimitry Andric /// Used when testing importing from distributed indexes via opt
1432cab237bSDimitry Andric // -function-import.
1442cab237bSDimitry Andric static cl::opt<bool>
1452cab237bSDimitry Andric     ImportAllIndex("import-all-index",
1462cab237bSDimitry Andric                    cl::desc("Import all external functions in index."));
1472cab237bSDimitry Andric 
1487d523365SDimitry Andric // Load lazily a module from \p FileName in \p Context.
loadFile(const std::string & FileName,LLVMContext & Context)1497d523365SDimitry Andric static std::unique_ptr<Module> loadFile(const std::string &FileName,
1507d523365SDimitry Andric                                         LLVMContext &Context) {
1517d523365SDimitry Andric   SMDiagnostic Err;
1524ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
1533ca95b02SDimitry Andric   // Metadata isn't loaded until functions are imported, to minimize
1543ca95b02SDimitry Andric   // the memory overhead.
155444ed5c5SDimitry Andric   std::unique_ptr<Module> Result =
156444ed5c5SDimitry Andric       getLazyIRFileModule(FileName, Err, Context,
157444ed5c5SDimitry Andric                           /* ShouldLazyLoadMetadata = */ true);
1587d523365SDimitry Andric   if (!Result) {
1597d523365SDimitry Andric     Err.print("function-import", errs());
1603ca95b02SDimitry Andric     report_fatal_error("Abort");
1617d523365SDimitry Andric   }
1627d523365SDimitry Andric 
1637d523365SDimitry Andric   return Result;
1647d523365SDimitry Andric }
1657d523365SDimitry Andric 
1663ca95b02SDimitry Andric /// Given a list of possible callee implementation for a call site, select one
1673ca95b02SDimitry Andric /// that fits the \p Threshold.
1683ca95b02SDimitry Andric ///
1693ca95b02SDimitry Andric /// FIXME: select "best" instead of first that fits. But what is "best"?
1703ca95b02SDimitry Andric /// - The smallest: more likely to be inlined.
1713ca95b02SDimitry Andric /// - The one with the least outgoing edges (already well optimized).
1723ca95b02SDimitry Andric /// - One from a module already being imported from in order to reduce the
1733ca95b02SDimitry Andric ///   number of source modules parsed/linked.
1743ca95b02SDimitry Andric /// - One that has PGO data attached.
1753ca95b02SDimitry Andric /// - [insert you fancy metric here]
1763ca95b02SDimitry Andric static const GlobalValueSummary *
selectCallee(const ModuleSummaryIndex & Index,ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,unsigned Threshold,StringRef CallerModulePath,FunctionImporter::ImportFailureReason & Reason,GlobalValue::GUID GUID)1773ca95b02SDimitry Andric selectCallee(const ModuleSummaryIndex &Index,
1780f5676f4SDimitry Andric              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
179*b5893f02SDimitry Andric              unsigned Threshold, StringRef CallerModulePath,
180*b5893f02SDimitry Andric              FunctionImporter::ImportFailureReason &Reason,
181*b5893f02SDimitry Andric              GlobalValue::GUID GUID) {
182*b5893f02SDimitry Andric   Reason = FunctionImporter::ImportFailureReason::None;
1833ca95b02SDimitry Andric   auto It = llvm::find_if(
1843ca95b02SDimitry Andric       CalleeSummaryList,
1853ca95b02SDimitry Andric       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1863ca95b02SDimitry Andric         auto *GVSummary = SummaryPtr.get();
187*b5893f02SDimitry Andric         if (!Index.isGlobalValueLive(GVSummary)) {
188*b5893f02SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::NotLive;
1894ba319b5SDimitry Andric           return false;
190*b5893f02SDimitry Andric         }
1914ba319b5SDimitry Andric 
1922cab237bSDimitry Andric         // For SamplePGO, in computeImportForFunction the OriginalId
1932cab237bSDimitry Andric         // may have been used to locate the callee summary list (See
1942cab237bSDimitry Andric         // comment there).
1952cab237bSDimitry Andric         // The mapping from OriginalId to GUID may return a GUID
1962cab237bSDimitry Andric         // that corresponds to a static variable. Filter it out here.
1972cab237bSDimitry Andric         // This can happen when
1982cab237bSDimitry Andric         // 1) There is a call to a library function which is not defined
1992cab237bSDimitry Andric         // in the index.
2002cab237bSDimitry Andric         // 2) There is a static variable with the  OriginalGUID identical
2012cab237bSDimitry Andric         // to the GUID of the library function in 1);
2022cab237bSDimitry Andric         // When this happens, the logic for SamplePGO kicks in and
2032cab237bSDimitry Andric         // the static variable in 2) will be found, which needs to be
2042cab237bSDimitry Andric         // filtered out.
205*b5893f02SDimitry Andric         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) {
206*b5893f02SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::GlobalVar;
2072cab237bSDimitry Andric           return false;
208*b5893f02SDimitry Andric         }
209*b5893f02SDimitry Andric         if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
210*b5893f02SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
2113ca95b02SDimitry Andric           // There is no point in importing these, we can't inline them
2123ca95b02SDimitry Andric           return false;
213*b5893f02SDimitry Andric         }
2143ca95b02SDimitry Andric 
2152cab237bSDimitry Andric         auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
2163ca95b02SDimitry Andric 
2177a7e6055SDimitry Andric         // If this is a local function, make sure we import the copy
2187a7e6055SDimitry Andric         // in the caller's module. The only time a local function can
2197a7e6055SDimitry Andric         // share an entry in the index is if there is a local with the same name
2207a7e6055SDimitry Andric         // in another module that had the same source file name (in a different
2217a7e6055SDimitry Andric         // directory), where each was compiled in their own directory so there
2227a7e6055SDimitry Andric         // was not distinguishing path.
2237a7e6055SDimitry Andric         // However, do the import from another module if there is only one
2247a7e6055SDimitry Andric         // entry in the list - in that case this must be a reference due
2257a7e6055SDimitry Andric         // to indirect call profile data, since a function pointer can point to
2267a7e6055SDimitry Andric         // a local in another module.
2277a7e6055SDimitry Andric         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
2287a7e6055SDimitry Andric             CalleeSummaryList.size() > 1 &&
229*b5893f02SDimitry Andric             Summary->modulePath() != CallerModulePath) {
230*b5893f02SDimitry Andric           Reason =
231*b5893f02SDimitry Andric               FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
2327a7e6055SDimitry Andric           return false;
233*b5893f02SDimitry Andric         }
2347a7e6055SDimitry Andric 
235*b5893f02SDimitry Andric         if (Summary->instCount() > Threshold) {
236*b5893f02SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::TooLarge;
2373ca95b02SDimitry Andric           return false;
238*b5893f02SDimitry Andric         }
2393ca95b02SDimitry Andric 
240*b5893f02SDimitry Andric         // Skip if it isn't legal to import (e.g. may reference unpromotable
241*b5893f02SDimitry Andric         // locals).
242*b5893f02SDimitry Andric         if (Summary->notEligibleToImport()) {
243*b5893f02SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::NotEligible;
2443ca95b02SDimitry Andric           return false;
245*b5893f02SDimitry Andric         }
246*b5893f02SDimitry Andric 
247*b5893f02SDimitry Andric         // Don't bother importing if we can't inline it anyway.
248*b5893f02SDimitry Andric         if (Summary->fflags().NoInline) {
249*b5893f02SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::NoInline;
250*b5893f02SDimitry Andric           return false;
251*b5893f02SDimitry Andric         }
2523ca95b02SDimitry Andric 
2533ca95b02SDimitry Andric         return true;
2543ca95b02SDimitry Andric       });
2553ca95b02SDimitry Andric   if (It == CalleeSummaryList.end())
2563ca95b02SDimitry Andric     return nullptr;
2573ca95b02SDimitry Andric 
2583ca95b02SDimitry Andric   return cast<GlobalValueSummary>(It->get());
2593ca95b02SDimitry Andric }
2603ca95b02SDimitry Andric 
2612cab237bSDimitry Andric namespace {
2622cab237bSDimitry Andric 
263d88c1a5aSDimitry Andric using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
264d88c1a5aSDimitry Andric                             GlobalValue::GUID>;
2653ca95b02SDimitry Andric 
2662cab237bSDimitry Andric } // anonymous namespace
2672cab237bSDimitry Andric 
2682cab237bSDimitry Andric static ValueInfo
updateValueInfoForIndirectCalls(const ModuleSummaryIndex & Index,ValueInfo VI)2692cab237bSDimitry Andric updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
2702cab237bSDimitry Andric   if (!VI.getSummaryList().empty())
2712cab237bSDimitry Andric     return VI;
2722cab237bSDimitry Andric   // For SamplePGO, the indirect call targets for local functions will
2732cab237bSDimitry Andric   // have its original name annotated in profile. We try to find the
2742cab237bSDimitry Andric   // corresponding PGOFuncName as the GUID.
2752cab237bSDimitry Andric   // FIXME: Consider updating the edges in the graph after building
2762cab237bSDimitry Andric   // it, rather than needing to perform this mapping on each walk.
2772cab237bSDimitry Andric   auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
2782cab237bSDimitry Andric   if (GUID == 0)
2794ba319b5SDimitry Andric     return ValueInfo();
2802cab237bSDimitry Andric   return Index.getValueInfo(GUID);
2812cab237bSDimitry Andric }
2822cab237bSDimitry Andric 
computeImportForReferencedGlobals(const FunctionSummary & Summary,const GVSummaryMapTy & DefinedGVSummaries,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists)2834ba319b5SDimitry Andric static void computeImportForReferencedGlobals(
2844ba319b5SDimitry Andric     const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries,
2854ba319b5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList,
2864ba319b5SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
2874ba319b5SDimitry Andric   for (auto &VI : Summary.refs()) {
2884ba319b5SDimitry Andric     if (DefinedGVSummaries.count(VI.getGUID())) {
2894ba319b5SDimitry Andric       LLVM_DEBUG(
2904ba319b5SDimitry Andric           dbgs() << "Ref ignored! Target already in destination module.\n");
2914ba319b5SDimitry Andric       continue;
2924ba319b5SDimitry Andric     }
2934ba319b5SDimitry Andric 
2944ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
2954ba319b5SDimitry Andric 
296*b5893f02SDimitry Andric     // If this is a local variable, make sure we import the copy
297*b5893f02SDimitry Andric     // in the caller's module. The only time a local variable can
298*b5893f02SDimitry Andric     // share an entry in the index is if there is a local with the same name
299*b5893f02SDimitry Andric     // in another module that had the same source file name (in a different
300*b5893f02SDimitry Andric     // directory), where each was compiled in their own directory so there
301*b5893f02SDimitry Andric     // was not distinguishing path.
302*b5893f02SDimitry Andric     auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
303*b5893f02SDimitry Andric       return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
304*b5893f02SDimitry Andric              RefSummary->modulePath() != Summary.modulePath();
305*b5893f02SDimitry Andric     };
306*b5893f02SDimitry Andric 
3074ba319b5SDimitry Andric     for (auto &RefSummary : VI.getSummaryList())
308*b5893f02SDimitry Andric       if (isa<GlobalVarSummary>(RefSummary.get()) &&
309*b5893f02SDimitry Andric           canImportGlobalVar(RefSummary.get()) &&
310*b5893f02SDimitry Andric           !LocalNotInModule(RefSummary.get())) {
311*b5893f02SDimitry Andric         auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
312*b5893f02SDimitry Andric         // Only update stat if we haven't already imported this variable.
313*b5893f02SDimitry Andric         if (ILI.second)
314*b5893f02SDimitry Andric           NumImportedGlobalVarsThinLink++;
3154ba319b5SDimitry Andric         if (ExportLists)
3164ba319b5SDimitry Andric           (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
3174ba319b5SDimitry Andric         break;
3184ba319b5SDimitry Andric       }
3194ba319b5SDimitry Andric   }
3204ba319b5SDimitry Andric }
3214ba319b5SDimitry Andric 
322*b5893f02SDimitry Andric static const char *
getFailureName(FunctionImporter::ImportFailureReason Reason)323*b5893f02SDimitry Andric getFailureName(FunctionImporter::ImportFailureReason Reason) {
324*b5893f02SDimitry Andric   switch (Reason) {
325*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::None:
326*b5893f02SDimitry Andric     return "None";
327*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::GlobalVar:
328*b5893f02SDimitry Andric     return "GlobalVar";
329*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::NotLive:
330*b5893f02SDimitry Andric     return "NotLive";
331*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::TooLarge:
332*b5893f02SDimitry Andric     return "TooLarge";
333*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::InterposableLinkage:
334*b5893f02SDimitry Andric     return "InterposableLinkage";
335*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
336*b5893f02SDimitry Andric     return "LocalLinkageNotInModule";
337*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::NotEligible:
338*b5893f02SDimitry Andric     return "NotEligible";
339*b5893f02SDimitry Andric   case FunctionImporter::ImportFailureReason::NoInline:
340*b5893f02SDimitry Andric     return "NoInline";
341*b5893f02SDimitry Andric   }
342*b5893f02SDimitry Andric   llvm_unreachable("invalid reason");
343*b5893f02SDimitry Andric }
344*b5893f02SDimitry Andric 
3453ca95b02SDimitry Andric /// Compute the list of functions to import for a given caller. Mark these
3463ca95b02SDimitry Andric /// imported functions and the symbols they reference in their source module as
3473ca95b02SDimitry Andric /// exported from their source module.
computeImportForFunction(const FunctionSummary & Summary,const ModuleSummaryIndex & Index,const unsigned Threshold,const GVSummaryMapTy & DefinedGVSummaries,SmallVectorImpl<EdgeInfo> & Worklist,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists,FunctionImporter::ImportThresholdsTy & ImportThresholds)3483ca95b02SDimitry Andric static void computeImportForFunction(
3493ca95b02SDimitry Andric     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
350d88c1a5aSDimitry Andric     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
3513ca95b02SDimitry Andric     SmallVectorImpl<EdgeInfo> &Worklist,
352d88c1a5aSDimitry Andric     FunctionImporter::ImportMapTy &ImportList,
3534ba319b5SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> *ExportLists,
3544ba319b5SDimitry Andric     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
3554ba319b5SDimitry Andric   computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
3564ba319b5SDimitry Andric                                     ExportLists);
3574ba319b5SDimitry Andric   static int ImportCount = 0;
3583ca95b02SDimitry Andric   for (auto &Edge : Summary.calls()) {
3590f5676f4SDimitry Andric     ValueInfo VI = Edge.first;
3604ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
3610f5676f4SDimitry Andric                       << "\n");
3623ca95b02SDimitry Andric 
3634ba319b5SDimitry Andric     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
3644ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
3654ba319b5SDimitry Andric                         << " reached.\n");
3664ba319b5SDimitry Andric       continue;
3674ba319b5SDimitry Andric     }
3684ba319b5SDimitry Andric 
3692cab237bSDimitry Andric     VI = updateValueInfoForIndirectCalls(Index, VI);
3700f5676f4SDimitry Andric     if (!VI)
3710f5676f4SDimitry Andric       continue;
3727a7e6055SDimitry Andric 
3730f5676f4SDimitry Andric     if (DefinedGVSummaries.count(VI.getGUID())) {
3744ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
3753ca95b02SDimitry Andric       continue;
3767d523365SDimitry Andric     }
3773ca95b02SDimitry Andric 
378d88c1a5aSDimitry Andric     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
379d88c1a5aSDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Hot)
380d88c1a5aSDimitry Andric         return ImportHotMultiplier;
381d88c1a5aSDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Cold)
382d88c1a5aSDimitry Andric         return ImportColdMultiplier;
383c4394386SDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Critical)
384c4394386SDimitry Andric         return ImportCriticalMultiplier;
385d88c1a5aSDimitry Andric       return 1.0;
386d88c1a5aSDimitry Andric     };
387d88c1a5aSDimitry Andric 
388d88c1a5aSDimitry Andric     const auto NewThreshold =
3894ba319b5SDimitry Andric         Threshold * GetBonusMultiplier(Edge.second.getHotness());
390d88c1a5aSDimitry Andric 
391*b5893f02SDimitry Andric     auto IT = ImportThresholds.insert(std::make_pair(
392*b5893f02SDimitry Andric         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
3934ba319b5SDimitry Andric     bool PreviouslyVisited = !IT.second;
394*b5893f02SDimitry Andric     auto &ProcessedThreshold = std::get<0>(IT.first->second);
395*b5893f02SDimitry Andric     auto &CalleeSummary = std::get<1>(IT.first->second);
396*b5893f02SDimitry Andric     auto &FailureInfo = std::get<2>(IT.first->second);
397*b5893f02SDimitry Andric 
398*b5893f02SDimitry Andric     bool IsHotCallsite =
399*b5893f02SDimitry Andric         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
400*b5893f02SDimitry Andric     bool IsCriticalCallsite =
401*b5893f02SDimitry Andric         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
4024ba319b5SDimitry Andric 
4034ba319b5SDimitry Andric     const FunctionSummary *ResolvedCalleeSummary = nullptr;
4044ba319b5SDimitry Andric     if (CalleeSummary) {
4054ba319b5SDimitry Andric       assert(PreviouslyVisited);
4064ba319b5SDimitry Andric       // Since the traversal of the call graph is DFS, we can revisit a function
4074ba319b5SDimitry Andric       // a second time with a higher threshold. In this case, it is added back
4084ba319b5SDimitry Andric       // to the worklist with the new threshold (so that its own callee chains
4094ba319b5SDimitry Andric       // can be considered with the higher threshold).
4104ba319b5SDimitry Andric       if (NewThreshold <= ProcessedThreshold) {
4114ba319b5SDimitry Andric         LLVM_DEBUG(
4124ba319b5SDimitry Andric             dbgs() << "ignored! Target was already imported with Threshold "
4134ba319b5SDimitry Andric                    << ProcessedThreshold << "\n");
4144ba319b5SDimitry Andric         continue;
4154ba319b5SDimitry Andric       }
4164ba319b5SDimitry Andric       // Update with new larger threshold.
4174ba319b5SDimitry Andric       ProcessedThreshold = NewThreshold;
4184ba319b5SDimitry Andric       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
4194ba319b5SDimitry Andric     } else {
4204ba319b5SDimitry Andric       // If we already rejected importing a callee at the same or higher
4214ba319b5SDimitry Andric       // threshold, don't waste time calling selectCallee.
4224ba319b5SDimitry Andric       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
4234ba319b5SDimitry Andric         LLVM_DEBUG(
4244ba319b5SDimitry Andric             dbgs() << "ignored! Target was already rejected with Threshold "
4254ba319b5SDimitry Andric             << ProcessedThreshold << "\n");
426*b5893f02SDimitry Andric         if (PrintImportFailures) {
427*b5893f02SDimitry Andric           assert(FailureInfo &&
428*b5893f02SDimitry Andric                  "Expected FailureInfo for previously rejected candidate");
429*b5893f02SDimitry Andric           FailureInfo->Attempts++;
430*b5893f02SDimitry Andric         }
4314ba319b5SDimitry Andric         continue;
4324ba319b5SDimitry Andric       }
4334ba319b5SDimitry Andric 
434*b5893f02SDimitry Andric       FunctionImporter::ImportFailureReason Reason;
4354ba319b5SDimitry Andric       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
436*b5893f02SDimitry Andric                                    Summary.modulePath(), Reason, VI.getGUID());
4373ca95b02SDimitry Andric       if (!CalleeSummary) {
4384ba319b5SDimitry Andric         // Update with new larger threshold if this was a retry (otherwise
439*b5893f02SDimitry Andric         // we would have already inserted with NewThreshold above). Also
440*b5893f02SDimitry Andric         // update failure info if requested.
441*b5893f02SDimitry Andric         if (PreviouslyVisited) {
4424ba319b5SDimitry Andric           ProcessedThreshold = NewThreshold;
443*b5893f02SDimitry Andric           if (PrintImportFailures) {
444*b5893f02SDimitry Andric             assert(FailureInfo &&
445*b5893f02SDimitry Andric                    "Expected FailureInfo for previously rejected candidate");
446*b5893f02SDimitry Andric             FailureInfo->Reason = Reason;
447*b5893f02SDimitry Andric             FailureInfo->Attempts++;
448*b5893f02SDimitry Andric             FailureInfo->MaxHotness =
449*b5893f02SDimitry Andric                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
450*b5893f02SDimitry Andric           }
451*b5893f02SDimitry Andric         } else if (PrintImportFailures) {
452*b5893f02SDimitry Andric           assert(!FailureInfo &&
453*b5893f02SDimitry Andric                  "Expected no FailureInfo for newly rejected candidate");
454*b5893f02SDimitry Andric           FailureInfo = llvm::make_unique<FunctionImporter::ImportFailureInfo>(
455*b5893f02SDimitry Andric               VI, Edge.second.getHotness(), Reason, 1);
456*b5893f02SDimitry Andric         }
4574ba319b5SDimitry Andric         LLVM_DEBUG(
4584ba319b5SDimitry Andric             dbgs() << "ignored! No qualifying callee with summary found.\n");
4593ca95b02SDimitry Andric         continue;
4607d523365SDimitry Andric       }
4612cab237bSDimitry Andric 
4622cab237bSDimitry Andric       // "Resolve" the summary
4634ba319b5SDimitry Andric       CalleeSummary = CalleeSummary->getBaseObject();
4644ba319b5SDimitry Andric       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
4653ca95b02SDimitry Andric 
466d88c1a5aSDimitry Andric       assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
4673ca95b02SDimitry Andric              "selectCallee() didn't honor the threshold");
4683ca95b02SDimitry Andric 
4693ca95b02SDimitry Andric       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
4704ba319b5SDimitry Andric       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
4714ba319b5SDimitry Andric       // We previously decided to import this GUID definition if it was already
4724ba319b5SDimitry Andric       // inserted in the set of imports from the exporting module.
4734ba319b5SDimitry Andric       bool PreviouslyImported = !ILI.second;
474*b5893f02SDimitry Andric       if (!PreviouslyImported) {
475*b5893f02SDimitry Andric         NumImportedFunctionsThinLink++;
476*b5893f02SDimitry Andric         if (IsHotCallsite)
477*b5893f02SDimitry Andric           NumImportedHotFunctionsThinLink++;
478*b5893f02SDimitry Andric         if (IsCriticalCallsite)
479*b5893f02SDimitry Andric           NumImportedCriticalFunctionsThinLink++;
480*b5893f02SDimitry Andric       }
4813ca95b02SDimitry Andric 
4823ca95b02SDimitry Andric       // Make exports in the source module.
4833ca95b02SDimitry Andric       if (ExportLists) {
4843ca95b02SDimitry Andric         auto &ExportList = (*ExportLists)[ExportModulePath];
4850f5676f4SDimitry Andric         ExportList.insert(VI.getGUID());
486d88c1a5aSDimitry Andric         if (!PreviouslyImported) {
487d88c1a5aSDimitry Andric           // This is the first time this function was exported from its source
488d88c1a5aSDimitry Andric           // module, so mark all functions and globals it references as exported
4893ca95b02SDimitry Andric           // to the outside if they are defined in the same source module.
490d88c1a5aSDimitry Andric           // For efficiency, we unconditionally add all the referenced GUIDs
491d88c1a5aSDimitry Andric           // to the ExportList for this module, and will prune out any not
492d88c1a5aSDimitry Andric           // defined in the module later in a single pass.
4933ca95b02SDimitry Andric           for (auto &Edge : ResolvedCalleeSummary->calls()) {
4943ca95b02SDimitry Andric             auto CalleeGUID = Edge.first.getGUID();
495d88c1a5aSDimitry Andric             ExportList.insert(CalleeGUID);
4963ca95b02SDimitry Andric           }
4973ca95b02SDimitry Andric           for (auto &Ref : ResolvedCalleeSummary->refs()) {
4983ca95b02SDimitry Andric             auto GUID = Ref.getGUID();
499d88c1a5aSDimitry Andric             ExportList.insert(GUID);
500d88c1a5aSDimitry Andric           }
5017d523365SDimitry Andric         }
5027d523365SDimitry Andric       }
5034ba319b5SDimitry Andric     }
5044ba319b5SDimitry Andric 
5054ba319b5SDimitry Andric     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
5064ba319b5SDimitry Andric       // Adjust the threshold for next level of imported functions.
5074ba319b5SDimitry Andric       // The threshold is different for hot callsites because we can then
5084ba319b5SDimitry Andric       // inline chains of hot calls.
5094ba319b5SDimitry Andric       if (IsHotCallsite)
5104ba319b5SDimitry Andric         return Threshold * ImportHotInstrFactor;
5114ba319b5SDimitry Andric       return Threshold * ImportInstrFactor;
5124ba319b5SDimitry Andric     };
5134ba319b5SDimitry Andric 
5144ba319b5SDimitry Andric     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
5154ba319b5SDimitry Andric 
5164ba319b5SDimitry Andric     ImportCount++;
5177d523365SDimitry Andric 
5183ca95b02SDimitry Andric     // Insert the newly imported function to the worklist.
5190f5676f4SDimitry Andric     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
5203ca95b02SDimitry Andric   }
5213ca95b02SDimitry Andric }
5223ca95b02SDimitry Andric 
5233ca95b02SDimitry Andric /// Given the list of globals defined in a module, compute the list of imports
5243ca95b02SDimitry Andric /// as well as the list of "exports", i.e. the list of symbols referenced from
5253ca95b02SDimitry Andric /// another module (that may require promotion).
ComputeImportForModule(const GVSummaryMapTy & DefinedGVSummaries,const ModuleSummaryIndex & Index,StringRef ModName,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists=nullptr)5263ca95b02SDimitry Andric static void ComputeImportForModule(
5273ca95b02SDimitry Andric     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
528*b5893f02SDimitry Andric     StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
5296d97bb29SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
5303ca95b02SDimitry Andric   // Worklist contains the list of function imported in this module, for which
5313ca95b02SDimitry Andric   // we will analyse the callees and may import further down the callgraph.
5323ca95b02SDimitry Andric   SmallVector<EdgeInfo, 128> Worklist;
5334ba319b5SDimitry Andric   FunctionImporter::ImportThresholdsTy ImportThresholds;
5343ca95b02SDimitry Andric 
5353ca95b02SDimitry Andric   // Populate the worklist with the import for the functions in the current
5363ca95b02SDimitry Andric   // module
5373ca95b02SDimitry Andric   for (auto &GVSummary : DefinedGVSummaries) {
5384ba319b5SDimitry Andric #ifndef NDEBUG
5394ba319b5SDimitry Andric     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
5404ba319b5SDimitry Andric     // so this map look up (and possibly others) can be avoided.
5414ba319b5SDimitry Andric     auto VI = Index.getValueInfo(GVSummary.first);
5424ba319b5SDimitry Andric #endif
5436d97bb29SDimitry Andric     if (!Index.isGlobalValueLive(GVSummary.second)) {
5444ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
54595ec533aSDimitry Andric       continue;
54695ec533aSDimitry Andric     }
5472cab237bSDimitry Andric     auto *FuncSummary =
5482cab237bSDimitry Andric         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
5493ca95b02SDimitry Andric     if (!FuncSummary)
5503ca95b02SDimitry Andric       // Skip import for global variables
5513ca95b02SDimitry Andric       continue;
5524ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
5533ca95b02SDimitry Andric     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
554d88c1a5aSDimitry Andric                              DefinedGVSummaries, Worklist, ImportList,
5554ba319b5SDimitry Andric                              ExportLists, ImportThresholds);
5563ca95b02SDimitry Andric   }
5573ca95b02SDimitry Andric 
558d88c1a5aSDimitry Andric   // Process the newly imported functions and add callees to the worklist.
5597d523365SDimitry Andric   while (!Worklist.empty()) {
5603ca95b02SDimitry Andric     auto FuncInfo = Worklist.pop_back_val();
561d88c1a5aSDimitry Andric     auto *Summary = std::get<0>(FuncInfo);
562d88c1a5aSDimitry Andric     auto Threshold = std::get<1>(FuncInfo);
5633ca95b02SDimitry Andric 
5643ca95b02SDimitry Andric     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
5654ba319b5SDimitry Andric                              Worklist, ImportList, ExportLists,
5664ba319b5SDimitry Andric                              ImportThresholds);
5677d523365SDimitry Andric   }
568*b5893f02SDimitry Andric 
569*b5893f02SDimitry Andric   // Print stats about functions considered but rejected for importing
570*b5893f02SDimitry Andric   // when requested.
571*b5893f02SDimitry Andric   if (PrintImportFailures) {
572*b5893f02SDimitry Andric     dbgs() << "Missed imports into module " << ModName << "\n";
573*b5893f02SDimitry Andric     for (auto &I : ImportThresholds) {
574*b5893f02SDimitry Andric       auto &ProcessedThreshold = std::get<0>(I.second);
575*b5893f02SDimitry Andric       auto &CalleeSummary = std::get<1>(I.second);
576*b5893f02SDimitry Andric       auto &FailureInfo = std::get<2>(I.second);
577*b5893f02SDimitry Andric       if (CalleeSummary)
578*b5893f02SDimitry Andric         continue; // We are going to import.
579*b5893f02SDimitry Andric       assert(FailureInfo);
580*b5893f02SDimitry Andric       FunctionSummary *FS = nullptr;
581*b5893f02SDimitry Andric       if (!FailureInfo->VI.getSummaryList().empty())
582*b5893f02SDimitry Andric         FS = dyn_cast<FunctionSummary>(
583*b5893f02SDimitry Andric             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
584*b5893f02SDimitry Andric       dbgs() << FailureInfo->VI
585*b5893f02SDimitry Andric              << ": Reason = " << getFailureName(FailureInfo->Reason)
586*b5893f02SDimitry Andric              << ", Threshold = " << ProcessedThreshold
587*b5893f02SDimitry Andric              << ", Size = " << (FS ? (int)FS->instCount() : -1)
588*b5893f02SDimitry Andric              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
589*b5893f02SDimitry Andric              << ", Attempts = " << FailureInfo->Attempts << "\n";
590*b5893f02SDimitry Andric     }
591*b5893f02SDimitry Andric   }
5927d523365SDimitry Andric }
5937d523365SDimitry Andric 
5944ba319b5SDimitry Andric #ifndef NDEBUG
isGlobalVarSummary(const ModuleSummaryIndex & Index,GlobalValue::GUID G)5954ba319b5SDimitry Andric static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
5964ba319b5SDimitry Andric                                GlobalValue::GUID G) {
5974ba319b5SDimitry Andric   if (const auto &VI = Index.getValueInfo(G)) {
5984ba319b5SDimitry Andric     auto SL = VI.getSummaryList();
5994ba319b5SDimitry Andric     if (!SL.empty())
6004ba319b5SDimitry Andric       return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
6014ba319b5SDimitry Andric   }
6024ba319b5SDimitry Andric   return false;
6034ba319b5SDimitry Andric }
6044ba319b5SDimitry Andric 
getGUID(GlobalValue::GUID G)6054ba319b5SDimitry Andric static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
6064ba319b5SDimitry Andric 
6074ba319b5SDimitry Andric template <class T>
numGlobalVarSummaries(const ModuleSummaryIndex & Index,T & Cont)6084ba319b5SDimitry Andric static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
6094ba319b5SDimitry Andric                                       T &Cont) {
6104ba319b5SDimitry Andric   unsigned NumGVS = 0;
6114ba319b5SDimitry Andric   for (auto &V : Cont)
6124ba319b5SDimitry Andric     if (isGlobalVarSummary(Index, getGUID(V)))
6134ba319b5SDimitry Andric       ++NumGVS;
6144ba319b5SDimitry Andric   return NumGVS;
6154ba319b5SDimitry Andric }
6164ba319b5SDimitry Andric #endif
6174ba319b5SDimitry Andric 
6183ca95b02SDimitry Andric /// Compute all the import and export for every module using the Index.
ComputeCrossModuleImport(const ModuleSummaryIndex & Index,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,StringMap<FunctionImporter::ImportMapTy> & ImportLists,StringMap<FunctionImporter::ExportSetTy> & ExportLists)6193ca95b02SDimitry Andric void llvm::ComputeCrossModuleImport(
6203ca95b02SDimitry Andric     const ModuleSummaryIndex &Index,
6213ca95b02SDimitry Andric     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
6223ca95b02SDimitry Andric     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
6236d97bb29SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
6243ca95b02SDimitry Andric   // For each module that has function defined, compute the import/export lists.
6253ca95b02SDimitry Andric   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
626d88c1a5aSDimitry Andric     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
6274ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Computing import for Module '"
6283ca95b02SDimitry Andric                       << DefinedGVSummaries.first() << "'\n");
629*b5893f02SDimitry Andric     ComputeImportForModule(DefinedGVSummaries.second, Index,
630*b5893f02SDimitry Andric                            DefinedGVSummaries.first(), ImportList,
6316d97bb29SDimitry Andric                            &ExportLists);
6323ca95b02SDimitry Andric   }
6333ca95b02SDimitry Andric 
634d88c1a5aSDimitry Andric   // When computing imports we added all GUIDs referenced by anything
635d88c1a5aSDimitry Andric   // imported from the module to its ExportList. Now we prune each ExportList
636d88c1a5aSDimitry Andric   // of any not defined in that module. This is more efficient than checking
637d88c1a5aSDimitry Andric   // while computing imports because some of the summary lists may be long
638d88c1a5aSDimitry Andric   // due to linkonce (comdat) copies.
639d88c1a5aSDimitry Andric   for (auto &ELI : ExportLists) {
640d88c1a5aSDimitry Andric     const auto &DefinedGVSummaries =
641d88c1a5aSDimitry Andric         ModuleToDefinedGVSummaries.lookup(ELI.first());
642d88c1a5aSDimitry Andric     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
643d88c1a5aSDimitry Andric       if (!DefinedGVSummaries.count(*EI))
644d88c1a5aSDimitry Andric         EI = ELI.second.erase(EI);
645d88c1a5aSDimitry Andric       else
646d88c1a5aSDimitry Andric         ++EI;
647d88c1a5aSDimitry Andric     }
648d88c1a5aSDimitry Andric   }
649d88c1a5aSDimitry Andric 
6503ca95b02SDimitry Andric #ifndef NDEBUG
6514ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
6523ca95b02SDimitry Andric                     << " modules:\n");
6533ca95b02SDimitry Andric   for (auto &ModuleImports : ImportLists) {
6543ca95b02SDimitry Andric     auto ModName = ModuleImports.first();
6553ca95b02SDimitry Andric     auto &Exports = ExportLists[ModName];
6564ba319b5SDimitry Andric     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
6574ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
6584ba319b5SDimitry Andric                       << Exports.size() - NumGVS << " functions and " << NumGVS
6594ba319b5SDimitry Andric                       << " vars. Imports from " << ModuleImports.second.size()
6603ca95b02SDimitry Andric                       << " modules.\n");
6613ca95b02SDimitry Andric     for (auto &Src : ModuleImports.second) {
6623ca95b02SDimitry Andric       auto SrcModName = Src.first();
6634ba319b5SDimitry Andric       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
6644ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
6654ba319b5SDimitry Andric                         << " functions imported from " << SrcModName << "\n");
6664ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
6674ba319b5SDimitry Andric                         << " global vars imported from " << SrcModName << "\n");
6683ca95b02SDimitry Andric     }
6693ca95b02SDimitry Andric   }
6703ca95b02SDimitry Andric #endif
6713ca95b02SDimitry Andric }
6723ca95b02SDimitry Andric 
6732cab237bSDimitry Andric #ifndef NDEBUG
dumpImportListForModule(const ModuleSummaryIndex & Index,StringRef ModulePath,FunctionImporter::ImportMapTy & ImportList)6744ba319b5SDimitry Andric static void dumpImportListForModule(const ModuleSummaryIndex &Index,
6754ba319b5SDimitry Andric                                     StringRef ModulePath,
6762cab237bSDimitry Andric                                     FunctionImporter::ImportMapTy &ImportList) {
6774ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
6782cab237bSDimitry Andric                     << ImportList.size() << " modules.\n");
6792cab237bSDimitry Andric   for (auto &Src : ImportList) {
6802cab237bSDimitry Andric     auto SrcModName = Src.first();
6814ba319b5SDimitry Andric     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
6824ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
6834ba319b5SDimitry Andric                       << " functions imported from " << SrcModName << "\n");
6844ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
6852cab237bSDimitry Andric                       << SrcModName << "\n");
6862cab237bSDimitry Andric   }
6872cab237bSDimitry Andric }
6882cab237bSDimitry Andric #endif
6892cab237bSDimitry Andric 
6903ca95b02SDimitry Andric /// Compute all the imports for the given module in the Index.
ComputeCrossModuleImportForModule(StringRef ModulePath,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)6913ca95b02SDimitry Andric void llvm::ComputeCrossModuleImportForModule(
6923ca95b02SDimitry Andric     StringRef ModulePath, const ModuleSummaryIndex &Index,
6933ca95b02SDimitry Andric     FunctionImporter::ImportMapTy &ImportList) {
6943ca95b02SDimitry Andric   // Collect the list of functions this module defines.
6953ca95b02SDimitry Andric   // GUID -> Summary
6963ca95b02SDimitry Andric   GVSummaryMapTy FunctionSummaryMap;
6973ca95b02SDimitry Andric   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
6983ca95b02SDimitry Andric 
6993ca95b02SDimitry Andric   // Compute the import list for this module.
7004ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
701*b5893f02SDimitry Andric   ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
7023ca95b02SDimitry Andric 
7033ca95b02SDimitry Andric #ifndef NDEBUG
7044ba319b5SDimitry Andric   dumpImportListForModule(Index, ModulePath, ImportList);
7052cab237bSDimitry Andric #endif
7063ca95b02SDimitry Andric }
7072cab237bSDimitry Andric 
7082cab237bSDimitry Andric // Mark all external summaries in Index for import into the given module.
7092cab237bSDimitry Andric // Used for distributed builds using a distributed index.
ComputeCrossModuleImportForModuleFromIndex(StringRef ModulePath,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)7102cab237bSDimitry Andric void llvm::ComputeCrossModuleImportForModuleFromIndex(
7112cab237bSDimitry Andric     StringRef ModulePath, const ModuleSummaryIndex &Index,
7122cab237bSDimitry Andric     FunctionImporter::ImportMapTy &ImportList) {
7132cab237bSDimitry Andric   for (auto &GlobalList : Index) {
7142cab237bSDimitry Andric     // Ignore entries for undefined references.
7152cab237bSDimitry Andric     if (GlobalList.second.SummaryList.empty())
7162cab237bSDimitry Andric       continue;
7172cab237bSDimitry Andric 
7182cab237bSDimitry Andric     auto GUID = GlobalList.first;
7192cab237bSDimitry Andric     assert(GlobalList.second.SummaryList.size() == 1 &&
7202cab237bSDimitry Andric            "Expected individual combined index to have one summary per GUID");
7212cab237bSDimitry Andric     auto &Summary = GlobalList.second.SummaryList[0];
7222cab237bSDimitry Andric     // Skip the summaries for the importing module. These are included to
7232cab237bSDimitry Andric     // e.g. record required linkage changes.
7242cab237bSDimitry Andric     if (Summary->modulePath() == ModulePath)
7252cab237bSDimitry Andric       continue;
7264ba319b5SDimitry Andric     // Add an entry to provoke importing by thinBackend.
7274ba319b5SDimitry Andric     ImportList[Summary->modulePath()].insert(GUID);
7282cab237bSDimitry Andric   }
7292cab237bSDimitry Andric #ifndef NDEBUG
7304ba319b5SDimitry Andric   dumpImportListForModule(Index, ModulePath, ImportList);
7313ca95b02SDimitry Andric #endif
7323ca95b02SDimitry Andric }
7333ca95b02SDimitry Andric 
computeDeadSymbols(ModuleSummaryIndex & Index,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols,function_ref<PrevailingType (GlobalValue::GUID)> isPrevailing)7346d97bb29SDimitry Andric void llvm::computeDeadSymbols(
7356d97bb29SDimitry Andric     ModuleSummaryIndex &Index,
7364ba319b5SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
7374ba319b5SDimitry Andric     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
7386d97bb29SDimitry Andric   assert(!Index.withGlobalValueDeadStripping());
73995ec533aSDimitry Andric   if (!ComputeDead)
7406d97bb29SDimitry Andric     return;
74195ec533aSDimitry Andric   if (GUIDPreservedSymbols.empty())
74295ec533aSDimitry Andric     // Don't do anything when nothing is live, this is friendly with tests.
7436d97bb29SDimitry Andric     return;
7446d97bb29SDimitry Andric   unsigned LiveSymbols = 0;
7450f5676f4SDimitry Andric   SmallVector<ValueInfo, 128> Worklist;
7460f5676f4SDimitry Andric   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
7470f5676f4SDimitry Andric   for (auto GUID : GUIDPreservedSymbols) {
7480f5676f4SDimitry Andric     ValueInfo VI = Index.getValueInfo(GUID);
7490f5676f4SDimitry Andric     if (!VI)
7500f5676f4SDimitry Andric       continue;
7516d97bb29SDimitry Andric     for (auto &S : VI.getSummaryList())
7526d97bb29SDimitry Andric       S->setLive(true);
75395ec533aSDimitry Andric   }
7546d97bb29SDimitry Andric 
75595ec533aSDimitry Andric   // Add values flagged in the index as live roots to the worklist.
7564ba319b5SDimitry Andric   for (const auto &Entry : Index) {
7574ba319b5SDimitry Andric     auto VI = Index.getValueInfo(Entry);
7586d97bb29SDimitry Andric     for (auto &S : Entry.second.SummaryList)
7596d97bb29SDimitry Andric       if (S->isLive()) {
7604ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
7614ba319b5SDimitry Andric         Worklist.push_back(VI);
7626d97bb29SDimitry Andric         ++LiveSymbols;
7636d97bb29SDimitry Andric         break;
76495ec533aSDimitry Andric       }
7654ba319b5SDimitry Andric   }
76695ec533aSDimitry Andric 
7676d97bb29SDimitry Andric   // Make value live and add it to the worklist if it was not live before.
7686d97bb29SDimitry Andric   auto visit = [&](ValueInfo VI) {
7692cab237bSDimitry Andric     // FIXME: If we knew which edges were created for indirect call profiles,
7702cab237bSDimitry Andric     // we could skip them here. Any that are live should be reached via
7712cab237bSDimitry Andric     // other edges, e.g. reference edges. Otherwise, using a profile collected
7722cab237bSDimitry Andric     // on a slightly different binary might provoke preserving, importing
7732cab237bSDimitry Andric     // and ultimately promoting calls to functions not linked into this
7742cab237bSDimitry Andric     // binary, which increases the binary size unnecessarily. Note that
7752cab237bSDimitry Andric     // if this code changes, the importer needs to change so that edges
7762cab237bSDimitry Andric     // to functions marked dead are skipped.
7772cab237bSDimitry Andric     VI = updateValueInfoForIndirectCalls(Index, VI);
7782cab237bSDimitry Andric     if (!VI)
7792cab237bSDimitry Andric       return;
780*b5893f02SDimitry Andric 
781*b5893f02SDimitry Andric     // We need to make sure all variants of the symbol are scanned, alias can
782*b5893f02SDimitry Andric     // make one (but not all) alive.
783*b5893f02SDimitry Andric     if (llvm::all_of(VI.getSummaryList(),
784*b5893f02SDimitry Andric                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
785*b5893f02SDimitry Andric                        return S->isLive();
786*b5893f02SDimitry Andric                      }))
7876d97bb29SDimitry Andric       return;
7884ba319b5SDimitry Andric 
7894ba319b5SDimitry Andric     // We only keep live symbols that are known to be non-prevailing if any are
790*b5893f02SDimitry Andric     // available_externally, linkonceodr, weakodr. Those symbols are discarded
791*b5893f02SDimitry Andric     // later in the EliminateAvailableExternally pass and setting them to
792*b5893f02SDimitry Andric     // not-live could break downstreams users of liveness information (PR36483)
793*b5893f02SDimitry Andric     // or limit optimization opportunities.
7944ba319b5SDimitry Andric     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
795*b5893f02SDimitry Andric       bool KeepAliveLinkage = false;
7964ba319b5SDimitry Andric       bool Interposable = false;
7974ba319b5SDimitry Andric       for (auto &S : VI.getSummaryList()) {
798*b5893f02SDimitry Andric         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
799*b5893f02SDimitry Andric             S->linkage() == GlobalValue::WeakODRLinkage ||
800*b5893f02SDimitry Andric             S->linkage() == GlobalValue::LinkOnceODRLinkage)
801*b5893f02SDimitry Andric           KeepAliveLinkage = true;
8024ba319b5SDimitry Andric         else if (GlobalValue::isInterposableLinkage(S->linkage()))
8034ba319b5SDimitry Andric           Interposable = true;
8044ba319b5SDimitry Andric       }
8054ba319b5SDimitry Andric 
806*b5893f02SDimitry Andric       if (!KeepAliveLinkage)
8074ba319b5SDimitry Andric         return;
8084ba319b5SDimitry Andric 
8094ba319b5SDimitry Andric       if (Interposable)
810*b5893f02SDimitry Andric         report_fatal_error(
811*b5893f02SDimitry Andric           "Interposable and available_externally/linkonce_odr/weak_odr symbol");
8124ba319b5SDimitry Andric     }
8134ba319b5SDimitry Andric 
8146d97bb29SDimitry Andric     for (auto &S : VI.getSummaryList())
8156d97bb29SDimitry Andric       S->setLive(true);
8166d97bb29SDimitry Andric     ++LiveSymbols;
8176d97bb29SDimitry Andric     Worklist.push_back(VI);
8186d97bb29SDimitry Andric   };
8196d97bb29SDimitry Andric 
82095ec533aSDimitry Andric   while (!Worklist.empty()) {
8210f5676f4SDimitry Andric     auto VI = Worklist.pop_back_val();
8220f5676f4SDimitry Andric     for (auto &Summary : VI.getSummaryList()) {
8232cab237bSDimitry Andric       GlobalValueSummary *Base = Summary->getBaseObject();
8244ba319b5SDimitry Andric       // Set base value live in case it is an alias.
8254ba319b5SDimitry Andric       Base->setLive(true);
8262cab237bSDimitry Andric       for (auto Ref : Base->refs())
8276d97bb29SDimitry Andric         visit(Ref);
8282cab237bSDimitry Andric       if (auto *FS = dyn_cast<FunctionSummary>(Base))
8296d97bb29SDimitry Andric         for (auto Call : FS->calls())
8306d97bb29SDimitry Andric           visit(Call.first);
83195ec533aSDimitry Andric     }
83295ec533aSDimitry Andric   }
8336d97bb29SDimitry Andric   Index.setWithGlobalValueDeadStripping();
8346d97bb29SDimitry Andric 
8356d97bb29SDimitry Andric   unsigned DeadSymbols = Index.size() - LiveSymbols;
8364ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
8376d97bb29SDimitry Andric                     << " symbols Dead \n");
8386d97bb29SDimitry Andric   NumDeadSymbols += DeadSymbols;
8396d97bb29SDimitry Andric   NumLiveSymbols += LiveSymbols;
84095ec533aSDimitry Andric }
84195ec533aSDimitry Andric 
842*b5893f02SDimitry Andric // Compute dead symbols and propagate constants in combined index.
computeDeadSymbolsWithConstProp(ModuleSummaryIndex & Index,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols,function_ref<PrevailingType (GlobalValue::GUID)> isPrevailing,bool ImportEnabled)843*b5893f02SDimitry Andric void llvm::computeDeadSymbolsWithConstProp(
844*b5893f02SDimitry Andric     ModuleSummaryIndex &Index,
845*b5893f02SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
846*b5893f02SDimitry Andric     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
847*b5893f02SDimitry Andric     bool ImportEnabled) {
848*b5893f02SDimitry Andric   computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
849*b5893f02SDimitry Andric   if (ImportEnabled) {
850*b5893f02SDimitry Andric     Index.propagateConstants(GUIDPreservedSymbols);
851*b5893f02SDimitry Andric   } else {
852*b5893f02SDimitry Andric     // If import is disabled we should drop read-only attribute
853*b5893f02SDimitry Andric     // from all summaries to prevent internalization.
854*b5893f02SDimitry Andric     for (auto &P : Index)
855*b5893f02SDimitry Andric       for (auto &S : P.second.SummaryList)
856*b5893f02SDimitry Andric         if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get()))
857*b5893f02SDimitry Andric           GVS->setReadOnly(false);
858*b5893f02SDimitry Andric   }
859*b5893f02SDimitry Andric }
860*b5893f02SDimitry Andric 
8613ca95b02SDimitry Andric /// Compute the set of summaries needed for a ThinLTO backend compilation of
8623ca95b02SDimitry Andric /// \p ModulePath.
gatherImportedSummariesForModule(StringRef ModulePath,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,const FunctionImporter::ImportMapTy & ImportList,std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)8633ca95b02SDimitry Andric void llvm::gatherImportedSummariesForModule(
8643ca95b02SDimitry Andric     StringRef ModulePath,
8653ca95b02SDimitry Andric     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
866d88c1a5aSDimitry Andric     const FunctionImporter::ImportMapTy &ImportList,
8673ca95b02SDimitry Andric     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
8683ca95b02SDimitry Andric   // Include all summaries from the importing module.
8693ca95b02SDimitry Andric   ModuleToSummariesForIndex[ModulePath] =
8703ca95b02SDimitry Andric       ModuleToDefinedGVSummaries.lookup(ModulePath);
8713ca95b02SDimitry Andric   // Include summaries for imports.
872d88c1a5aSDimitry Andric   for (auto &ILI : ImportList) {
8733ca95b02SDimitry Andric     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
8743ca95b02SDimitry Andric     const auto &DefinedGVSummaries =
8753ca95b02SDimitry Andric         ModuleToDefinedGVSummaries.lookup(ILI.first());
8763ca95b02SDimitry Andric     for (auto &GI : ILI.second) {
8774ba319b5SDimitry Andric       const auto &DS = DefinedGVSummaries.find(GI);
8783ca95b02SDimitry Andric       assert(DS != DefinedGVSummaries.end() &&
8793ca95b02SDimitry Andric              "Expected a defined summary for imported global value");
8804ba319b5SDimitry Andric       SummariesForIndex[GI] = DS->second;
8813ca95b02SDimitry Andric     }
8823ca95b02SDimitry Andric   }
8833ca95b02SDimitry Andric }
8843ca95b02SDimitry Andric 
8853ca95b02SDimitry Andric /// Emit the files \p ModulePath will import from into \p OutputFilename.
EmitImportsFiles(StringRef ModulePath,StringRef OutputFilename,const std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)8864ba319b5SDimitry Andric std::error_code llvm::EmitImportsFiles(
8874ba319b5SDimitry Andric     StringRef ModulePath, StringRef OutputFilename,
8884ba319b5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
8893ca95b02SDimitry Andric   std::error_code EC;
8903ca95b02SDimitry Andric   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
8913ca95b02SDimitry Andric   if (EC)
8923ca95b02SDimitry Andric     return EC;
8934ba319b5SDimitry Andric   for (auto &ILI : ModuleToSummariesForIndex)
8944ba319b5SDimitry Andric     // The ModuleToSummariesForIndex map includes an entry for the current
8954ba319b5SDimitry Andric     // Module (needed for writing out the index files). We don't want to
8964ba319b5SDimitry Andric     // include it in the imports file, however, so filter it out.
8974ba319b5SDimitry Andric     if (ILI.first != ModulePath)
8984ba319b5SDimitry Andric       ImportsOS << ILI.first << "\n";
8993ca95b02SDimitry Andric   return std::error_code();
9003ca95b02SDimitry Andric }
9013ca95b02SDimitry Andric 
convertToDeclaration(GlobalValue & GV)9024ba319b5SDimitry Andric bool llvm::convertToDeclaration(GlobalValue &GV) {
9034ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
9044ba319b5SDimitry Andric                     << "\n");
9054ba319b5SDimitry Andric   if (Function *F = dyn_cast<Function>(&GV)) {
9064ba319b5SDimitry Andric     F->deleteBody();
9074ba319b5SDimitry Andric     F->clearMetadata();
9084ba319b5SDimitry Andric     F->setComdat(nullptr);
9094ba319b5SDimitry Andric   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
9104ba319b5SDimitry Andric     V->setInitializer(nullptr);
9114ba319b5SDimitry Andric     V->setLinkage(GlobalValue::ExternalLinkage);
9124ba319b5SDimitry Andric     V->clearMetadata();
9134ba319b5SDimitry Andric     V->setComdat(nullptr);
9144ba319b5SDimitry Andric   } else {
9154ba319b5SDimitry Andric     GlobalValue *NewGV;
9164ba319b5SDimitry Andric     if (GV.getValueType()->isFunctionTy())
9174ba319b5SDimitry Andric       NewGV =
9184ba319b5SDimitry Andric           Function::Create(cast<FunctionType>(GV.getValueType()),
919*b5893f02SDimitry Andric                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
920*b5893f02SDimitry Andric                            "", GV.getParent());
9214ba319b5SDimitry Andric     else
9224ba319b5SDimitry Andric       NewGV =
9234ba319b5SDimitry Andric           new GlobalVariable(*GV.getParent(), GV.getValueType(),
9244ba319b5SDimitry Andric                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
9254ba319b5SDimitry Andric                              /*init*/ nullptr, "",
9264ba319b5SDimitry Andric                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
9274ba319b5SDimitry Andric                              GV.getType()->getAddressSpace());
9284ba319b5SDimitry Andric     NewGV->takeName(&GV);
9294ba319b5SDimitry Andric     GV.replaceAllUsesWith(NewGV);
9304ba319b5SDimitry Andric     return false;
9314ba319b5SDimitry Andric   }
9324ba319b5SDimitry Andric   return true;
9334ba319b5SDimitry Andric }
9344ba319b5SDimitry Andric 
935*b5893f02SDimitry Andric /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis.
thinLTOResolvePrevailingInModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals)936*b5893f02SDimitry Andric void llvm::thinLTOResolvePrevailingInModule(
9373ca95b02SDimitry Andric     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
9383ca95b02SDimitry Andric   auto updateLinkage = [&](GlobalValue &GV) {
9393ca95b02SDimitry Andric     // See if the global summary analysis computed a new resolved linkage.
9403ca95b02SDimitry Andric     const auto &GS = DefinedGlobals.find(GV.getGUID());
9413ca95b02SDimitry Andric     if (GS == DefinedGlobals.end())
9423ca95b02SDimitry Andric       return;
9433ca95b02SDimitry Andric     auto NewLinkage = GS->second->linkage();
9443ca95b02SDimitry Andric     if (NewLinkage == GV.getLinkage())
9453ca95b02SDimitry Andric       return;
946c4394386SDimitry Andric 
947c4394386SDimitry Andric     // Switch the linkage to weakany if asked for, e.g. we do this for
948c4394386SDimitry Andric     // linker redefined symbols (via --wrap or --defsym).
949c4394386SDimitry Andric     // We record that the visibility should be changed here in `addThinLTO`
950c4394386SDimitry Andric     // as we need access to the resolution vectors for each input file in
951c4394386SDimitry Andric     // order to find which symbols have been redefined.
952c4394386SDimitry Andric     // We may consider reorganizing this code and moving the linkage recording
953*b5893f02SDimitry Andric     // somewhere else, e.g. in thinLTOResolvePrevailingInIndex.
954c4394386SDimitry Andric     if (NewLinkage == GlobalValue::WeakAnyLinkage) {
955c4394386SDimitry Andric       GV.setLinkage(NewLinkage);
956c4394386SDimitry Andric       return;
957c4394386SDimitry Andric     }
958c4394386SDimitry Andric 
959*b5893f02SDimitry Andric     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
960*b5893f02SDimitry Andric         // In case it was dead and already converted to declaration.
961*b5893f02SDimitry Andric         GV.isDeclaration())
962c4394386SDimitry Andric       return;
9637a7e6055SDimitry Andric     // Check for a non-prevailing def that has interposable linkage
9647a7e6055SDimitry Andric     // (e.g. non-odr weak or linkonce). In that case we can't simply
9657a7e6055SDimitry Andric     // convert to available_externally, since it would lose the
9667a7e6055SDimitry Andric     // interposable property and possibly get inlined. Simply drop
9677a7e6055SDimitry Andric     // the definition in that case.
9687a7e6055SDimitry Andric     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
9694ba319b5SDimitry Andric         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
9704ba319b5SDimitry Andric       if (!convertToDeclaration(GV))
9714ba319b5SDimitry Andric         // FIXME: Change this to collect replaced GVs and later erase
972*b5893f02SDimitry Andric         // them from the parent module once thinLTOResolvePrevailingGUID is
9734ba319b5SDimitry Andric         // changed to enable this for aliases.
9744ba319b5SDimitry Andric         llvm_unreachable("Expected GV to be converted");
9754ba319b5SDimitry Andric     } else {
9764ba319b5SDimitry Andric       // If the original symbols has global unnamed addr and linkonce_odr linkage,
9774ba319b5SDimitry Andric       // it should be an auto hide symbol. Add hidden visibility to the symbol to
9784ba319b5SDimitry Andric       // preserve the property.
9794ba319b5SDimitry Andric       if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
9804ba319b5SDimitry Andric           NewLinkage == GlobalValue::WeakODRLinkage)
9814ba319b5SDimitry Andric         GV.setVisibility(GlobalValue::HiddenVisibility);
9824ba319b5SDimitry Andric 
9834ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
9844ba319b5SDimitry Andric                         << "` from " << GV.getLinkage() << " to " << NewLinkage
9854ba319b5SDimitry Andric                         << "\n");
9863ca95b02SDimitry Andric       GV.setLinkage(NewLinkage);
9877a7e6055SDimitry Andric     }
9887a7e6055SDimitry Andric     // Remove declarations from comdats, including available_externally
989d88c1a5aSDimitry Andric     // as this is a declaration for the linker, and will be dropped eventually.
990d88c1a5aSDimitry Andric     // It is illegal for comdats to contain declarations.
991d88c1a5aSDimitry Andric     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
9927a7e6055SDimitry Andric     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
993d88c1a5aSDimitry Andric       GO->setComdat(nullptr);
9943ca95b02SDimitry Andric   };
9953ca95b02SDimitry Andric 
9963ca95b02SDimitry Andric   // Process functions and global now
9973ca95b02SDimitry Andric   for (auto &GV : TheModule)
9983ca95b02SDimitry Andric     updateLinkage(GV);
9993ca95b02SDimitry Andric   for (auto &GV : TheModule.globals())
10003ca95b02SDimitry Andric     updateLinkage(GV);
10013ca95b02SDimitry Andric   for (auto &GV : TheModule.aliases())
10023ca95b02SDimitry Andric     updateLinkage(GV);
10033ca95b02SDimitry Andric }
10043ca95b02SDimitry Andric 
10053ca95b02SDimitry Andric /// Run internalization on \p TheModule based on symmary analysis.
thinLTOInternalizeModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals)10063ca95b02SDimitry Andric void llvm::thinLTOInternalizeModule(Module &TheModule,
10073ca95b02SDimitry Andric                                     const GVSummaryMapTy &DefinedGlobals) {
10083ca95b02SDimitry Andric   // Declare a callback for the internalize pass that will ask for every
10093ca95b02SDimitry Andric   // candidate GlobalValue if it can be internalized or not.
10103ca95b02SDimitry Andric   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
10113ca95b02SDimitry Andric     // Lookup the linkage recorded in the summaries during global analysis.
10125517e702SDimitry Andric     auto GS = DefinedGlobals.find(GV.getGUID());
10133ca95b02SDimitry Andric     if (GS == DefinedGlobals.end()) {
10143ca95b02SDimitry Andric       // Must have been promoted (possibly conservatively). Find original
10153ca95b02SDimitry Andric       // name so that we can access the correct summary and see if it can
10163ca95b02SDimitry Andric       // be internalized again.
10173ca95b02SDimitry Andric       // FIXME: Eventually we should control promotion instead of promoting
10183ca95b02SDimitry Andric       // and internalizing again.
10193ca95b02SDimitry Andric       StringRef OrigName =
10203ca95b02SDimitry Andric           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
10213ca95b02SDimitry Andric       std::string OrigId = GlobalValue::getGlobalIdentifier(
10223ca95b02SDimitry Andric           OrigName, GlobalValue::InternalLinkage,
10233ca95b02SDimitry Andric           TheModule.getSourceFileName());
10245517e702SDimitry Andric       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
10253ca95b02SDimitry Andric       if (GS == DefinedGlobals.end()) {
10263ca95b02SDimitry Andric         // Also check the original non-promoted non-globalized name. In some
10273ca95b02SDimitry Andric         // cases a preempted weak value is linked in as a local copy because
10283ca95b02SDimitry Andric         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
10293ca95b02SDimitry Andric         // In that case, since it was originally not a local value, it was
10303ca95b02SDimitry Andric         // recorded in the index using the original name.
10313ca95b02SDimitry Andric         // FIXME: This may not be needed once PR27866 is fixed.
10325517e702SDimitry Andric         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
10333ca95b02SDimitry Andric         assert(GS != DefinedGlobals.end());
10343ca95b02SDimitry Andric       }
10355517e702SDimitry Andric     }
10365517e702SDimitry Andric     return !GlobalValue::isLocalLinkage(GS->second->linkage());
10373ca95b02SDimitry Andric   };
10383ca95b02SDimitry Andric 
10393ca95b02SDimitry Andric   // FIXME: See if we can just internalize directly here via linkage changes
10403ca95b02SDimitry Andric   // based on the index, rather than invoking internalizeModule.
10412cab237bSDimitry Andric   internalizeModule(TheModule, MustPreserveGV);
10422cab237bSDimitry Andric }
10432cab237bSDimitry Andric 
10442cab237bSDimitry Andric /// Make alias a clone of its aliasee.
replaceAliasWithAliasee(Module * SrcModule,GlobalAlias * GA)10452cab237bSDimitry Andric static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
10462cab237bSDimitry Andric   Function *Fn = cast<Function>(GA->getBaseObject());
10472cab237bSDimitry Andric 
10482cab237bSDimitry Andric   ValueToValueMapTy VMap;
10492cab237bSDimitry Andric   Function *NewFn = CloneFunction(Fn, VMap);
10502cab237bSDimitry Andric   // Clone should use the original alias's linkage and name, and we ensure
10512cab237bSDimitry Andric   // all uses of alias instead use the new clone (casted if necessary).
10522cab237bSDimitry Andric   NewFn->setLinkage(GA->getLinkage());
10532cab237bSDimitry Andric   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
10542cab237bSDimitry Andric   NewFn->takeName(GA);
10552cab237bSDimitry Andric   return NewFn;
10563ca95b02SDimitry Andric }
10573ca95b02SDimitry Andric 
1058*b5893f02SDimitry Andric // Internalize values that we marked with specific attribute
1059*b5893f02SDimitry Andric // in processGlobalForThinLTO.
internalizeImmutableGVs(Module & M)1060*b5893f02SDimitry Andric static void internalizeImmutableGVs(Module &M) {
1061*b5893f02SDimitry Andric   for (auto &GV : M.globals())
1062*b5893f02SDimitry Andric     // Skip GVs which have been converted to declarations
1063*b5893f02SDimitry Andric     // by dropDeadSymbols.
1064*b5893f02SDimitry Andric     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1065*b5893f02SDimitry Andric       GV.setLinkage(GlobalValue::InternalLinkage);
1066*b5893f02SDimitry Andric       GV.setVisibility(GlobalValue::DefaultVisibility);
1067*b5893f02SDimitry Andric     }
1068*b5893f02SDimitry Andric }
1069*b5893f02SDimitry Andric 
10707d523365SDimitry Andric // Automatically import functions in Module \p DestModule based on the summaries
10717d523365SDimitry Andric // index.
importFunctions(Module & DestModule,const FunctionImporter::ImportMapTy & ImportList)1072d88c1a5aSDimitry Andric Expected<bool> FunctionImporter::importFunctions(
10737a7e6055SDimitry Andric     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
10744ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Starting import for Module "
10757d523365SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
10764ba319b5SDimitry Andric   unsigned ImportedCount = 0, ImportedGVCount = 0;
10777d523365SDimitry Andric 
10787a7e6055SDimitry Andric   IRMover Mover(DestModule);
10797d523365SDimitry Andric   // Do the actual import of functions now, one Module at a time
10803ca95b02SDimitry Andric   std::set<StringRef> ModuleNameOrderedList;
10813ca95b02SDimitry Andric   for (auto &FunctionsToImportPerModule : ImportList) {
10823ca95b02SDimitry Andric     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
10833ca95b02SDimitry Andric   }
10843ca95b02SDimitry Andric   for (auto &Name : ModuleNameOrderedList) {
10857d523365SDimitry Andric     // Get the module for the import
10863ca95b02SDimitry Andric     const auto &FunctionsToImportPerModule = ImportList.find(Name);
10873ca95b02SDimitry Andric     assert(FunctionsToImportPerModule != ImportList.end());
1088d88c1a5aSDimitry Andric     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1089d88c1a5aSDimitry Andric     if (!SrcModuleOrErr)
1090d88c1a5aSDimitry Andric       return SrcModuleOrErr.takeError();
1091d88c1a5aSDimitry Andric     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
10927d523365SDimitry Andric     assert(&DestModule.getContext() == &SrcModule->getContext() &&
10937d523365SDimitry Andric            "Context mismatch");
10947d523365SDimitry Andric 
10953ca95b02SDimitry Andric     // If modules were created with lazy metadata loading, materialize it
10963ca95b02SDimitry Andric     // now, before linking it (otherwise this will be a noop).
1097d88c1a5aSDimitry Andric     if (Error Err = SrcModule->materializeMetadata())
1098d88c1a5aSDimitry Andric       return std::move(Err);
10993ca95b02SDimitry Andric 
11003ca95b02SDimitry Andric     auto &ImportGUIDs = FunctionsToImportPerModule->second;
11013ca95b02SDimitry Andric     // Find the globals to import
11027a7e6055SDimitry Andric     SetVector<GlobalValue *> GlobalsToImport;
11033ca95b02SDimitry Andric     for (Function &F : *SrcModule) {
11043ca95b02SDimitry Andric       if (!F.hasName())
11053ca95b02SDimitry Andric         continue;
11063ca95b02SDimitry Andric       auto GUID = F.getGUID();
11073ca95b02SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
11084ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
11094ba319b5SDimitry Andric                         << GUID << " " << F.getName() << " from "
11103ca95b02SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
11113ca95b02SDimitry Andric       if (Import) {
1112d88c1a5aSDimitry Andric         if (Error Err = F.materialize())
1113d88c1a5aSDimitry Andric           return std::move(Err);
11143ca95b02SDimitry Andric         if (EnableImportMetadata) {
11153ca95b02SDimitry Andric           // Add 'thinlto_src_module' metadata for statistics and debugging.
11163ca95b02SDimitry Andric           F.setMetadata(
11173ca95b02SDimitry Andric               "thinlto_src_module",
11182cab237bSDimitry Andric               MDNode::get(DestModule.getContext(),
11192cab237bSDimitry Andric                           {MDString::get(DestModule.getContext(),
11203ca95b02SDimitry Andric                                          SrcModule->getSourceFileName())}));
11213ca95b02SDimitry Andric         }
11223ca95b02SDimitry Andric         GlobalsToImport.insert(&F);
11233ca95b02SDimitry Andric       }
11243ca95b02SDimitry Andric     }
11253ca95b02SDimitry Andric     for (GlobalVariable &GV : SrcModule->globals()) {
11263ca95b02SDimitry Andric       if (!GV.hasName())
11273ca95b02SDimitry Andric         continue;
11283ca95b02SDimitry Andric       auto GUID = GV.getGUID();
11293ca95b02SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
11304ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
11314ba319b5SDimitry Andric                         << GUID << " " << GV.getName() << " from "
11323ca95b02SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
11333ca95b02SDimitry Andric       if (Import) {
1134d88c1a5aSDimitry Andric         if (Error Err = GV.materialize())
1135d88c1a5aSDimitry Andric           return std::move(Err);
11364ba319b5SDimitry Andric         ImportedGVCount += GlobalsToImport.insert(&GV);
11373ca95b02SDimitry Andric       }
11383ca95b02SDimitry Andric     }
11393ca95b02SDimitry Andric     for (GlobalAlias &GA : SrcModule->aliases()) {
11403ca95b02SDimitry Andric       if (!GA.hasName())
11413ca95b02SDimitry Andric         continue;
11423ca95b02SDimitry Andric       auto GUID = GA.getGUID();
11433ca95b02SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
11444ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
11454ba319b5SDimitry Andric                         << GUID << " " << GA.getName() << " from "
11463ca95b02SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
11473ca95b02SDimitry Andric       if (Import) {
1148d88c1a5aSDimitry Andric         if (Error Err = GA.materialize())
1149d88c1a5aSDimitry Andric           return std::move(Err);
11502cab237bSDimitry Andric         // Import alias as a copy of its aliasee.
11512cab237bSDimitry Andric         GlobalObject *Base = GA.getBaseObject();
11522cab237bSDimitry Andric         if (Error Err = Base->materialize())
11532cab237bSDimitry Andric           return std::move(Err);
11542cab237bSDimitry Andric         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
11554ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
11562cab237bSDimitry Andric                           << " " << Base->getName() << " from "
11572cab237bSDimitry Andric                           << SrcModule->getSourceFileName() << "\n");
11582cab237bSDimitry Andric         if (EnableImportMetadata) {
11592cab237bSDimitry Andric           // Add 'thinlto_src_module' metadata for statistics and debugging.
11602cab237bSDimitry Andric           Fn->setMetadata(
11612cab237bSDimitry Andric               "thinlto_src_module",
11622cab237bSDimitry Andric               MDNode::get(DestModule.getContext(),
11632cab237bSDimitry Andric                           {MDString::get(DestModule.getContext(),
11642cab237bSDimitry Andric                                          SrcModule->getSourceFileName())}));
11652cab237bSDimitry Andric         }
11662cab237bSDimitry Andric         GlobalsToImport.insert(Fn);
11673ca95b02SDimitry Andric       }
11683ca95b02SDimitry Andric     }
11697d523365SDimitry Andric 
117095ec533aSDimitry Andric     // Upgrade debug info after we're done materializing all the globals and we
117195ec533aSDimitry Andric     // have loaded all the required metadata!
117295ec533aSDimitry Andric     UpgradeDebugInfo(*SrcModule);
117395ec533aSDimitry Andric 
11747d523365SDimitry Andric     // Link in the specified functions.
11753ca95b02SDimitry Andric     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
11763ca95b02SDimitry Andric       return true;
11773ca95b02SDimitry Andric 
11783ca95b02SDimitry Andric     if (PrintImports) {
11793ca95b02SDimitry Andric       for (const auto *GV : GlobalsToImport)
11803ca95b02SDimitry Andric         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
11813ca95b02SDimitry Andric                << " from " << SrcModule->getSourceFileName() << "\n";
11823ca95b02SDimitry Andric     }
11833ca95b02SDimitry Andric 
11847a7e6055SDimitry Andric     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
11857a7e6055SDimitry Andric                    [](GlobalValue &, IRMover::ValueAdder) {},
11867a7e6055SDimitry Andric                    /*IsPerformingImport=*/true))
11877d523365SDimitry Andric       report_fatal_error("Function Import: link error");
11887d523365SDimitry Andric 
11893ca95b02SDimitry Andric     ImportedCount += GlobalsToImport.size();
119095ec533aSDimitry Andric     NumImportedModules++;
11917d523365SDimitry Andric   }
11927d523365SDimitry Andric 
1193*b5893f02SDimitry Andric   internalizeImmutableGVs(DestModule);
1194*b5893f02SDimitry Andric 
11954ba319b5SDimitry Andric   NumImportedFunctions += (ImportedCount - ImportedGVCount);
11964ba319b5SDimitry Andric   NumImportedGlobalVars += ImportedGVCount;
11977d523365SDimitry Andric 
11984ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
11994ba319b5SDimitry Andric                     << " functions for Module "
12004ba319b5SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
12014ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
12024ba319b5SDimitry Andric                     << " global variables for Module "
12037d523365SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
12047d523365SDimitry Andric   return ImportedCount;
12057d523365SDimitry Andric }
12067d523365SDimitry Andric 
doImportingForModule(Module & M)1207d88c1a5aSDimitry Andric static bool doImportingForModule(Module &M) {
1208d88c1a5aSDimitry Andric   if (SummaryFile.empty())
1209d88c1a5aSDimitry Andric     report_fatal_error("error: -function-import requires -summary-file\n");
1210d88c1a5aSDimitry Andric   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1211d88c1a5aSDimitry Andric       getModuleSummaryIndexForFile(SummaryFile);
1212d88c1a5aSDimitry Andric   if (!IndexPtrOrErr) {
1213d88c1a5aSDimitry Andric     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1214d88c1a5aSDimitry Andric                           "Error loading file '" + SummaryFile + "': ");
12157d523365SDimitry Andric     return false;
12167d523365SDimitry Andric   }
1217d88c1a5aSDimitry Andric   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
12187d523365SDimitry Andric 
12193ca95b02SDimitry Andric   // First step is collecting the import list.
12203ca95b02SDimitry Andric   FunctionImporter::ImportMapTy ImportList;
12212cab237bSDimitry Andric   // If requested, simply import all functions in the index. This is used
12222cab237bSDimitry Andric   // when testing distributed backend handling via the opt tool, when
12232cab237bSDimitry Andric   // we have distributed indexes containing exactly the summaries to import.
12242cab237bSDimitry Andric   if (ImportAllIndex)
12252cab237bSDimitry Andric     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
12262cab237bSDimitry Andric                                                ImportList);
12272cab237bSDimitry Andric   else
12283ca95b02SDimitry Andric     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
12293ca95b02SDimitry Andric                                       ImportList);
12303ca95b02SDimitry Andric 
1231d88c1a5aSDimitry Andric   // Conservatively mark all internal values as promoted. This interface is
1232d88c1a5aSDimitry Andric   // only used when doing importing via the function importing pass. The pass
1233d88c1a5aSDimitry Andric   // is only enabled when testing importing via the 'opt' tool, which does
1234d88c1a5aSDimitry Andric   // not do the ThinLink that would normally determine what values to promote.
1235d88c1a5aSDimitry Andric   for (auto &I : *Index) {
12360f5676f4SDimitry Andric     for (auto &S : I.second.SummaryList) {
1237d88c1a5aSDimitry Andric       if (GlobalValue::isLocalLinkage(S->linkage()))
1238d88c1a5aSDimitry Andric         S->setLinkage(GlobalValue::ExternalLinkage);
1239d88c1a5aSDimitry Andric     }
1240d88c1a5aSDimitry Andric   }
1241d88c1a5aSDimitry Andric 
12423ca95b02SDimitry Andric   // Next we need to promote to global scope and rename any local values that
1243444ed5c5SDimitry Andric   // are potentially exported to other modules.
12443ca95b02SDimitry Andric   if (renameModuleForThinLTO(M, *Index, nullptr)) {
1245444ed5c5SDimitry Andric     errs() << "Error renaming module\n";
1246444ed5c5SDimitry Andric     return false;
1247444ed5c5SDimitry Andric   }
1248444ed5c5SDimitry Andric 
12497d523365SDimitry Andric   // Perform the import now.
12507d523365SDimitry Andric   auto ModuleLoader = [&M](StringRef Identifier) {
12517d523365SDimitry Andric     return loadFile(Identifier, M.getContext());
12527d523365SDimitry Andric   };
12537d523365SDimitry Andric   FunctionImporter Importer(*Index, ModuleLoader);
12547a7e6055SDimitry Andric   Expected<bool> Result = Importer.importFunctions(M, ImportList);
1255d88c1a5aSDimitry Andric 
1256d88c1a5aSDimitry Andric   // FIXME: Probably need to propagate Errors through the pass manager.
1257d88c1a5aSDimitry Andric   if (!Result) {
1258d88c1a5aSDimitry Andric     logAllUnhandledErrors(Result.takeError(), errs(),
1259d88c1a5aSDimitry Andric                           "Error importing module: ");
1260d88c1a5aSDimitry Andric     return false;
1261d88c1a5aSDimitry Andric   }
1262d88c1a5aSDimitry Andric 
1263d88c1a5aSDimitry Andric   return *Result;
1264d88c1a5aSDimitry Andric }
1265d88c1a5aSDimitry Andric 
1266d88c1a5aSDimitry Andric namespace {
12672cab237bSDimitry Andric 
1268d88c1a5aSDimitry Andric /// Pass that performs cross-module function import provided a summary file.
1269d88c1a5aSDimitry Andric class FunctionImportLegacyPass : public ModulePass {
1270d88c1a5aSDimitry Andric public:
1271d88c1a5aSDimitry Andric   /// Pass identification, replacement for typeid
1272d88c1a5aSDimitry Andric   static char ID;
1273d88c1a5aSDimitry Andric 
FunctionImportLegacyPass()12742cab237bSDimitry Andric   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
12752cab237bSDimitry Andric 
1276d88c1a5aSDimitry Andric   /// Specify pass name for debug output
getPassName() const1277d88c1a5aSDimitry Andric   StringRef getPassName() const override { return "Function Importing"; }
1278d88c1a5aSDimitry Andric 
runOnModule(Module & M)1279d88c1a5aSDimitry Andric   bool runOnModule(Module &M) override {
1280d88c1a5aSDimitry Andric     if (skipModule(M))
1281d88c1a5aSDimitry Andric       return false;
1282d88c1a5aSDimitry Andric 
1283d88c1a5aSDimitry Andric     return doImportingForModule(M);
12847d523365SDimitry Andric   }
12857d523365SDimitry Andric };
12862cab237bSDimitry Andric 
12872cab237bSDimitry Andric } // end anonymous namespace
12887d523365SDimitry Andric 
run(Module & M,ModuleAnalysisManager & AM)1289d88c1a5aSDimitry Andric PreservedAnalyses FunctionImportPass::run(Module &M,
1290d88c1a5aSDimitry Andric                                           ModuleAnalysisManager &AM) {
1291d88c1a5aSDimitry Andric   if (!doImportingForModule(M))
1292d88c1a5aSDimitry Andric     return PreservedAnalyses::all();
1293d88c1a5aSDimitry Andric 
1294d88c1a5aSDimitry Andric   return PreservedAnalyses::none();
1295d88c1a5aSDimitry Andric }
1296d88c1a5aSDimitry Andric 
1297d88c1a5aSDimitry Andric char FunctionImportLegacyPass::ID = 0;
1298d88c1a5aSDimitry Andric INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
12997d523365SDimitry Andric                 "Summary Based Function Import", false, false)
13007d523365SDimitry Andric 
13017d523365SDimitry Andric namespace llvm {
13022cab237bSDimitry Andric 
createFunctionImportPass()1303d88c1a5aSDimitry Andric Pass *createFunctionImportPass() {
1304d88c1a5aSDimitry Andric   return new FunctionImportLegacyPass();
13057d523365SDimitry Andric }
13062cab237bSDimitry Andric 
13072cab237bSDimitry Andric } // end namespace llvm
1308