10b57cec5SDimitry Andric //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the FunctionImportGlobalProcessing class, used
100b57cec5SDimitry Andric // to perform the necessary global value handling for function importing.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Transforms/Utils/FunctionImportUtils.h"
150b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
160b57cec5SDimitry Andric using namespace llvm;
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric /// Checks if we should import SGV as a definition, otherwise import as a
190b57cec5SDimitry Andric /// declaration.
200b57cec5SDimitry Andric bool FunctionImportGlobalProcessing::doImportAsDefinition(
210b57cec5SDimitry Andric     const GlobalValue *SGV, SetVector<GlobalValue *> *GlobalsToImport) {
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric   // Only import the globals requested for importing.
240b57cec5SDimitry Andric   if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
250b57cec5SDimitry Andric     return false;
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric   assert(!isa<GlobalAlias>(SGV) &&
280b57cec5SDimitry Andric          "Unexpected global alias in the import list.");
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric   // Otherwise yes.
310b57cec5SDimitry Andric   return true;
320b57cec5SDimitry Andric }
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric bool FunctionImportGlobalProcessing::doImportAsDefinition(
350b57cec5SDimitry Andric     const GlobalValue *SGV) {
360b57cec5SDimitry Andric   if (!isPerformingImport())
370b57cec5SDimitry Andric     return false;
380b57cec5SDimitry Andric   return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
390b57cec5SDimitry Andric                                                               GlobalsToImport);
400b57cec5SDimitry Andric }
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
430b57cec5SDimitry Andric     const GlobalValue *SGV) {
440b57cec5SDimitry Andric   assert(SGV->hasLocalLinkage());
450b57cec5SDimitry Andric   // Both the imported references and the original local variable must
460b57cec5SDimitry Andric   // be promoted.
470b57cec5SDimitry Andric   if (!isPerformingImport() && !isModuleExporting())
480b57cec5SDimitry Andric     return false;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   if (isPerformingImport()) {
510b57cec5SDimitry Andric     assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
520b57cec5SDimitry Andric             !isNonRenamableLocal(*SGV)) &&
530b57cec5SDimitry Andric            "Attempting to promote non-renamable local");
540b57cec5SDimitry Andric     // We don't know for sure yet if we are importing this value (as either
550b57cec5SDimitry Andric     // a reference or a def), since we are simply walking all values in the
560b57cec5SDimitry Andric     // module. But by necessity if we end up importing it and it is local,
570b57cec5SDimitry Andric     // it must be promoted, so unconditionally promote all values in the
580b57cec5SDimitry Andric     // importing module.
590b57cec5SDimitry Andric     return true;
600b57cec5SDimitry Andric   }
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   // When exporting, consult the index. We can have more than one local
630b57cec5SDimitry Andric   // with the same GUID, in the case of same-named locals in different but
640b57cec5SDimitry Andric   // same-named source files that were compiled in their respective directories
650b57cec5SDimitry Andric   // (so the source file name and resulting GUID is the same). Find the one
660b57cec5SDimitry Andric   // in this module.
670b57cec5SDimitry Andric   auto Summary = ImportIndex.findSummaryInModule(
680b57cec5SDimitry Andric       SGV->getGUID(), SGV->getParent()->getModuleIdentifier());
690b57cec5SDimitry Andric   assert(Summary && "Missing summary for global value when exporting");
700b57cec5SDimitry Andric   auto Linkage = Summary->linkage();
710b57cec5SDimitry Andric   if (!GlobalValue::isLocalLinkage(Linkage)) {
720b57cec5SDimitry Andric     assert(!isNonRenamableLocal(*SGV) &&
730b57cec5SDimitry Andric            "Attempting to promote non-renamable local");
740b57cec5SDimitry Andric     return true;
750b57cec5SDimitry Andric   }
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric   return false;
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric #ifndef NDEBUG
810b57cec5SDimitry Andric bool FunctionImportGlobalProcessing::isNonRenamableLocal(
820b57cec5SDimitry Andric     const GlobalValue &GV) const {
830b57cec5SDimitry Andric   if (!GV.hasLocalLinkage())
840b57cec5SDimitry Andric     return false;
850b57cec5SDimitry Andric   // This needs to stay in sync with the logic in buildModuleSummaryIndex.
860b57cec5SDimitry Andric   if (GV.hasSection())
870b57cec5SDimitry Andric     return true;
880b57cec5SDimitry Andric   if (Used.count(const_cast<GlobalValue *>(&GV)))
890b57cec5SDimitry Andric     return true;
900b57cec5SDimitry Andric   return false;
910b57cec5SDimitry Andric }
920b57cec5SDimitry Andric #endif
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric std::string FunctionImportGlobalProcessing::getName(const GlobalValue *SGV,
950b57cec5SDimitry Andric                                                     bool DoPromote) {
960b57cec5SDimitry Andric   // For locals that must be promoted to global scope, ensure that
970b57cec5SDimitry Andric   // the promoted name uniquely identifies the copy in the original module,
980b57cec5SDimitry Andric   // using the ID assigned during combined index creation. When importing,
990b57cec5SDimitry Andric   // we rename all locals (not just those that are promoted) in order to
1000b57cec5SDimitry Andric   // avoid naming conflicts between locals imported from different modules.
1010b57cec5SDimitry Andric   if (SGV->hasLocalLinkage() && (DoPromote || isPerformingImport()))
1020b57cec5SDimitry Andric     return ModuleSummaryIndex::getGlobalNameForLocal(
1030b57cec5SDimitry Andric         SGV->getName(),
1040b57cec5SDimitry Andric         ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
1050b57cec5SDimitry Andric   return SGV->getName();
1060b57cec5SDimitry Andric }
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric GlobalValue::LinkageTypes
1090b57cec5SDimitry Andric FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
1100b57cec5SDimitry Andric                                            bool DoPromote) {
1110b57cec5SDimitry Andric   // Any local variable that is referenced by an exported function needs
1120b57cec5SDimitry Andric   // to be promoted to global scope. Since we don't currently know which
1130b57cec5SDimitry Andric   // functions reference which local variables/functions, we must treat
1140b57cec5SDimitry Andric   // all as potentially exported if this module is exporting anything.
1150b57cec5SDimitry Andric   if (isModuleExporting()) {
1160b57cec5SDimitry Andric     if (SGV->hasLocalLinkage() && DoPromote)
1170b57cec5SDimitry Andric       return GlobalValue::ExternalLinkage;
1180b57cec5SDimitry Andric     return SGV->getLinkage();
1190b57cec5SDimitry Andric   }
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   // Otherwise, if we aren't importing, no linkage change is needed.
1220b57cec5SDimitry Andric   if (!isPerformingImport())
1230b57cec5SDimitry Andric     return SGV->getLinkage();
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   switch (SGV->getLinkage()) {
1260b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
1270b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
1280b57cec5SDimitry Andric     // External and linkonce definitions are converted to available_externally
1290b57cec5SDimitry Andric     // definitions upon import, so that they are available for inlining
1300b57cec5SDimitry Andric     // and/or optimization, but are turned into declarations later
1310b57cec5SDimitry Andric     // during the EliminateAvailableExternally pass.
1320b57cec5SDimitry Andric     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
1330b57cec5SDimitry Andric       return GlobalValue::AvailableExternallyLinkage;
1340b57cec5SDimitry Andric     // An imported external declaration stays external.
1350b57cec5SDimitry Andric     return SGV->getLinkage();
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
1380b57cec5SDimitry Andric     // An imported available_externally definition converts
1390b57cec5SDimitry Andric     // to external if imported as a declaration.
1400b57cec5SDimitry Andric     if (!doImportAsDefinition(SGV))
1410b57cec5SDimitry Andric       return GlobalValue::ExternalLinkage;
1420b57cec5SDimitry Andric     // An imported available_externally declaration stays that way.
1430b57cec5SDimitry Andric     return SGV->getLinkage();
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
1460b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
1470b57cec5SDimitry Andric     // Can't import linkonce_any/weak_any definitions correctly, or we might
1480b57cec5SDimitry Andric     // change the program semantics, since the linker will pick the first
1490b57cec5SDimitry Andric     // linkonce_any/weak_any definition and importing would change the order
1500b57cec5SDimitry Andric     // they are seen by the linker. The module linking caller needs to enforce
1510b57cec5SDimitry Andric     // this.
1520b57cec5SDimitry Andric     assert(!doImportAsDefinition(SGV));
1530b57cec5SDimitry Andric     // If imported as a declaration, it becomes external_weak.
1540b57cec5SDimitry Andric     return SGV->getLinkage();
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
1570b57cec5SDimitry Andric     // For weak_odr linkage, there is a guarantee that all copies will be
1580b57cec5SDimitry Andric     // equivalent, so the issue described above for weak_any does not exist,
1590b57cec5SDimitry Andric     // and the definition can be imported. It can be treated similarly
1600b57cec5SDimitry Andric     // to an imported externally visible global value.
1610b57cec5SDimitry Andric     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
1620b57cec5SDimitry Andric       return GlobalValue::AvailableExternallyLinkage;
1630b57cec5SDimitry Andric     else
1640b57cec5SDimitry Andric       return GlobalValue::ExternalLinkage;
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
1670b57cec5SDimitry Andric     // It would be incorrect to import an appending linkage variable,
1680b57cec5SDimitry Andric     // since it would cause global constructors/destructors to be
1690b57cec5SDimitry Andric     // executed multiple times. This should have already been handled
1700b57cec5SDimitry Andric     // by linkIfNeeded, and we will assert in shouldLinkFromSource
1710b57cec5SDimitry Andric     // if we try to import, so we simply return AppendingLinkage.
1720b57cec5SDimitry Andric     return GlobalValue::AppendingLinkage;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
1750b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
1760b57cec5SDimitry Andric     // If we are promoting the local to global scope, it is handled
1770b57cec5SDimitry Andric     // similarly to a normal externally visible global.
1780b57cec5SDimitry Andric     if (DoPromote) {
1790b57cec5SDimitry Andric       if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
1800b57cec5SDimitry Andric         return GlobalValue::AvailableExternallyLinkage;
1810b57cec5SDimitry Andric       else
1820b57cec5SDimitry Andric         return GlobalValue::ExternalLinkage;
1830b57cec5SDimitry Andric     }
1840b57cec5SDimitry Andric     // A non-promoted imported local definition stays local.
1850b57cec5SDimitry Andric     // The ThinLTO pass will eventually force-import their definitions.
1860b57cec5SDimitry Andric     return SGV->getLinkage();
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
1890b57cec5SDimitry Andric     // External weak doesn't apply to definitions, must be a declaration.
1900b57cec5SDimitry Andric     assert(!doImportAsDefinition(SGV));
1910b57cec5SDimitry Andric     // Linkage stays external_weak.
1920b57cec5SDimitry Andric     return SGV->getLinkage();
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
1950b57cec5SDimitry Andric     // Linkage stays common on definitions.
1960b57cec5SDimitry Andric     // The ThinLTO pass will eventually force-import their definitions.
1970b57cec5SDimitry Andric     return SGV->getLinkage();
1980b57cec5SDimitry Andric   }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   llvm_unreachable("unknown linkage type");
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   ValueInfo VI;
2060b57cec5SDimitry Andric   if (GV.hasName()) {
2070b57cec5SDimitry Andric     VI = ImportIndex.getValueInfo(GV.getGUID());
2080b57cec5SDimitry Andric     // Set synthetic function entry counts.
2090b57cec5SDimitry Andric     if (VI && ImportIndex.hasSyntheticEntryCounts()) {
2100b57cec5SDimitry Andric       if (Function *F = dyn_cast<Function>(&GV)) {
2110b57cec5SDimitry Andric         if (!F->isDeclaration()) {
2120b57cec5SDimitry Andric           for (auto &S : VI.getSummaryList()) {
2130b57cec5SDimitry Andric             FunctionSummary *FS = dyn_cast<FunctionSummary>(S->getBaseObject());
2140b57cec5SDimitry Andric             if (FS->modulePath() == M.getModuleIdentifier()) {
2150b57cec5SDimitry Andric               F->setEntryCount(Function::ProfileCount(FS->entryCount(),
2160b57cec5SDimitry Andric                                                       Function::PCT_Synthetic));
2170b57cec5SDimitry Andric               break;
2180b57cec5SDimitry Andric             }
2190b57cec5SDimitry Andric           }
2200b57cec5SDimitry Andric         }
2210b57cec5SDimitry Andric       }
2220b57cec5SDimitry Andric     }
2230b57cec5SDimitry Andric     // Check the summaries to see if the symbol gets resolved to a known local
2240b57cec5SDimitry Andric     // definition.
2250b57cec5SDimitry Andric     if (VI && VI.isDSOLocal()) {
2260b57cec5SDimitry Andric       GV.setDSOLocal(true);
2270b57cec5SDimitry Andric       if (GV.hasDLLImportStorageClass())
2280b57cec5SDimitry Andric         GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
2290b57cec5SDimitry Andric     }
2300b57cec5SDimitry Andric   }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   // Mark read/write-only variables which can be imported with specific
2330b57cec5SDimitry Andric   // attribute. We can't internalize them now because IRMover will fail
2340b57cec5SDimitry Andric   // to link variable definitions to their external declarations during
2350b57cec5SDimitry Andric   // ThinLTO import. We'll internalize read-only variables later, after
2360b57cec5SDimitry Andric   // import is finished. See internalizeGVsAfterImport.
2370b57cec5SDimitry Andric   //
2380b57cec5SDimitry Andric   // If global value dead stripping is not enabled in summary then
2390b57cec5SDimitry Andric   // propagateConstants hasn't been run. We can't internalize GV
2400b57cec5SDimitry Andric   // in such case.
2410b57cec5SDimitry Andric   if (!GV.isDeclaration() && VI && ImportIndex.withGlobalValueDeadStripping()) {
2420b57cec5SDimitry Andric     const auto &SL = VI.getSummaryList();
2430b57cec5SDimitry Andric     auto *GVS = SL.empty() ? nullptr : dyn_cast<GlobalVarSummary>(SL[0].get());
2440b57cec5SDimitry Andric     // At this stage "maybe" is "definitely"
2450b57cec5SDimitry Andric     if (GVS && (GVS->maybeReadOnly() || GVS->maybeWriteOnly()))
2460b57cec5SDimitry Andric       cast<GlobalVariable>(&GV)->addAttribute("thinlto-internalize");
2470b57cec5SDimitry Andric   }
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   bool DoPromote = false;
2500b57cec5SDimitry Andric   if (GV.hasLocalLinkage() &&
2510b57cec5SDimitry Andric       ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) {
2520b57cec5SDimitry Andric     // Save the original name string before we rename GV below.
2530b57cec5SDimitry Andric     auto Name = GV.getName().str();
2540b57cec5SDimitry Andric     // Once we change the name or linkage it is difficult to determine
2550b57cec5SDimitry Andric     // again whether we should promote since shouldPromoteLocalToGlobal needs
2560b57cec5SDimitry Andric     // to locate the summary (based on GUID from name and linkage). Therefore,
2570b57cec5SDimitry Andric     // use DoPromote result saved above.
2580b57cec5SDimitry Andric     GV.setName(getName(&GV, DoPromote));
2590b57cec5SDimitry Andric     GV.setLinkage(getLinkage(&GV, DoPromote));
2600b57cec5SDimitry Andric     if (!GV.hasLocalLinkage())
2610b57cec5SDimitry Andric       GV.setVisibility(GlobalValue::HiddenVisibility);
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     // If we are renaming a COMDAT leader, ensure that we record the COMDAT
2640b57cec5SDimitry Andric     // for later renaming as well. This is required for COFF.
2650b57cec5SDimitry Andric     if (const auto *C = GV.getComdat())
2660b57cec5SDimitry Andric       if (C->getName() == Name)
2670b57cec5SDimitry Andric         RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
2680b57cec5SDimitry Andric   } else
2690b57cec5SDimitry Andric     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   // Remove functions imported as available externally defs from comdats,
2720b57cec5SDimitry Andric   // as this is a declaration for the linker, and will be dropped eventually.
2730b57cec5SDimitry Andric   // It is illegal for comdats to contain declarations.
2740b57cec5SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(&GV);
2750b57cec5SDimitry Andric   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
2760b57cec5SDimitry Andric     // The IRMover should not have placed any imported declarations in
2770b57cec5SDimitry Andric     // a comdat, so the only declaration that should be in a comdat
2780b57cec5SDimitry Andric     // at this point would be a definition imported as available_externally.
2790b57cec5SDimitry Andric     assert(GO->hasAvailableExternallyLinkage() &&
2800b57cec5SDimitry Andric            "Expected comdat on definition (possibly available external)");
2810b57cec5SDimitry Andric     GO->setComdat(nullptr);
2820b57cec5SDimitry Andric   }
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
2860b57cec5SDimitry Andric   for (GlobalVariable &GV : M.globals())
2870b57cec5SDimitry Andric     processGlobalForThinLTO(GV);
2880b57cec5SDimitry Andric   for (Function &SF : M)
2890b57cec5SDimitry Andric     processGlobalForThinLTO(SF);
2900b57cec5SDimitry Andric   for (GlobalAlias &GA : M.aliases())
2910b57cec5SDimitry Andric     processGlobalForThinLTO(GA);
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   // Replace any COMDATS that required renaming (because the COMDAT leader was
2940b57cec5SDimitry Andric   // promoted and renamed).
2950b57cec5SDimitry Andric   if (!RenamedComdats.empty())
2960b57cec5SDimitry Andric     for (auto &GO : M.global_objects())
2970b57cec5SDimitry Andric       if (auto *C = GO.getComdat()) {
2980b57cec5SDimitry Andric         auto Replacement = RenamedComdats.find(C);
2990b57cec5SDimitry Andric         if (Replacement != RenamedComdats.end())
3000b57cec5SDimitry Andric           GO.setComdat(Replacement->second);
3010b57cec5SDimitry Andric       }
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric bool FunctionImportGlobalProcessing::run() {
3050b57cec5SDimitry Andric   processGlobalsForThinLTO();
3060b57cec5SDimitry Andric   return false;
3070b57cec5SDimitry Andric }
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
3100b57cec5SDimitry Andric                                   SetVector<GlobalValue *> *GlobalsToImport) {
3110b57cec5SDimitry Andric   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
3120b57cec5SDimitry Andric   return ThinLTOProcessing.run();
3130b57cec5SDimitry Andric }
314