FunctionImport.cpp 51 KB

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