FunctionImportUtils.cpp 14 KB

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