FunctionImport.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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.propagateAttributes(GUIDPreservedSymbols);
  770. } else {
  771. // If import is disabled we should drop read/write-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. GVS->setWriteOnly(false);
  778. }
  779. }
  780. }
  781. /// Compute the set of summaries needed for a ThinLTO backend compilation of
  782. /// \p ModulePath.
  783. void llvm::gatherImportedSummariesForModule(
  784. StringRef ModulePath,
  785. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  786. const FunctionImporter::ImportMapTy &ImportList,
  787. std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
  788. // Include all summaries from the importing module.
  789. ModuleToSummariesForIndex[ModulePath] =
  790. ModuleToDefinedGVSummaries.lookup(ModulePath);
  791. // Include summaries for imports.
  792. for (auto &ILI : ImportList) {
  793. auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
  794. const auto &DefinedGVSummaries =
  795. ModuleToDefinedGVSummaries.lookup(ILI.first());
  796. for (auto &GI : ILI.second) {
  797. const auto &DS = DefinedGVSummaries.find(GI);
  798. assert(DS != DefinedGVSummaries.end() &&
  799. "Expected a defined summary for imported global value");
  800. SummariesForIndex[GI] = DS->second;
  801. }
  802. }
  803. }
  804. /// Emit the files \p ModulePath will import from into \p OutputFilename.
  805. std::error_code llvm::EmitImportsFiles(
  806. StringRef ModulePath, StringRef OutputFilename,
  807. const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
  808. std::error_code EC;
  809. raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
  810. if (EC)
  811. return EC;
  812. for (auto &ILI : ModuleToSummariesForIndex)
  813. // The ModuleToSummariesForIndex map includes an entry for the current
  814. // Module (needed for writing out the index files). We don't want to
  815. // include it in the imports file, however, so filter it out.
  816. if (ILI.first != ModulePath)
  817. ImportsOS << ILI.first << "\n";
  818. return std::error_code();
  819. }
  820. bool llvm::convertToDeclaration(GlobalValue &GV) {
  821. LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
  822. << "\n");
  823. if (Function *F = dyn_cast<Function>(&GV)) {
  824. F->deleteBody();
  825. F->clearMetadata();
  826. F->setComdat(nullptr);
  827. } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
  828. V->setInitializer(nullptr);
  829. V->setLinkage(GlobalValue::ExternalLinkage);
  830. V->clearMetadata();
  831. V->setComdat(nullptr);
  832. } else {
  833. GlobalValue *NewGV;
  834. if (GV.getValueType()->isFunctionTy())
  835. NewGV =
  836. Function::Create(cast<FunctionType>(GV.getValueType()),
  837. GlobalValue::ExternalLinkage, GV.getAddressSpace(),
  838. "", GV.getParent());
  839. else
  840. NewGV =
  841. new GlobalVariable(*GV.getParent(), GV.getValueType(),
  842. /*isConstant*/ false, GlobalValue::ExternalLinkage,
  843. /*init*/ nullptr, "",
  844. /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
  845. GV.getType()->getAddressSpace());
  846. NewGV->takeName(&GV);
  847. GV.replaceAllUsesWith(NewGV);
  848. return false;
  849. }
  850. return true;
  851. }
  852. /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis.
  853. void llvm::thinLTOResolvePrevailingInModule(
  854. Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
  855. auto updateLinkage = [&](GlobalValue &GV) {
  856. // See if the global summary analysis computed a new resolved linkage.
  857. const auto &GS = DefinedGlobals.find(GV.getGUID());
  858. if (GS == DefinedGlobals.end())
  859. return;
  860. auto NewLinkage = GS->second->linkage();
  861. if (NewLinkage == GV.getLinkage())
  862. return;
  863. // Switch the linkage to weakany if asked for, e.g. we do this for
  864. // linker redefined symbols (via --wrap or --defsym).
  865. // We record that the visibility should be changed here in `addThinLTO`
  866. // as we need access to the resolution vectors for each input file in
  867. // order to find which symbols have been redefined.
  868. // We may consider reorganizing this code and moving the linkage recording
  869. // somewhere else, e.g. in thinLTOResolvePrevailingInIndex.
  870. if (NewLinkage == GlobalValue::WeakAnyLinkage) {
  871. GV.setLinkage(NewLinkage);
  872. return;
  873. }
  874. if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
  875. // In case it was dead and already converted to declaration.
  876. GV.isDeclaration())
  877. return;
  878. // Check for a non-prevailing def that has interposable linkage
  879. // (e.g. non-odr weak or linkonce). In that case we can't simply
  880. // convert to available_externally, since it would lose the
  881. // interposable property and possibly get inlined. Simply drop
  882. // the definition in that case.
  883. if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
  884. GlobalValue::isInterposableLinkage(GV.getLinkage())) {
  885. if (!convertToDeclaration(GV))
  886. // FIXME: Change this to collect replaced GVs and later erase
  887. // them from the parent module once thinLTOResolvePrevailingGUID is
  888. // changed to enable this for aliases.
  889. llvm_unreachable("Expected GV to be converted");
  890. } else {
  891. // If all copies of the original symbol had global unnamed addr and
  892. // linkonce_odr linkage, it should be an auto hide symbol. In that case
  893. // the thin link would have marked it as CanAutoHide. Add hidden visibility
  894. // to the symbol to preserve the property.
  895. if (NewLinkage == GlobalValue::WeakODRLinkage &&
  896. GS->second->canAutoHide()) {
  897. assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
  898. GV.setVisibility(GlobalValue::HiddenVisibility);
  899. }
  900. LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
  901. << "` from " << GV.getLinkage() << " to " << NewLinkage
  902. << "\n");
  903. GV.setLinkage(NewLinkage);
  904. }
  905. // Remove declarations from comdats, including available_externally
  906. // as this is a declaration for the linker, and will be dropped eventually.
  907. // It is illegal for comdats to contain declarations.
  908. auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
  909. if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
  910. GO->setComdat(nullptr);
  911. };
  912. // Process functions and global now
  913. for (auto &GV : TheModule)
  914. updateLinkage(GV);
  915. for (auto &GV : TheModule.globals())
  916. updateLinkage(GV);
  917. for (auto &GV : TheModule.aliases())
  918. updateLinkage(GV);
  919. }
  920. /// Run internalization on \p TheModule based on symmary analysis.
  921. void llvm::thinLTOInternalizeModule(Module &TheModule,
  922. const GVSummaryMapTy &DefinedGlobals) {
  923. // Declare a callback for the internalize pass that will ask for every
  924. // candidate GlobalValue if it can be internalized or not.
  925. auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
  926. // Lookup the linkage recorded in the summaries during global analysis.
  927. auto GS = DefinedGlobals.find(GV.getGUID());
  928. if (GS == DefinedGlobals.end()) {
  929. // Must have been promoted (possibly conservatively). Find original
  930. // name so that we can access the correct summary and see if it can
  931. // be internalized again.
  932. // FIXME: Eventually we should control promotion instead of promoting
  933. // and internalizing again.
  934. StringRef OrigName =
  935. ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
  936. std::string OrigId = GlobalValue::getGlobalIdentifier(
  937. OrigName, GlobalValue::InternalLinkage,
  938. TheModule.getSourceFileName());
  939. GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
  940. if (GS == DefinedGlobals.end()) {
  941. // Also check the original non-promoted non-globalized name. In some
  942. // cases a preempted weak value is linked in as a local copy because
  943. // it is referenced by an alias (IRLinker::linkGlobalValueProto).
  944. // In that case, since it was originally not a local value, it was
  945. // recorded in the index using the original name.
  946. // FIXME: This may not be needed once PR27866 is fixed.
  947. GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
  948. assert(GS != DefinedGlobals.end());
  949. }
  950. }
  951. return !GlobalValue::isLocalLinkage(GS->second->linkage());
  952. };
  953. // FIXME: See if we can just internalize directly here via linkage changes
  954. // based on the index, rather than invoking internalizeModule.
  955. internalizeModule(TheModule, MustPreserveGV);
  956. }
  957. /// Make alias a clone of its aliasee.
  958. static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
  959. Function *Fn = cast<Function>(GA->getBaseObject());
  960. ValueToValueMapTy VMap;
  961. Function *NewFn = CloneFunction(Fn, VMap);
  962. // Clone should use the original alias's linkage, visibility and name, and we
  963. // ensure all uses of alias instead use the new clone (casted if necessary).
  964. NewFn->setLinkage(GA->getLinkage());
  965. NewFn->setVisibility(GA->getVisibility());
  966. GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
  967. NewFn->takeName(GA);
  968. return NewFn;
  969. }
  970. // Internalize values that we marked with specific attribute
  971. // in processGlobalForThinLTO.
  972. static void internalizeGVsAfterImport(Module &M) {
  973. for (auto &GV : M.globals())
  974. // Skip GVs which have been converted to declarations
  975. // by dropDeadSymbols.
  976. if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
  977. GV.setLinkage(GlobalValue::InternalLinkage);
  978. GV.setVisibility(GlobalValue::DefaultVisibility);
  979. }
  980. }
  981. // Automatically import functions in Module \p DestModule based on the summaries
  982. // index.
  983. Expected<bool> FunctionImporter::importFunctions(
  984. Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
  985. LLVM_DEBUG(dbgs() << "Starting import for Module "
  986. << DestModule.getModuleIdentifier() << "\n");
  987. unsigned ImportedCount = 0, ImportedGVCount = 0;
  988. IRMover Mover(DestModule);
  989. // Do the actual import of functions now, one Module at a time
  990. std::set<StringRef> ModuleNameOrderedList;
  991. for (auto &FunctionsToImportPerModule : ImportList) {
  992. ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
  993. }
  994. for (auto &Name : ModuleNameOrderedList) {
  995. // Get the module for the import
  996. const auto &FunctionsToImportPerModule = ImportList.find(Name);
  997. assert(FunctionsToImportPerModule != ImportList.end());
  998. Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
  999. if (!SrcModuleOrErr)
  1000. return SrcModuleOrErr.takeError();
  1001. std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
  1002. assert(&DestModule.getContext() == &SrcModule->getContext() &&
  1003. "Context mismatch");
  1004. // If modules were created with lazy metadata loading, materialize it
  1005. // now, before linking it (otherwise this will be a noop).
  1006. if (Error Err = SrcModule->materializeMetadata())
  1007. return std::move(Err);
  1008. auto &ImportGUIDs = FunctionsToImportPerModule->second;
  1009. // Find the globals to import
  1010. SetVector<GlobalValue *> GlobalsToImport;
  1011. for (Function &F : *SrcModule) {
  1012. if (!F.hasName())
  1013. continue;
  1014. auto GUID = F.getGUID();
  1015. auto Import = ImportGUIDs.count(GUID);
  1016. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
  1017. << GUID << " " << F.getName() << " from "
  1018. << SrcModule->getSourceFileName() << "\n");
  1019. if (Import) {
  1020. if (Error Err = F.materialize())
  1021. return std::move(Err);
  1022. if (EnableImportMetadata) {
  1023. // Add 'thinlto_src_module' metadata for statistics and debugging.
  1024. F.setMetadata(
  1025. "thinlto_src_module",
  1026. MDNode::get(DestModule.getContext(),
  1027. {MDString::get(DestModule.getContext(),
  1028. SrcModule->getSourceFileName())}));
  1029. }
  1030. GlobalsToImport.insert(&F);
  1031. }
  1032. }
  1033. for (GlobalVariable &GV : SrcModule->globals()) {
  1034. if (!GV.hasName())
  1035. continue;
  1036. auto GUID = GV.getGUID();
  1037. auto Import = ImportGUIDs.count(GUID);
  1038. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
  1039. << GUID << " " << GV.getName() << " from "
  1040. << SrcModule->getSourceFileName() << "\n");
  1041. if (Import) {
  1042. if (Error Err = GV.materialize())
  1043. return std::move(Err);
  1044. ImportedGVCount += GlobalsToImport.insert(&GV);
  1045. }
  1046. }
  1047. for (GlobalAlias &GA : SrcModule->aliases()) {
  1048. if (!GA.hasName())
  1049. continue;
  1050. auto GUID = GA.getGUID();
  1051. auto Import = ImportGUIDs.count(GUID);
  1052. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
  1053. << GUID << " " << GA.getName() << " from "
  1054. << SrcModule->getSourceFileName() << "\n");
  1055. if (Import) {
  1056. if (Error Err = GA.materialize())
  1057. return std::move(Err);
  1058. // Import alias as a copy of its aliasee.
  1059. GlobalObject *Base = GA.getBaseObject();
  1060. if (Error Err = Base->materialize())
  1061. return std::move(Err);
  1062. auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
  1063. LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
  1064. << " " << Base->getName() << " from "
  1065. << SrcModule->getSourceFileName() << "\n");
  1066. if (EnableImportMetadata) {
  1067. // Add 'thinlto_src_module' metadata for statistics and debugging.
  1068. Fn->setMetadata(
  1069. "thinlto_src_module",
  1070. MDNode::get(DestModule.getContext(),
  1071. {MDString::get(DestModule.getContext(),
  1072. SrcModule->getSourceFileName())}));
  1073. }
  1074. GlobalsToImport.insert(Fn);
  1075. }
  1076. }
  1077. // Upgrade debug info after we're done materializing all the globals and we
  1078. // have loaded all the required metadata!
  1079. UpgradeDebugInfo(*SrcModule);
  1080. // Link in the specified functions.
  1081. if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
  1082. return true;
  1083. if (PrintImports) {
  1084. for (const auto *GV : GlobalsToImport)
  1085. dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
  1086. << " from " << SrcModule->getSourceFileName() << "\n";
  1087. }
  1088. if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
  1089. [](GlobalValue &, IRMover::ValueAdder) {},
  1090. /*IsPerformingImport=*/true))
  1091. report_fatal_error("Function Import: link error");
  1092. ImportedCount += GlobalsToImport.size();
  1093. NumImportedModules++;
  1094. }
  1095. internalizeGVsAfterImport(DestModule);
  1096. NumImportedFunctions += (ImportedCount - ImportedGVCount);
  1097. NumImportedGlobalVars += ImportedGVCount;
  1098. LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
  1099. << " functions for Module "
  1100. << DestModule.getModuleIdentifier() << "\n");
  1101. LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
  1102. << " global variables for Module "
  1103. << DestModule.getModuleIdentifier() << "\n");
  1104. return ImportedCount;
  1105. }
  1106. static bool doImportingForModule(Module &M) {
  1107. if (SummaryFile.empty())
  1108. report_fatal_error("error: -function-import requires -summary-file\n");
  1109. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
  1110. getModuleSummaryIndexForFile(SummaryFile);
  1111. if (!IndexPtrOrErr) {
  1112. logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
  1113. "Error loading file '" + SummaryFile + "': ");
  1114. return false;
  1115. }
  1116. std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
  1117. // First step is collecting the import list.
  1118. FunctionImporter::ImportMapTy ImportList;
  1119. // If requested, simply import all functions in the index. This is used
  1120. // when testing distributed backend handling via the opt tool, when
  1121. // we have distributed indexes containing exactly the summaries to import.
  1122. if (ImportAllIndex)
  1123. ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
  1124. ImportList);
  1125. else
  1126. ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
  1127. ImportList);
  1128. // Conservatively mark all internal values as promoted. This interface is
  1129. // only used when doing importing via the function importing pass. The pass
  1130. // is only enabled when testing importing via the 'opt' tool, which does
  1131. // not do the ThinLink that would normally determine what values to promote.
  1132. for (auto &I : *Index) {
  1133. for (auto &S : I.second.SummaryList) {
  1134. if (GlobalValue::isLocalLinkage(S->linkage()))
  1135. S->setLinkage(GlobalValue::ExternalLinkage);
  1136. }
  1137. }
  1138. // Next we need to promote to global scope and rename any local values that
  1139. // are potentially exported to other modules.
  1140. if (renameModuleForThinLTO(M, *Index, nullptr)) {
  1141. errs() << "Error renaming module\n";
  1142. return false;
  1143. }
  1144. // Perform the import now.
  1145. auto ModuleLoader = [&M](StringRef Identifier) {
  1146. return loadFile(Identifier, M.getContext());
  1147. };
  1148. FunctionImporter Importer(*Index, ModuleLoader);
  1149. Expected<bool> Result = Importer.importFunctions(M, ImportList);
  1150. // FIXME: Probably need to propagate Errors through the pass manager.
  1151. if (!Result) {
  1152. logAllUnhandledErrors(Result.takeError(), errs(),
  1153. "Error importing module: ");
  1154. return false;
  1155. }
  1156. return *Result;
  1157. }
  1158. namespace {
  1159. /// Pass that performs cross-module function import provided a summary file.
  1160. class FunctionImportLegacyPass : public ModulePass {
  1161. public:
  1162. /// Pass identification, replacement for typeid
  1163. static char ID;
  1164. explicit FunctionImportLegacyPass() : ModulePass(ID) {}
  1165. /// Specify pass name for debug output
  1166. StringRef getPassName() const override { return "Function Importing"; }
  1167. bool runOnModule(Module &M) override {
  1168. if (skipModule(M))
  1169. return false;
  1170. return doImportingForModule(M);
  1171. }
  1172. };
  1173. } // end anonymous namespace
  1174. PreservedAnalyses FunctionImportPass::run(Module &M,
  1175. ModuleAnalysisManager &AM) {
  1176. if (!doImportingForModule(M))
  1177. return PreservedAnalyses::all();
  1178. return PreservedAnalyses::none();
  1179. }
  1180. char FunctionImportLegacyPass::ID = 0;
  1181. INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
  1182. "Summary Based Function Import", false, false)
  1183. namespace llvm {
  1184. Pass *createFunctionImportPass() {
  1185. return new FunctionImportLegacyPass();
  1186. }
  1187. } // end namespace llvm