FunctionImport.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements Function import based on summaries.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/IPO/FunctionImport.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ADT/StringMap.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/StringSet.h"
  21. #include "llvm/Bitcode/BitcodeReader.h"
  22. #include "llvm/IR/AutoUpgrade.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/GlobalAlias.h"
  26. #include "llvm/IR/GlobalObject.h"
  27. #include "llvm/IR/GlobalValue.h"
  28. #include "llvm/IR/GlobalVariable.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IR/ModuleSummaryIndex.h"
  32. #include "llvm/IRReader/IRReader.h"
  33. #include "llvm/Linker/IRMover.h"
  34. #include "llvm/Object/ModuleSymbolTable.h"
  35. #include "llvm/Object/SymbolicFile.h"
  36. #include "llvm/Pass.h"
  37. #include "llvm/Support/Casting.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/Error.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/FileSystem.h"
  43. #include "llvm/Support/SourceMgr.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Transforms/IPO/Internalize.h"
  46. #include "llvm/Transforms/Utils/Cloning.h"
  47. #include "llvm/Transforms/Utils/FunctionImportUtils.h"
  48. #include "llvm/Transforms/Utils/ValueMapper.h"
  49. #include <cassert>
  50. #include <memory>
  51. #include <set>
  52. #include <string>
  53. #include <system_error>
  54. #include <tuple>
  55. #include <utility>
  56. using namespace llvm;
  57. #define DEBUG_TYPE "function-import"
  58. STATISTIC(NumImportedFunctionsThinLink,
  59. "Number of functions thin link decided to import");
  60. STATISTIC(NumImportedHotFunctionsThinLink,
  61. "Number of hot functions thin link decided to import");
  62. STATISTIC(NumImportedCriticalFunctionsThinLink,
  63. "Number of critical functions thin link decided to import");
  64. STATISTIC(NumImportedGlobalVarsThinLink,
  65. "Number of global variables thin link decided to import");
  66. STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
  67. STATISTIC(NumImportedGlobalVars,
  68. "Number of global variables imported in backend");
  69. STATISTIC(NumImportedModules, "Number of modules imported from");
  70. STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
  71. STATISTIC(NumLiveSymbols, "Number of live symbols in index");
  72. /// Limit on instruction count of imported functions.
  73. static cl::opt<unsigned> ImportInstrLimit(
  74. "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
  75. cl::desc("Only import functions with less than N instructions"));
  76. static cl::opt<int> ImportCutoff(
  77. "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
  78. cl::desc("Only import first N functions if N>=0 (default -1)"));
  79. static cl::opt<float>
  80. ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
  81. cl::Hidden, cl::value_desc("x"),
  82. cl::desc("As we import functions, multiply the "
  83. "`import-instr-limit` threshold by this factor "
  84. "before processing newly imported functions"));
  85. static cl::opt<float> ImportHotInstrFactor(
  86. "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
  87. cl::value_desc("x"),
  88. cl::desc("As we import functions called from hot callsite, multiply the "
  89. "`import-instr-limit` threshold by this factor "
  90. "before processing newly imported functions"));
  91. static cl::opt<float> ImportHotMultiplier(
  92. "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
  93. cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
  94. static cl::opt<float> ImportCriticalMultiplier(
  95. "import-critical-multiplier", cl::init(100.0), cl::Hidden,
  96. cl::value_desc("x"),
  97. cl::desc(
  98. "Multiply the `import-instr-limit` threshold for critical callsites"));
  99. // FIXME: This multiplier was not really tuned up.
  100. static cl::opt<float> ImportColdMultiplier(
  101. "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
  102. cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
  103. static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
  104. cl::desc("Print imported functions"));
  105. static cl::opt<bool> PrintImportFailures(
  106. "print-import-failures", cl::init(false), cl::Hidden,
  107. cl::desc("Print information for functions rejected for importing"));
  108. static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
  109. cl::desc("Compute dead symbols"));
  110. static cl::opt<bool> EnableImportMetadata(
  111. "enable-import-metadata", cl::init(
  112. #if !defined(NDEBUG)
  113. true /*Enabled with asserts.*/
  114. #else
  115. false
  116. #endif
  117. ),
  118. cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
  119. /// Summary file to use for function importing when using -function-import from
  120. /// the command line.
  121. static cl::opt<std::string>
  122. SummaryFile("summary-file",
  123. cl::desc("The summary file to use for function importing."));
  124. /// Used when testing importing from distributed indexes via opt
  125. // -function-import.
  126. static cl::opt<bool>
  127. ImportAllIndex("import-all-index",
  128. cl::desc("Import all external functions in index."));
  129. // Load lazily a module from \p FileName in \p Context.
  130. static std::unique_ptr<Module> loadFile(const std::string &FileName,
  131. LLVMContext &Context) {
  132. SMDiagnostic Err;
  133. LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
  134. // Metadata isn't loaded until functions are imported, to minimize
  135. // the memory overhead.
  136. std::unique_ptr<Module> Result =
  137. getLazyIRFileModule(FileName, Err, Context,
  138. /* ShouldLazyLoadMetadata = */ true);
  139. if (!Result) {
  140. Err.print("function-import", errs());
  141. report_fatal_error("Abort");
  142. }
  143. return Result;
  144. }
  145. /// Given a list of possible callee implementation for a call site, select one
  146. /// that fits the \p Threshold.
  147. ///
  148. /// FIXME: select "best" instead of first that fits. But what is "best"?
  149. /// - The smallest: more likely to be inlined.
  150. /// - The one with the least outgoing edges (already well optimized).
  151. /// - One from a module already being imported from in order to reduce the
  152. /// number of source modules parsed/linked.
  153. /// - One that has PGO data attached.
  154. /// - [insert you fancy metric here]
  155. static const GlobalValueSummary *
  156. selectCallee(const ModuleSummaryIndex &Index,
  157. ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
  158. unsigned Threshold, StringRef CallerModulePath,
  159. FunctionImporter::ImportFailureReason &Reason,
  160. GlobalValue::GUID GUID) {
  161. Reason = FunctionImporter::ImportFailureReason::None;
  162. auto It = llvm::find_if(
  163. CalleeSummaryList,
  164. [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
  165. auto *GVSummary = SummaryPtr.get();
  166. if (!Index.isGlobalValueLive(GVSummary)) {
  167. Reason = FunctionImporter::ImportFailureReason::NotLive;
  168. return false;
  169. }
  170. // For SamplePGO, in computeImportForFunction the OriginalId
  171. // may have been used to locate the callee summary list (See
  172. // comment there).
  173. // The mapping from OriginalId to GUID may return a GUID
  174. // that corresponds to a static variable. Filter it out here.
  175. // This can happen when
  176. // 1) There is a call to a library function which is not defined
  177. // in the index.
  178. // 2) There is a static variable with the OriginalGUID identical
  179. // to the GUID of the library function in 1);
  180. // When this happens, the logic for SamplePGO kicks in and
  181. // the static variable in 2) will be found, which needs to be
  182. // filtered out.
  183. if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) {
  184. Reason = FunctionImporter::ImportFailureReason::GlobalVar;
  185. return false;
  186. }
  187. if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
  188. Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
  189. // There is no point in importing these, we can't inline them
  190. return false;
  191. }
  192. auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
  193. // If this is a local function, make sure we import the copy
  194. // in the caller's module. The only time a local function can
  195. // share an entry in the index is if there is a local with the same name
  196. // in another module that had the same source file name (in a different
  197. // directory), where each was compiled in their own directory so there
  198. // was not distinguishing path.
  199. // However, do the import from another module if there is only one
  200. // entry in the list - in that case this must be a reference due
  201. // to indirect call profile data, since a function pointer can point to
  202. // a local in another module.
  203. if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
  204. CalleeSummaryList.size() > 1 &&
  205. Summary->modulePath() != CallerModulePath) {
  206. Reason =
  207. FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
  208. return false;
  209. }
  210. if (Summary->instCount() > Threshold) {
  211. Reason = FunctionImporter::ImportFailureReason::TooLarge;
  212. return false;
  213. }
  214. // Skip if it isn't legal to import (e.g. may reference unpromotable
  215. // locals).
  216. if (Summary->notEligibleToImport()) {
  217. Reason = FunctionImporter::ImportFailureReason::NotEligible;
  218. return false;
  219. }
  220. // Don't bother importing if we can't inline it anyway.
  221. if (Summary->fflags().NoInline) {
  222. Reason = FunctionImporter::ImportFailureReason::NoInline;
  223. return false;
  224. }
  225. return true;
  226. });
  227. if (It == CalleeSummaryList.end())
  228. return nullptr;
  229. return cast<GlobalValueSummary>(It->get());
  230. }
  231. namespace {
  232. using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
  233. GlobalValue::GUID>;
  234. } // anonymous namespace
  235. static ValueInfo
  236. updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
  237. if (!VI.getSummaryList().empty())
  238. return VI;
  239. // For SamplePGO, the indirect call targets for local functions will
  240. // have its original name annotated in profile. We try to find the
  241. // corresponding PGOFuncName as the GUID.
  242. // FIXME: Consider updating the edges in the graph after building
  243. // it, rather than needing to perform this mapping on each walk.
  244. auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
  245. if (GUID == 0)
  246. return ValueInfo();
  247. return Index.getValueInfo(GUID);
  248. }
  249. static void computeImportForReferencedGlobals(
  250. const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries,
  251. FunctionImporter::ImportMapTy &ImportList,
  252. StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
  253. for (auto &VI : Summary.refs()) {
  254. if (DefinedGVSummaries.count(VI.getGUID())) {
  255. LLVM_DEBUG(
  256. dbgs() << "Ref ignored! Target already in destination module.\n");
  257. continue;
  258. }
  259. LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
  260. // If this is a local variable, make sure we import the copy
  261. // in the caller's module. The only time a local variable can
  262. // share an entry in the index is if there is a local with the same name
  263. // in another module that had the same source file name (in a different
  264. // directory), where each was compiled in their own directory so there
  265. // was not distinguishing path.
  266. auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
  267. return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
  268. RefSummary->modulePath() != Summary.modulePath();
  269. };
  270. for (auto &RefSummary : VI.getSummaryList())
  271. if (isa<GlobalVarSummary>(RefSummary.get()) &&
  272. canImportGlobalVar(RefSummary.get()) &&
  273. !LocalNotInModule(RefSummary.get())) {
  274. auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
  275. // Only update stat if we haven't already imported this variable.
  276. if (ILI.second)
  277. NumImportedGlobalVarsThinLink++;
  278. if (ExportLists)
  279. (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
  280. break;
  281. }
  282. }
  283. }
  284. static const char *
  285. getFailureName(FunctionImporter::ImportFailureReason Reason) {
  286. switch (Reason) {
  287. case FunctionImporter::ImportFailureReason::None:
  288. return "None";
  289. case FunctionImporter::ImportFailureReason::GlobalVar:
  290. return "GlobalVar";
  291. case FunctionImporter::ImportFailureReason::NotLive:
  292. return "NotLive";
  293. case FunctionImporter::ImportFailureReason::TooLarge:
  294. return "TooLarge";
  295. case FunctionImporter::ImportFailureReason::InterposableLinkage:
  296. return "InterposableLinkage";
  297. case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
  298. return "LocalLinkageNotInModule";
  299. case FunctionImporter::ImportFailureReason::NotEligible:
  300. return "NotEligible";
  301. case FunctionImporter::ImportFailureReason::NoInline:
  302. return "NoInline";
  303. }
  304. llvm_unreachable("invalid reason");
  305. }
  306. /// Compute the list of functions to import for a given caller. Mark these
  307. /// imported functions and the symbols they reference in their source module as
  308. /// exported from their source module.
  309. static void computeImportForFunction(
  310. const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
  311. const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
  312. SmallVectorImpl<EdgeInfo> &Worklist,
  313. FunctionImporter::ImportMapTy &ImportList,
  314. StringMap<FunctionImporter::ExportSetTy> *ExportLists,
  315. FunctionImporter::ImportThresholdsTy &ImportThresholds) {
  316. computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
  317. ExportLists);
  318. static int ImportCount = 0;
  319. for (auto &Edge : Summary.calls()) {
  320. ValueInfo VI = Edge.first;
  321. LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
  322. << "\n");
  323. if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
  324. LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
  325. << " reached.\n");
  326. continue;
  327. }
  328. VI = updateValueInfoForIndirectCalls(Index, VI);
  329. if (!VI)
  330. continue;
  331. if (DefinedGVSummaries.count(VI.getGUID())) {
  332. LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
  333. continue;
  334. }
  335. auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
  336. if (Hotness == CalleeInfo::HotnessType::Hot)
  337. return ImportHotMultiplier;
  338. if (Hotness == CalleeInfo::HotnessType::Cold)
  339. return ImportColdMultiplier;
  340. if (Hotness == CalleeInfo::HotnessType::Critical)
  341. return ImportCriticalMultiplier;
  342. return 1.0;
  343. };
  344. const auto NewThreshold =
  345. Threshold * GetBonusMultiplier(Edge.second.getHotness());
  346. auto IT = ImportThresholds.insert(std::make_pair(
  347. VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
  348. bool PreviouslyVisited = !IT.second;
  349. auto &ProcessedThreshold = std::get<0>(IT.first->second);
  350. auto &CalleeSummary = std::get<1>(IT.first->second);
  351. auto &FailureInfo = std::get<2>(IT.first->second);
  352. bool IsHotCallsite =
  353. Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
  354. bool IsCriticalCallsite =
  355. Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
  356. const FunctionSummary *ResolvedCalleeSummary = nullptr;
  357. if (CalleeSummary) {
  358. assert(PreviouslyVisited);
  359. // Since the traversal of the call graph is DFS, we can revisit a function
  360. // a second time with a higher threshold. In this case, it is added back
  361. // to the worklist with the new threshold (so that its own callee chains
  362. // can be considered with the higher threshold).
  363. if (NewThreshold <= ProcessedThreshold) {
  364. LLVM_DEBUG(
  365. dbgs() << "ignored! Target was already imported with Threshold "
  366. << ProcessedThreshold << "\n");
  367. continue;
  368. }
  369. // Update with new larger threshold.
  370. ProcessedThreshold = NewThreshold;
  371. ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
  372. } else {
  373. // If we already rejected importing a callee at the same or higher
  374. // threshold, don't waste time calling selectCallee.
  375. if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
  376. LLVM_DEBUG(
  377. dbgs() << "ignored! Target was already rejected with Threshold "
  378. << ProcessedThreshold << "\n");
  379. if (PrintImportFailures) {
  380. assert(FailureInfo &&
  381. "Expected FailureInfo for previously rejected candidate");
  382. FailureInfo->Attempts++;
  383. }
  384. continue;
  385. }
  386. FunctionImporter::ImportFailureReason Reason;
  387. CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
  388. Summary.modulePath(), Reason, VI.getGUID());
  389. if (!CalleeSummary) {
  390. // Update with new larger threshold if this was a retry (otherwise
  391. // we would have already inserted with NewThreshold above). Also
  392. // update failure info if requested.
  393. if (PreviouslyVisited) {
  394. ProcessedThreshold = NewThreshold;
  395. if (PrintImportFailures) {
  396. assert(FailureInfo &&
  397. "Expected FailureInfo for previously rejected candidate");
  398. FailureInfo->Reason = Reason;
  399. FailureInfo->Attempts++;
  400. FailureInfo->MaxHotness =
  401. std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
  402. }
  403. } else if (PrintImportFailures) {
  404. assert(!FailureInfo &&
  405. "Expected no FailureInfo for newly rejected candidate");
  406. FailureInfo = llvm::make_unique<FunctionImporter::ImportFailureInfo>(
  407. VI, Edge.second.getHotness(), Reason, 1);
  408. }
  409. LLVM_DEBUG(
  410. dbgs() << "ignored! No qualifying callee with summary found.\n");
  411. continue;
  412. }
  413. // "Resolve" the summary
  414. CalleeSummary = CalleeSummary->getBaseObject();
  415. ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
  416. assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
  417. "selectCallee() didn't honor the threshold");
  418. auto ExportModulePath = ResolvedCalleeSummary->modulePath();
  419. auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
  420. // We previously decided to import this GUID definition if it was already
  421. // inserted in the set of imports from the exporting module.
  422. bool PreviouslyImported = !ILI.second;
  423. if (!PreviouslyImported) {
  424. NumImportedFunctionsThinLink++;
  425. if (IsHotCallsite)
  426. NumImportedHotFunctionsThinLink++;
  427. if (IsCriticalCallsite)
  428. NumImportedCriticalFunctionsThinLink++;
  429. }
  430. // Make exports in the source module.
  431. if (ExportLists) {
  432. auto &ExportList = (*ExportLists)[ExportModulePath];
  433. ExportList.insert(VI.getGUID());
  434. if (!PreviouslyImported) {
  435. // This is the first time this function was exported from its source
  436. // module, so mark all functions and globals it references as exported
  437. // to the outside if they are defined in the same source module.
  438. // For efficiency, we unconditionally add all the referenced GUIDs
  439. // to the ExportList for this module, and will prune out any not
  440. // defined in the module later in a single pass.
  441. for (auto &Edge : ResolvedCalleeSummary->calls()) {
  442. auto CalleeGUID = Edge.first.getGUID();
  443. ExportList.insert(CalleeGUID);
  444. }
  445. for (auto &Ref : ResolvedCalleeSummary->refs()) {
  446. auto GUID = Ref.getGUID();
  447. ExportList.insert(GUID);
  448. }
  449. }
  450. }
  451. }
  452. auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
  453. // Adjust the threshold for next level of imported functions.
  454. // The threshold is different for hot callsites because we can then
  455. // inline chains of hot calls.
  456. if (IsHotCallsite)
  457. return Threshold * ImportHotInstrFactor;
  458. return Threshold * ImportInstrFactor;
  459. };
  460. const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
  461. ImportCount++;
  462. // Insert the newly imported function to the worklist.
  463. Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
  464. }
  465. }
  466. /// Given the list of globals defined in a module, compute the list of imports
  467. /// as well as the list of "exports", i.e. the list of symbols referenced from
  468. /// another module (that may require promotion).
  469. static void ComputeImportForModule(
  470. const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
  471. StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
  472. StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
  473. // Worklist contains the list of function imported in this module, for which
  474. // we will analyse the callees and may import further down the callgraph.
  475. SmallVector<EdgeInfo, 128> Worklist;
  476. FunctionImporter::ImportThresholdsTy ImportThresholds;
  477. // Populate the worklist with the import for the functions in the current
  478. // module
  479. for (auto &GVSummary : DefinedGVSummaries) {
  480. #ifndef NDEBUG
  481. // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
  482. // so this map look up (and possibly others) can be avoided.
  483. auto VI = Index.getValueInfo(GVSummary.first);
  484. #endif
  485. if (!Index.isGlobalValueLive(GVSummary.second)) {
  486. LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
  487. continue;
  488. }
  489. auto *FuncSummary =
  490. dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
  491. if (!FuncSummary)
  492. // Skip import for global variables
  493. continue;
  494. LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
  495. computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
  496. DefinedGVSummaries, Worklist, ImportList,
  497. ExportLists, ImportThresholds);
  498. }
  499. // Process the newly imported functions and add callees to the worklist.
  500. while (!Worklist.empty()) {
  501. auto FuncInfo = Worklist.pop_back_val();
  502. auto *Summary = std::get<0>(FuncInfo);
  503. auto Threshold = std::get<1>(FuncInfo);
  504. computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
  505. Worklist, ImportList, ExportLists,
  506. ImportThresholds);
  507. }
  508. // Print stats about functions considered but rejected for importing
  509. // when requested.
  510. if (PrintImportFailures) {
  511. dbgs() << "Missed imports into module " << ModName << "\n";
  512. for (auto &I : ImportThresholds) {
  513. auto &ProcessedThreshold = std::get<0>(I.second);
  514. auto &CalleeSummary = std::get<1>(I.second);
  515. auto &FailureInfo = std::get<2>(I.second);
  516. if (CalleeSummary)
  517. continue; // We are going to import.
  518. assert(FailureInfo);
  519. FunctionSummary *FS = nullptr;
  520. if (!FailureInfo->VI.getSummaryList().empty())
  521. FS = dyn_cast<FunctionSummary>(
  522. FailureInfo->VI.getSummaryList()[0]->getBaseObject());
  523. dbgs() << FailureInfo->VI
  524. << ": Reason = " << getFailureName(FailureInfo->Reason)
  525. << ", Threshold = " << ProcessedThreshold
  526. << ", Size = " << (FS ? (int)FS->instCount() : -1)
  527. << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
  528. << ", Attempts = " << FailureInfo->Attempts << "\n";
  529. }
  530. }
  531. }
  532. #ifndef NDEBUG
  533. static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
  534. GlobalValue::GUID G) {
  535. if (const auto &VI = Index.getValueInfo(G)) {
  536. auto SL = VI.getSummaryList();
  537. if (!SL.empty())
  538. return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
  539. }
  540. return false;
  541. }
  542. static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
  543. template <class T>
  544. static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
  545. T &Cont) {
  546. unsigned NumGVS = 0;
  547. for (auto &V : Cont)
  548. if (isGlobalVarSummary(Index, getGUID(V)))
  549. ++NumGVS;
  550. return NumGVS;
  551. }
  552. #endif
  553. /// Compute all the import and export for every module using the Index.
  554. void llvm::ComputeCrossModuleImport(
  555. const ModuleSummaryIndex &Index,
  556. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  557. StringMap<FunctionImporter::ImportMapTy> &ImportLists,
  558. StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
  559. // For each module that has function defined, compute the import/export lists.
  560. for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
  561. auto &ImportList = ImportLists[DefinedGVSummaries.first()];
  562. LLVM_DEBUG(dbgs() << "Computing import for Module '"
  563. << DefinedGVSummaries.first() << "'\n");
  564. ComputeImportForModule(DefinedGVSummaries.second, Index,
  565. DefinedGVSummaries.first(), ImportList,
  566. &ExportLists);
  567. }
  568. // When computing imports we added all GUIDs referenced by anything
  569. // imported from the module to its ExportList. Now we prune each ExportList
  570. // of any not defined in that module. This is more efficient than checking
  571. // while computing imports because some of the summary lists may be long
  572. // due to linkonce (comdat) copies.
  573. for (auto &ELI : ExportLists) {
  574. const auto &DefinedGVSummaries =
  575. ModuleToDefinedGVSummaries.lookup(ELI.first());
  576. for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
  577. if (!DefinedGVSummaries.count(*EI))
  578. EI = ELI.second.erase(EI);
  579. else
  580. ++EI;
  581. }
  582. }
  583. #ifndef NDEBUG
  584. LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
  585. << " modules:\n");
  586. for (auto &ModuleImports : ImportLists) {
  587. auto ModName = ModuleImports.first();
  588. auto &Exports = ExportLists[ModName];
  589. unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
  590. LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
  591. << Exports.size() - NumGVS << " functions and " << NumGVS
  592. << " vars. Imports from " << ModuleImports.second.size()
  593. << " modules.\n");
  594. for (auto &Src : ModuleImports.second) {
  595. auto SrcModName = Src.first();
  596. unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
  597. LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
  598. << " functions imported from " << SrcModName << "\n");
  599. LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
  600. << " global vars imported from " << SrcModName << "\n");
  601. }
  602. }
  603. #endif
  604. }
  605. #ifndef NDEBUG
  606. static void dumpImportListForModule(const ModuleSummaryIndex &Index,
  607. StringRef ModulePath,
  608. FunctionImporter::ImportMapTy &ImportList) {
  609. LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
  610. << ImportList.size() << " modules.\n");
  611. for (auto &Src : ImportList) {
  612. auto SrcModName = Src.first();
  613. unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
  614. LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
  615. << " functions imported from " << SrcModName << "\n");
  616. LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
  617. << SrcModName << "\n");
  618. }
  619. }
  620. #endif
  621. /// Compute all the imports for the given module in the Index.
  622. void llvm::ComputeCrossModuleImportForModule(
  623. StringRef ModulePath, const ModuleSummaryIndex &Index,
  624. FunctionImporter::ImportMapTy &ImportList) {
  625. // Collect the list of functions this module defines.
  626. // GUID -> Summary
  627. GVSummaryMapTy FunctionSummaryMap;
  628. Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
  629. // Compute the import list for this module.
  630. LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
  631. ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
  632. #ifndef NDEBUG
  633. dumpImportListForModule(Index, ModulePath, ImportList);
  634. #endif
  635. }
  636. // Mark all external summaries in Index for import into the given module.
  637. // Used for distributed builds using a distributed index.
  638. void llvm::ComputeCrossModuleImportForModuleFromIndex(
  639. StringRef ModulePath, const ModuleSummaryIndex &Index,
  640. FunctionImporter::ImportMapTy &ImportList) {
  641. for (auto &GlobalList : Index) {
  642. // Ignore entries for undefined references.
  643. if (GlobalList.second.SummaryList.empty())
  644. continue;
  645. auto GUID = GlobalList.first;
  646. assert(GlobalList.second.SummaryList.size() == 1 &&
  647. "Expected individual combined index to have one summary per GUID");
  648. auto &Summary = GlobalList.second.SummaryList[0];
  649. // Skip the summaries for the importing module. These are included to
  650. // e.g. record required linkage changes.
  651. if (Summary->modulePath() == ModulePath)
  652. continue;
  653. // Add an entry to provoke importing by thinBackend.
  654. ImportList[Summary->modulePath()].insert(GUID);
  655. }
  656. #ifndef NDEBUG
  657. dumpImportListForModule(Index, ModulePath, ImportList);
  658. #endif
  659. }
  660. void llvm::computeDeadSymbols(
  661. ModuleSummaryIndex &Index,
  662. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
  663. function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
  664. assert(!Index.withGlobalValueDeadStripping());
  665. if (!ComputeDead)
  666. return;
  667. if (GUIDPreservedSymbols.empty())
  668. // Don't do anything when nothing is live, this is friendly with tests.
  669. return;
  670. unsigned LiveSymbols = 0;
  671. SmallVector<ValueInfo, 128> Worklist;
  672. Worklist.reserve(GUIDPreservedSymbols.size() * 2);
  673. for (auto GUID : GUIDPreservedSymbols) {
  674. ValueInfo VI = Index.getValueInfo(GUID);
  675. if (!VI)
  676. continue;
  677. for (auto &S : VI.getSummaryList())
  678. S->setLive(true);
  679. }
  680. // Add values flagged in the index as live roots to the worklist.
  681. for (const auto &Entry : Index) {
  682. auto VI = Index.getValueInfo(Entry);
  683. for (auto &S : Entry.second.SummaryList)
  684. if (S->isLive()) {
  685. LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
  686. Worklist.push_back(VI);
  687. ++LiveSymbols;
  688. break;
  689. }
  690. }
  691. // Make value live and add it to the worklist if it was not live before.
  692. auto visit = [&](ValueInfo VI) {
  693. // FIXME: If we knew which edges were created for indirect call profiles,
  694. // we could skip them here. Any that are live should be reached via
  695. // other edges, e.g. reference edges. Otherwise, using a profile collected
  696. // on a slightly different binary might provoke preserving, importing
  697. // and ultimately promoting calls to functions not linked into this
  698. // binary, which increases the binary size unnecessarily. Note that
  699. // if this code changes, the importer needs to change so that edges
  700. // to functions marked dead are skipped.
  701. VI = updateValueInfoForIndirectCalls(Index, VI);
  702. if (!VI)
  703. return;
  704. if (llvm::any_of(VI.getSummaryList(),
  705. [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
  706. return S->isLive();
  707. }))
  708. return;
  709. // We only keep live symbols that are known to be non-prevailing if any are
  710. // available_externally, linkonceodr, weakodr. Those symbols are discarded
  711. // later in the EliminateAvailableExternally pass and setting them to
  712. // not-live could break downstreams users of liveness information (PR36483)
  713. // or limit optimization opportunities.
  714. if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
  715. bool KeepAliveLinkage = false;
  716. bool Interposable = false;
  717. for (auto &S : VI.getSummaryList()) {
  718. if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
  719. S->linkage() == GlobalValue::WeakODRLinkage ||
  720. S->linkage() == GlobalValue::LinkOnceODRLinkage)
  721. KeepAliveLinkage = true;
  722. else if (GlobalValue::isInterposableLinkage(S->linkage()))
  723. Interposable = true;
  724. }
  725. if (!KeepAliveLinkage)
  726. return;
  727. if (Interposable)
  728. report_fatal_error(
  729. "Interposable and available_externally/linkonce_odr/weak_odr symbol");
  730. }
  731. for (auto &S : VI.getSummaryList())
  732. S->setLive(true);
  733. ++LiveSymbols;
  734. Worklist.push_back(VI);
  735. };
  736. while (!Worklist.empty()) {
  737. auto VI = Worklist.pop_back_val();
  738. for (auto &Summary : VI.getSummaryList()) {
  739. if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
  740. // If this is an alias, visit the aliasee VI to ensure that all copies
  741. // are marked live and it is added to the worklist for further
  742. // processing of its references.
  743. visit(AS->getAliaseeVI());
  744. continue;
  745. }
  746. Summary->setLive(true);
  747. for (auto Ref : Summary->refs())
  748. visit(Ref);
  749. if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
  750. for (auto Call : FS->calls())
  751. visit(Call.first);
  752. }
  753. }
  754. Index.setWithGlobalValueDeadStripping();
  755. unsigned DeadSymbols = Index.size() - LiveSymbols;
  756. LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
  757. << " symbols Dead \n");
  758. NumDeadSymbols += DeadSymbols;
  759. NumLiveSymbols += LiveSymbols;
  760. }
  761. // Compute dead symbols and propagate constants in combined index.
  762. void llvm::computeDeadSymbolsWithConstProp(
  763. ModuleSummaryIndex &Index,
  764. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
  765. function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
  766. bool ImportEnabled) {
  767. computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
  768. if (ImportEnabled) {
  769. Index.propagateConstants(GUIDPreservedSymbols);
  770. } else {
  771. // If import is disabled we should drop read-only attribute
  772. // from all summaries to prevent internalization.
  773. for (auto &P : Index)
  774. for (auto &S : P.second.SummaryList)
  775. if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get()))
  776. GVS->setReadOnly(false);
  777. }
  778. }
  779. /// Compute the set of summaries needed for a ThinLTO backend compilation of
  780. /// \p ModulePath.
  781. void llvm::gatherImportedSummariesForModule(
  782. StringRef ModulePath,
  783. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  784. const FunctionImporter::ImportMapTy &ImportList,
  785. std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
  786. // Include all summaries from the importing module.
  787. ModuleToSummariesForIndex[ModulePath] =
  788. ModuleToDefinedGVSummaries.lookup(ModulePath);
  789. // Include summaries for imports.
  790. for (auto &ILI : ImportList) {
  791. auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
  792. const auto &DefinedGVSummaries =
  793. ModuleToDefinedGVSummaries.lookup(ILI.first());
  794. for (auto &GI : ILI.second) {
  795. const auto &DS = DefinedGVSummaries.find(GI);
  796. assert(DS != DefinedGVSummaries.end() &&
  797. "Expected a defined summary for imported global value");
  798. SummariesForIndex[GI] = DS->second;
  799. }
  800. }
  801. }
  802. /// Emit the files \p ModulePath will import from into \p OutputFilename.
  803. std::error_code llvm::EmitImportsFiles(
  804. StringRef ModulePath, StringRef OutputFilename,
  805. const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
  806. std::error_code EC;
  807. raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
  808. if (EC)
  809. return EC;
  810. for (auto &ILI : ModuleToSummariesForIndex)
  811. // The ModuleToSummariesForIndex map includes an entry for the current
  812. // Module (needed for writing out the index files). We don't want to
  813. // include it in the imports file, however, so filter it out.
  814. if (ILI.first != ModulePath)
  815. ImportsOS << ILI.first << "\n";
  816. return std::error_code();
  817. }
  818. bool llvm::convertToDeclaration(GlobalValue &GV) {
  819. LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
  820. << "\n");
  821. if (Function *F = dyn_cast<Function>(&GV)) {
  822. F->deleteBody();
  823. F->clearMetadata();
  824. F->setComdat(nullptr);
  825. } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
  826. V->setInitializer(nullptr);
  827. V->setLinkage(GlobalValue::ExternalLinkage);
  828. V->clearMetadata();
  829. V->setComdat(nullptr);
  830. } else {
  831. GlobalValue *NewGV;
  832. if (GV.getValueType()->isFunctionTy())
  833. NewGV =
  834. Function::Create(cast<FunctionType>(GV.getValueType()),
  835. GlobalValue::ExternalLinkage, GV.getAddressSpace(),
  836. "", GV.getParent());
  837. else
  838. NewGV =
  839. new GlobalVariable(*GV.getParent(), GV.getValueType(),
  840. /*isConstant*/ false, GlobalValue::ExternalLinkage,
  841. /*init*/ nullptr, "",
  842. /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
  843. GV.getType()->getAddressSpace());
  844. NewGV->takeName(&GV);
  845. GV.replaceAllUsesWith(NewGV);
  846. return false;
  847. }
  848. return true;
  849. }
  850. /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis.
  851. void llvm::thinLTOResolvePrevailingInModule(
  852. Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
  853. auto updateLinkage = [&](GlobalValue &GV) {
  854. // See if the global summary analysis computed a new resolved linkage.
  855. const auto &GS = DefinedGlobals.find(GV.getGUID());
  856. if (GS == DefinedGlobals.end())
  857. return;
  858. auto NewLinkage = GS->second->linkage();
  859. if (NewLinkage == GV.getLinkage())
  860. return;
  861. // Switch the linkage to weakany if asked for, e.g. we do this for
  862. // linker redefined symbols (via --wrap or --defsym).
  863. // We record that the visibility should be changed here in `addThinLTO`
  864. // as we need access to the resolution vectors for each input file in
  865. // order to find which symbols have been redefined.
  866. // We may consider reorganizing this code and moving the linkage recording
  867. // somewhere else, e.g. in thinLTOResolvePrevailingInIndex.
  868. if (NewLinkage == GlobalValue::WeakAnyLinkage) {
  869. GV.setLinkage(NewLinkage);
  870. return;
  871. }
  872. if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
  873. // In case it was dead and already converted to declaration.
  874. GV.isDeclaration())
  875. return;
  876. // Check for a non-prevailing def that has interposable linkage
  877. // (e.g. non-odr weak or linkonce). In that case we can't simply
  878. // convert to available_externally, since it would lose the
  879. // interposable property and possibly get inlined. Simply drop
  880. // the definition in that case.
  881. if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
  882. GlobalValue::isInterposableLinkage(GV.getLinkage())) {
  883. if (!convertToDeclaration(GV))
  884. // FIXME: Change this to collect replaced GVs and later erase
  885. // them from the parent module once thinLTOResolvePrevailingGUID is
  886. // changed to enable this for aliases.
  887. llvm_unreachable("Expected GV to be converted");
  888. } else {
  889. // If all copies of the original symbol had global unnamed addr and
  890. // linkonce_odr linkage, it should be an auto hide symbol. In that case
  891. // the thin link would have marked it as CanAutoHide. Add hidden visibility
  892. // to the symbol to preserve the property.
  893. if (NewLinkage == GlobalValue::WeakODRLinkage &&
  894. GS->second->canAutoHide()) {
  895. assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
  896. GV.setVisibility(GlobalValue::HiddenVisibility);
  897. }
  898. LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
  899. << "` from " << GV.getLinkage() << " to " << NewLinkage
  900. << "\n");
  901. GV.setLinkage(NewLinkage);
  902. }
  903. // Remove declarations from comdats, including available_externally
  904. // as this is a declaration for the linker, and will be dropped eventually.
  905. // It is illegal for comdats to contain declarations.
  906. auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
  907. if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
  908. GO->setComdat(nullptr);
  909. };
  910. // Process functions and global now
  911. for (auto &GV : TheModule)
  912. updateLinkage(GV);
  913. for (auto &GV : TheModule.globals())
  914. updateLinkage(GV);
  915. for (auto &GV : TheModule.aliases())
  916. updateLinkage(GV);
  917. }
  918. /// Run internalization on \p TheModule based on symmary analysis.
  919. void llvm::thinLTOInternalizeModule(Module &TheModule,
  920. const GVSummaryMapTy &DefinedGlobals) {
  921. // Declare a callback for the internalize pass that will ask for every
  922. // candidate GlobalValue if it can be internalized or not.
  923. auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
  924. // Lookup the linkage recorded in the summaries during global analysis.
  925. auto GS = DefinedGlobals.find(GV.getGUID());
  926. if (GS == DefinedGlobals.end()) {
  927. // Must have been promoted (possibly conservatively). Find original
  928. // name so that we can access the correct summary and see if it can
  929. // be internalized again.
  930. // FIXME: Eventually we should control promotion instead of promoting
  931. // and internalizing again.
  932. StringRef OrigName =
  933. ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
  934. std::string OrigId = GlobalValue::getGlobalIdentifier(
  935. OrigName, GlobalValue::InternalLinkage,
  936. TheModule.getSourceFileName());
  937. GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
  938. if (GS == DefinedGlobals.end()) {
  939. // Also check the original non-promoted non-globalized name. In some
  940. // cases a preempted weak value is linked in as a local copy because
  941. // it is referenced by an alias (IRLinker::linkGlobalValueProto).
  942. // In that case, since it was originally not a local value, it was
  943. // recorded in the index using the original name.
  944. // FIXME: This may not be needed once PR27866 is fixed.
  945. GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
  946. assert(GS != DefinedGlobals.end());
  947. }
  948. }
  949. return !GlobalValue::isLocalLinkage(GS->second->linkage());
  950. };
  951. // FIXME: See if we can just internalize directly here via linkage changes
  952. // based on the index, rather than invoking internalizeModule.
  953. internalizeModule(TheModule, MustPreserveGV);
  954. }
  955. /// Make alias a clone of its aliasee.
  956. static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
  957. Function *Fn = cast<Function>(GA->getBaseObject());
  958. ValueToValueMapTy VMap;
  959. Function *NewFn = CloneFunction(Fn, VMap);
  960. // Clone should use the original alias's linkage, visibility and name, and we
  961. // ensure all uses of alias instead use the new clone (casted if necessary).
  962. NewFn->setLinkage(GA->getLinkage());
  963. NewFn->setVisibility(GA->getVisibility());
  964. GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
  965. NewFn->takeName(GA);
  966. return NewFn;
  967. }
  968. // Internalize values that we marked with specific attribute
  969. // in processGlobalForThinLTO.
  970. static void internalizeImmutableGVs(Module &M) {
  971. for (auto &GV : M.globals())
  972. // Skip GVs which have been converted to declarations
  973. // by dropDeadSymbols.
  974. if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
  975. GV.setLinkage(GlobalValue::InternalLinkage);
  976. GV.setVisibility(GlobalValue::DefaultVisibility);
  977. }
  978. }
  979. // Automatically import functions in Module \p DestModule based on the summaries
  980. // index.
  981. Expected<bool> FunctionImporter::importFunctions(
  982. Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
  983. LLVM_DEBUG(dbgs() << "Starting import for Module "
  984. << DestModule.getModuleIdentifier() << "\n");
  985. unsigned ImportedCount = 0, ImportedGVCount = 0;
  986. IRMover Mover(DestModule);
  987. // Do the actual import of functions now, one Module at a time
  988. std::set<StringRef> ModuleNameOrderedList;
  989. for (auto &FunctionsToImportPerModule : ImportList) {
  990. ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
  991. }
  992. for (auto &Name : ModuleNameOrderedList) {
  993. // Get the module for the import
  994. const auto &FunctionsToImportPerModule = ImportList.find(Name);
  995. assert(FunctionsToImportPerModule != ImportList.end());
  996. Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
  997. if (!SrcModuleOrErr)
  998. return SrcModuleOrErr.takeError();
  999. std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
  1000. assert(&DestModule.getContext() == &SrcModule->getContext() &&
  1001. "Context mismatch");
  1002. // If modules were created with lazy metadata loading, materialize it
  1003. // now, before linking it (otherwise this will be a noop).
  1004. if (Error Err = SrcModule->materializeMetadata())
  1005. return std::move(Err);
  1006. auto &ImportGUIDs = FunctionsToImportPerModule->second;
  1007. // Find the globals to import
  1008. SetVector<GlobalValue *> GlobalsToImport;
  1009. for (Function &F : *SrcModule) {
  1010. if (!F.hasName())
  1011. continue;
  1012. auto GUID = F.getGUID();
  1013. auto Import = ImportGUIDs.count(GUID);
  1014. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
  1015. << GUID << " " << F.getName() << " from "
  1016. << SrcModule->getSourceFileName() << "\n");
  1017. if (Import) {
  1018. if (Error Err = F.materialize())
  1019. return std::move(Err);
  1020. if (EnableImportMetadata) {
  1021. // Add 'thinlto_src_module' metadata for statistics and debugging.
  1022. F.setMetadata(
  1023. "thinlto_src_module",
  1024. MDNode::get(DestModule.getContext(),
  1025. {MDString::get(DestModule.getContext(),
  1026. SrcModule->getSourceFileName())}));
  1027. }
  1028. GlobalsToImport.insert(&F);
  1029. }
  1030. }
  1031. for (GlobalVariable &GV : SrcModule->globals()) {
  1032. if (!GV.hasName())
  1033. continue;
  1034. auto GUID = GV.getGUID();
  1035. auto Import = ImportGUIDs.count(GUID);
  1036. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
  1037. << GUID << " " << GV.getName() << " from "
  1038. << SrcModule->getSourceFileName() << "\n");
  1039. if (Import) {
  1040. if (Error Err = GV.materialize())
  1041. return std::move(Err);
  1042. ImportedGVCount += GlobalsToImport.insert(&GV);
  1043. }
  1044. }
  1045. for (GlobalAlias &GA : SrcModule->aliases()) {
  1046. if (!GA.hasName())
  1047. continue;
  1048. auto GUID = GA.getGUID();
  1049. auto Import = ImportGUIDs.count(GUID);
  1050. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
  1051. << GUID << " " << GA.getName() << " from "
  1052. << SrcModule->getSourceFileName() << "\n");
  1053. if (Import) {
  1054. if (Error Err = GA.materialize())
  1055. return std::move(Err);
  1056. // Import alias as a copy of its aliasee.
  1057. GlobalObject *Base = GA.getBaseObject();
  1058. if (Error Err = Base->materialize())
  1059. return std::move(Err);
  1060. auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
  1061. LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
  1062. << " " << Base->getName() << " from "
  1063. << SrcModule->getSourceFileName() << "\n");
  1064. if (EnableImportMetadata) {
  1065. // Add 'thinlto_src_module' metadata for statistics and debugging.
  1066. Fn->setMetadata(
  1067. "thinlto_src_module",
  1068. MDNode::get(DestModule.getContext(),
  1069. {MDString::get(DestModule.getContext(),
  1070. SrcModule->getSourceFileName())}));
  1071. }
  1072. GlobalsToImport.insert(Fn);
  1073. }
  1074. }
  1075. // Upgrade debug info after we're done materializing all the globals and we
  1076. // have loaded all the required metadata!
  1077. UpgradeDebugInfo(*SrcModule);
  1078. // Link in the specified functions.
  1079. if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
  1080. return true;
  1081. if (PrintImports) {
  1082. for (const auto *GV : GlobalsToImport)
  1083. dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
  1084. << " from " << SrcModule->getSourceFileName() << "\n";
  1085. }
  1086. if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
  1087. [](GlobalValue &, IRMover::ValueAdder) {},
  1088. /*IsPerformingImport=*/true))
  1089. report_fatal_error("Function Import: link error");
  1090. ImportedCount += GlobalsToImport.size();
  1091. NumImportedModules++;
  1092. }
  1093. internalizeImmutableGVs(DestModule);
  1094. NumImportedFunctions += (ImportedCount - ImportedGVCount);
  1095. NumImportedGlobalVars += ImportedGVCount;
  1096. LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
  1097. << " functions for Module "
  1098. << DestModule.getModuleIdentifier() << "\n");
  1099. LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
  1100. << " global variables for Module "
  1101. << DestModule.getModuleIdentifier() << "\n");
  1102. return ImportedCount;
  1103. }
  1104. static bool doImportingForModule(Module &M) {
  1105. if (SummaryFile.empty())
  1106. report_fatal_error("error: -function-import requires -summary-file\n");
  1107. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
  1108. getModuleSummaryIndexForFile(SummaryFile);
  1109. if (!IndexPtrOrErr) {
  1110. logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
  1111. "Error loading file '" + SummaryFile + "': ");
  1112. return false;
  1113. }
  1114. std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
  1115. // First step is collecting the import list.
  1116. FunctionImporter::ImportMapTy ImportList;
  1117. // If requested, simply import all functions in the index. This is used
  1118. // when testing distributed backend handling via the opt tool, when
  1119. // we have distributed indexes containing exactly the summaries to import.
  1120. if (ImportAllIndex)
  1121. ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
  1122. ImportList);
  1123. else
  1124. ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
  1125. ImportList);
  1126. // Conservatively mark all internal values as promoted. This interface is
  1127. // only used when doing importing via the function importing pass. The pass
  1128. // is only enabled when testing importing via the 'opt' tool, which does
  1129. // not do the ThinLink that would normally determine what values to promote.
  1130. for (auto &I : *Index) {
  1131. for (auto &S : I.second.SummaryList) {
  1132. if (GlobalValue::isLocalLinkage(S->linkage()))
  1133. S->setLinkage(GlobalValue::ExternalLinkage);
  1134. }
  1135. }
  1136. // Next we need to promote to global scope and rename any local values that
  1137. // are potentially exported to other modules.
  1138. if (renameModuleForThinLTO(M, *Index, nullptr)) {
  1139. errs() << "Error renaming module\n";
  1140. return false;
  1141. }
  1142. // Perform the import now.
  1143. auto ModuleLoader = [&M](StringRef Identifier) {
  1144. return loadFile(Identifier, M.getContext());
  1145. };
  1146. FunctionImporter Importer(*Index, ModuleLoader);
  1147. Expected<bool> Result = Importer.importFunctions(M, ImportList);
  1148. // FIXME: Probably need to propagate Errors through the pass manager.
  1149. if (!Result) {
  1150. logAllUnhandledErrors(Result.takeError(), errs(),
  1151. "Error importing module: ");
  1152. return false;
  1153. }
  1154. return *Result;
  1155. }
  1156. namespace {
  1157. /// Pass that performs cross-module function import provided a summary file.
  1158. class FunctionImportLegacyPass : public ModulePass {
  1159. public:
  1160. /// Pass identification, replacement for typeid
  1161. static char ID;
  1162. explicit FunctionImportLegacyPass() : ModulePass(ID) {}
  1163. /// Specify pass name for debug output
  1164. StringRef getPassName() const override { return "Function Importing"; }
  1165. bool runOnModule(Module &M) override {
  1166. if (skipModule(M))
  1167. return false;
  1168. return doImportingForModule(M);
  1169. }
  1170. };
  1171. } // end anonymous namespace
  1172. PreservedAnalyses FunctionImportPass::run(Module &M,
  1173. ModuleAnalysisManager &AM) {
  1174. if (!doImportingForModule(M))
  1175. return PreservedAnalyses::all();
  1176. return PreservedAnalyses::none();
  1177. }
  1178. char FunctionImportLegacyPass::ID = 0;
  1179. INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
  1180. "Summary Based Function Import", false, false)
  1181. namespace llvm {
  1182. Pass *createFunctionImportPass() {
  1183. return new FunctionImportLegacyPass();
  1184. }
  1185. } // end namespace llvm