FunctionImportUtils.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
  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 the FunctionImportGlobalProcessing class, used
  10. // to perform the necessary global value handling for function importing.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/FunctionImportUtils.h"
  14. #include "llvm/Support/CommandLine.h"
  15. using namespace llvm;
  16. /// Uses the "source_filename" instead of a Module hash ID for the suffix of
  17. /// promoted locals during LTO. NOTE: This requires that the source filename
  18. /// has a unique name / path to avoid name collisions.
  19. static cl::opt<bool> UseSourceFilenameForPromotedLocals(
  20. "use-source-filename-for-promoted-locals", cl::Hidden,
  21. cl::desc("Uses the source file name instead of the Module hash. "
  22. "This requires that the source filename has a unique name / "
  23. "path to avoid name collisions."));
  24. /// Checks if we should import SGV as a definition, otherwise import as a
  25. /// declaration.
  26. bool FunctionImportGlobalProcessing::doImportAsDefinition(
  27. const GlobalValue *SGV) {
  28. if (!isPerformingImport())
  29. return false;
  30. // Only import the globals requested for importing.
  31. if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
  32. return false;
  33. assert(!isa<GlobalAlias>(SGV) &&
  34. "Unexpected global alias in the import list.");
  35. // Otherwise yes.
  36. return true;
  37. }
  38. bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
  39. const GlobalValue *SGV, ValueInfo VI) {
  40. assert(SGV->hasLocalLinkage());
  41. // Ifuncs and ifunc alias does not have summary.
  42. if (isa<GlobalIFunc>(SGV) ||
  43. (isa<GlobalAlias>(SGV) &&
  44. isa<GlobalIFunc>(cast<GlobalAlias>(SGV)->getAliaseeObject())))
  45. return false;
  46. // Both the imported references and the original local variable must
  47. // be promoted.
  48. if (!isPerformingImport() && !isModuleExporting())
  49. return false;
  50. if (isPerformingImport()) {
  51. assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
  52. !isNonRenamableLocal(*SGV)) &&
  53. "Attempting to promote non-renamable local");
  54. // We don't know for sure yet if we are importing this value (as either
  55. // a reference or a def), since we are simply walking all values in the
  56. // module. But by necessity if we end up importing it and it is local,
  57. // it must be promoted, so unconditionally promote all values in the
  58. // importing module.
  59. return true;
  60. }
  61. // When exporting, consult the index. We can have more than one local
  62. // with the same GUID, in the case of same-named locals in different but
  63. // same-named source files that were compiled in their respective directories
  64. // (so the source file name and resulting GUID is the same). Find the one
  65. // in this module.
  66. auto Summary = ImportIndex.findSummaryInModule(
  67. VI, SGV->getParent()->getModuleIdentifier());
  68. assert(Summary && "Missing summary for global value when exporting");
  69. auto Linkage = Summary->linkage();
  70. if (!GlobalValue::isLocalLinkage(Linkage)) {
  71. assert(!isNonRenamableLocal(*SGV) &&
  72. "Attempting to promote non-renamable local");
  73. return true;
  74. }
  75. return false;
  76. }
  77. #ifndef NDEBUG
  78. bool FunctionImportGlobalProcessing::isNonRenamableLocal(
  79. const GlobalValue &GV) const {
  80. if (!GV.hasLocalLinkage())
  81. return false;
  82. // This needs to stay in sync with the logic in buildModuleSummaryIndex.
  83. if (GV.hasSection())
  84. return true;
  85. if (Used.count(const_cast<GlobalValue *>(&GV)))
  86. return true;
  87. return false;
  88. }
  89. #endif
  90. std::string
  91. FunctionImportGlobalProcessing::getPromotedName(const GlobalValue *SGV) {
  92. assert(SGV->hasLocalLinkage());
  93. // For locals that must be promoted to global scope, ensure that
  94. // the promoted name uniquely identifies the copy in the original module,
  95. // using the ID assigned during combined index creation.
  96. if (UseSourceFilenameForPromotedLocals &&
  97. !SGV->getParent()->getSourceFileName().empty()) {
  98. SmallString<256> Suffix(SGV->getParent()->getSourceFileName());
  99. std::replace_if(std::begin(Suffix), std::end(Suffix),
  100. [&](char ch) { return !isAlnum(ch); }, '_');
  101. return ModuleSummaryIndex::getGlobalNameForLocal(
  102. SGV->getName(), Suffix);
  103. }
  104. return ModuleSummaryIndex::getGlobalNameForLocal(
  105. SGV->getName(),
  106. ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
  107. }
  108. GlobalValue::LinkageTypes
  109. FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
  110. bool DoPromote) {
  111. // Any local variable that is referenced by an exported function needs
  112. // to be promoted to global scope. Since we don't currently know which
  113. // functions reference which local variables/functions, we must treat
  114. // all as potentially exported if this module is exporting anything.
  115. if (isModuleExporting()) {
  116. if (SGV->hasLocalLinkage() && DoPromote)
  117. return GlobalValue::ExternalLinkage;
  118. return SGV->getLinkage();
  119. }
  120. // Otherwise, if we aren't importing, no linkage change is needed.
  121. if (!isPerformingImport())
  122. return SGV->getLinkage();
  123. switch (SGV->getLinkage()) {
  124. case GlobalValue::LinkOnceODRLinkage:
  125. case GlobalValue::ExternalLinkage:
  126. // External and linkonce definitions are converted to available_externally
  127. // definitions upon import, so that they are available for inlining
  128. // and/or optimization, but are turned into declarations later
  129. // during the EliminateAvailableExternally pass.
  130. if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
  131. return GlobalValue::AvailableExternallyLinkage;
  132. // An imported external declaration stays external.
  133. return SGV->getLinkage();
  134. case GlobalValue::AvailableExternallyLinkage:
  135. // An imported available_externally definition converts
  136. // to external if imported as a declaration.
  137. if (!doImportAsDefinition(SGV))
  138. return GlobalValue::ExternalLinkage;
  139. // An imported available_externally declaration stays that way.
  140. return SGV->getLinkage();
  141. case GlobalValue::LinkOnceAnyLinkage:
  142. case GlobalValue::WeakAnyLinkage:
  143. // Can't import linkonce_any/weak_any definitions correctly, or we might
  144. // change the program semantics, since the linker will pick the first
  145. // linkonce_any/weak_any definition and importing would change the order
  146. // they are seen by the linker. The module linking caller needs to enforce
  147. // this.
  148. assert(!doImportAsDefinition(SGV));
  149. // If imported as a declaration, it becomes external_weak.
  150. return SGV->getLinkage();
  151. case GlobalValue::WeakODRLinkage:
  152. // For weak_odr linkage, there is a guarantee that all copies will be
  153. // equivalent, so the issue described above for weak_any does not exist,
  154. // and the definition can be imported. It can be treated similarly
  155. // to an imported externally visible global value.
  156. if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
  157. return GlobalValue::AvailableExternallyLinkage;
  158. else
  159. return GlobalValue::ExternalLinkage;
  160. case GlobalValue::AppendingLinkage:
  161. // It would be incorrect to import an appending linkage variable,
  162. // since it would cause global constructors/destructors to be
  163. // executed multiple times. This should have already been handled
  164. // by linkIfNeeded, and we will assert in shouldLinkFromSource
  165. // if we try to import, so we simply return AppendingLinkage.
  166. return GlobalValue::AppendingLinkage;
  167. case GlobalValue::InternalLinkage:
  168. case GlobalValue::PrivateLinkage:
  169. // If we are promoting the local to global scope, it is handled
  170. // similarly to a normal externally visible global.
  171. if (DoPromote) {
  172. if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
  173. return GlobalValue::AvailableExternallyLinkage;
  174. else
  175. return GlobalValue::ExternalLinkage;
  176. }
  177. // A non-promoted imported local definition stays local.
  178. // The ThinLTO pass will eventually force-import their definitions.
  179. return SGV->getLinkage();
  180. case GlobalValue::ExternalWeakLinkage:
  181. // External weak doesn't apply to definitions, must be a declaration.
  182. assert(!doImportAsDefinition(SGV));
  183. // Linkage stays external_weak.
  184. return SGV->getLinkage();
  185. case GlobalValue::CommonLinkage:
  186. // Linkage stays common on definitions.
  187. // The ThinLTO pass will eventually force-import their definitions.
  188. return SGV->getLinkage();
  189. }
  190. llvm_unreachable("unknown linkage type");
  191. }
  192. void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
  193. ValueInfo VI;
  194. if (GV.hasName()) {
  195. VI = ImportIndex.getValueInfo(GV.getGUID());
  196. // Set synthetic function entry counts.
  197. if (VI && ImportIndex.hasSyntheticEntryCounts()) {
  198. if (Function *F = dyn_cast<Function>(&GV)) {
  199. if (!F->isDeclaration()) {
  200. for (const auto &S : VI.getSummaryList()) {
  201. auto *FS = cast<FunctionSummary>(S->getBaseObject());
  202. if (FS->modulePath() == M.getModuleIdentifier()) {
  203. F->setEntryCount(Function::ProfileCount(FS->entryCount(),
  204. Function::PCT_Synthetic));
  205. break;
  206. }
  207. }
  208. }
  209. }
  210. }
  211. }
  212. // We should always have a ValueInfo (i.e. GV in index) for definitions when
  213. // we are exporting, and also when importing that value.
  214. assert(VI || GV.isDeclaration() ||
  215. (isPerformingImport() && !doImportAsDefinition(&GV)));
  216. // Mark read/write-only variables which can be imported with specific
  217. // attribute. We can't internalize them now because IRMover will fail
  218. // to link variable definitions to their external declarations during
  219. // ThinLTO import. We'll internalize read-only variables later, after
  220. // import is finished. See internalizeGVsAfterImport.
  221. //
  222. // If global value dead stripping is not enabled in summary then
  223. // propagateConstants hasn't been run. We can't internalize GV
  224. // in such case.
  225. if (!GV.isDeclaration() && VI && ImportIndex.withAttributePropagation()) {
  226. if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
  227. // We can have more than one local with the same GUID, in the case of
  228. // same-named locals in different but same-named source files that were
  229. // compiled in their respective directories (so the source file name
  230. // and resulting GUID is the same). Find the one in this module.
  231. // Handle the case where there is no summary found in this module. That
  232. // can happen in the distributed ThinLTO backend, because the index only
  233. // contains summaries from the source modules if they are being imported.
  234. // We might have a non-null VI and get here even in that case if the name
  235. // matches one in this module (e.g. weak or appending linkage).
  236. auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
  237. ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
  238. if (GVS &&
  239. (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) {
  240. V->addAttribute("thinlto-internalize");
  241. // Objects referenced by writeonly GV initializer should not be
  242. // promoted, because there is no any kind of read access to them
  243. // on behalf of this writeonly GV. To avoid promotion we convert
  244. // GV initializer to 'zeroinitializer'. This effectively drops
  245. // references in IR module (not in combined index), so we can
  246. // ignore them when computing import. We do not export references
  247. // of writeonly object. See computeImportForReferencedGlobals
  248. if (ImportIndex.isWriteOnly(GVS))
  249. V->setInitializer(Constant::getNullValue(V->getValueType()));
  250. }
  251. }
  252. }
  253. if (GV.hasLocalLinkage() && shouldPromoteLocalToGlobal(&GV, VI)) {
  254. // Save the original name string before we rename GV below.
  255. auto Name = GV.getName().str();
  256. GV.setName(getPromotedName(&GV));
  257. GV.setLinkage(getLinkage(&GV, /* DoPromote */ true));
  258. assert(!GV.hasLocalLinkage());
  259. GV.setVisibility(GlobalValue::HiddenVisibility);
  260. // If we are renaming a COMDAT leader, ensure that we record the COMDAT
  261. // for later renaming as well. This is required for COFF.
  262. if (const auto *C = GV.getComdat())
  263. if (C->getName() == Name)
  264. RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
  265. } else
  266. GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
  267. // When ClearDSOLocalOnDeclarations is true, clear dso_local if GV is
  268. // converted to a declaration, to disable direct access. Don't do this if GV
  269. // is implicitly dso_local due to a non-default visibility.
  270. if (ClearDSOLocalOnDeclarations &&
  271. (GV.isDeclarationForLinker() ||
  272. (isPerformingImport() && !doImportAsDefinition(&GV))) &&
  273. !GV.isImplicitDSOLocal()) {
  274. GV.setDSOLocal(false);
  275. } else if (VI && VI.isDSOLocal(ImportIndex.withDSOLocalPropagation())) {
  276. // If all summaries are dso_local, symbol gets resolved to a known local
  277. // definition.
  278. GV.setDSOLocal(true);
  279. if (GV.hasDLLImportStorageClass())
  280. GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
  281. }
  282. // Remove functions imported as available externally defs from comdats,
  283. // as this is a declaration for the linker, and will be dropped eventually.
  284. // It is illegal for comdats to contain declarations.
  285. auto *GO = dyn_cast<GlobalObject>(&GV);
  286. if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
  287. // The IRMover should not have placed any imported declarations in
  288. // a comdat, so the only declaration that should be in a comdat
  289. // at this point would be a definition imported as available_externally.
  290. assert(GO->hasAvailableExternallyLinkage() &&
  291. "Expected comdat on definition (possibly available external)");
  292. GO->setComdat(nullptr);
  293. }
  294. }
  295. void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
  296. for (GlobalVariable &GV : M.globals())
  297. processGlobalForThinLTO(GV);
  298. for (Function &SF : M)
  299. processGlobalForThinLTO(SF);
  300. for (GlobalAlias &GA : M.aliases())
  301. processGlobalForThinLTO(GA);
  302. // Replace any COMDATS that required renaming (because the COMDAT leader was
  303. // promoted and renamed).
  304. if (!RenamedComdats.empty())
  305. for (auto &GO : M.global_objects())
  306. if (auto *C = GO.getComdat()) {
  307. auto Replacement = RenamedComdats.find(C);
  308. if (Replacement != RenamedComdats.end())
  309. GO.setComdat(Replacement->second);
  310. }
  311. }
  312. bool FunctionImportGlobalProcessing::run() {
  313. processGlobalsForThinLTO();
  314. return false;
  315. }
  316. bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
  317. bool ClearDSOLocalOnDeclarations,
  318. SetVector<GlobalValue *> *GlobalsToImport) {
  319. FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport,
  320. ClearDSOLocalOnDeclarations);
  321. return ThinLTOProcessing.run();
  322. }