FunctionImport.cpp 56 KB

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