1488a800aSTeresa Johnson //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
2488a800aSTeresa Johnson //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6488a800aSTeresa Johnson //
7488a800aSTeresa Johnson //===----------------------------------------------------------------------===//
8488a800aSTeresa Johnson //
9488a800aSTeresa Johnson // This file implements the FunctionImportGlobalProcessing class, used
10488a800aSTeresa Johnson // to perform the necessary global value handling for function importing.
11488a800aSTeresa Johnson //
12488a800aSTeresa Johnson //===----------------------------------------------------------------------===//
13488a800aSTeresa Johnson 
14488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
157f92d66fSevgeny #include "llvm/IR/Constants.h"
16df5ef871STeresa Johnson #include "llvm/IR/InstIterator.h"
17488a800aSTeresa Johnson using namespace llvm;
18488a800aSTeresa Johnson 
19488a800aSTeresa Johnson /// Checks if we should import SGV as a definition, otherwise import as a
20488a800aSTeresa Johnson /// declaration.
21488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::doImportAsDefinition(
226d8f817fSPeter Collingbourne     const GlobalValue *SGV, SetVector<GlobalValue *> *GlobalsToImport) {
238d05185aSMehdi Amini 
248d05185aSMehdi Amini   // Only import the globals requested for importing.
2572c0b1ccSDavid Blaikie   if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
2672c0b1ccSDavid Blaikie     return false;
272f0cc477SDavid Blaikie 
282f0cc477SDavid Blaikie   assert(!isa<GlobalAlias>(SGV) &&
292f0cc477SDavid Blaikie          "Unexpected global alias in the import list.");
302f0cc477SDavid Blaikie 
3172c0b1ccSDavid Blaikie   // Otherwise yes.
3272c0b1ccSDavid Blaikie   return true;
33488a800aSTeresa Johnson }
34488a800aSTeresa Johnson 
35488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::doImportAsDefinition(
36488a800aSTeresa Johnson     const GlobalValue *SGV) {
37488a800aSTeresa Johnson   if (!isPerformingImport())
38488a800aSTeresa Johnson     return false;
398d05185aSMehdi Amini   return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
408d05185aSMehdi Amini                                                               GlobalsToImport);
41488a800aSTeresa Johnson }
42488a800aSTeresa Johnson 
4338d4df71STeresa Johnson bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
44488a800aSTeresa Johnson     const GlobalValue *SGV) {
45488a800aSTeresa Johnson   assert(SGV->hasLocalLinkage());
46488a800aSTeresa Johnson   // Both the imported references and the original local variable must
47488a800aSTeresa Johnson   // be promoted.
48488a800aSTeresa Johnson   if (!isPerformingImport() && !isModuleExporting())
49488a800aSTeresa Johnson     return false;
50488a800aSTeresa Johnson 
514fef68cbSTeresa Johnson   if (isPerformingImport()) {
526d8f817fSPeter Collingbourne     assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
536d8f817fSPeter Collingbourne             !isNonRenamableLocal(*SGV)) &&
54519465b9STeresa Johnson            "Attempting to promote non-renamable local");
554fef68cbSTeresa Johnson     // We don't know for sure yet if we are importing this value (as either
564fef68cbSTeresa Johnson     // a reference or a def), since we are simply walking all values in the
574fef68cbSTeresa Johnson     // module. But by necessity if we end up importing it and it is local,
584fef68cbSTeresa Johnson     // it must be promoted, so unconditionally promote all values in the
594fef68cbSTeresa Johnson     // importing module.
604fef68cbSTeresa Johnson     return true;
610515fb8dSTeresa Johnson   }
62b4e1e829SMehdi Amini 
639006d526STeresa Johnson   // When exporting, consult the index. We can have more than one local
649006d526STeresa Johnson   // with the same GUID, in the case of same-named locals in different but
659006d526STeresa Johnson   // same-named source files that were compiled in their respective directories
669006d526STeresa Johnson   // (so the source file name and resulting GUID is the same). Find the one
679006d526STeresa Johnson   // in this module.
689006d526STeresa Johnson   auto Summary = ImportIndex.findSummaryInModule(
699006d526STeresa Johnson       SGV->getGUID(), SGV->getParent()->getModuleIdentifier());
709006d526STeresa Johnson   assert(Summary && "Missing summary for global value when exporting");
719006d526STeresa Johnson   auto Linkage = Summary->linkage();
724fef68cbSTeresa Johnson   if (!GlobalValue::isLocalLinkage(Linkage)) {
73519465b9STeresa Johnson     assert(!isNonRenamableLocal(*SGV) &&
74519465b9STeresa Johnson            "Attempting to promote non-renamable local");
75488a800aSTeresa Johnson     return true;
76488a800aSTeresa Johnson   }
77488a800aSTeresa Johnson 
784fef68cbSTeresa Johnson   return false;
794fef68cbSTeresa Johnson }
804fef68cbSTeresa Johnson 
81519465b9STeresa Johnson #ifndef NDEBUG
82519465b9STeresa Johnson bool FunctionImportGlobalProcessing::isNonRenamableLocal(
83519465b9STeresa Johnson     const GlobalValue &GV) const {
84519465b9STeresa Johnson   if (!GV.hasLocalLinkage())
85519465b9STeresa Johnson     return false;
86519465b9STeresa Johnson   // This needs to stay in sync with the logic in buildModuleSummaryIndex.
87519465b9STeresa Johnson   if (GV.hasSection())
88519465b9STeresa Johnson     return true;
89519465b9STeresa Johnson   if (Used.count(const_cast<GlobalValue *>(&GV)))
90519465b9STeresa Johnson     return true;
91519465b9STeresa Johnson   return false;
92519465b9STeresa Johnson }
93519465b9STeresa Johnson #endif
94519465b9STeresa Johnson 
95*3be6dbcaSTeresa Johnson std::string
96*3be6dbcaSTeresa Johnson FunctionImportGlobalProcessing::getPromotedName(const GlobalValue *SGV) {
97*3be6dbcaSTeresa Johnson   assert(SGV->hasLocalLinkage());
98488a800aSTeresa Johnson   // For locals that must be promoted to global scope, ensure that
99488a800aSTeresa Johnson   // the promoted name uniquely identifies the copy in the original module,
100*3be6dbcaSTeresa Johnson   // using the ID assigned during combined index creation.
10126ab5772STeresa Johnson   return ModuleSummaryIndex::getGlobalNameForLocal(
102488a800aSTeresa Johnson       SGV->getName(),
103ae280e54SMehdi Amini       ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
104488a800aSTeresa Johnson }
105488a800aSTeresa Johnson 
106488a800aSTeresa Johnson GlobalValue::LinkageTypes
1071b9c2be8STeresa Johnson FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
1081b9c2be8STeresa Johnson                                            bool DoPromote) {
109488a800aSTeresa Johnson   // Any local variable that is referenced by an exported function needs
110488a800aSTeresa Johnson   // to be promoted to global scope. Since we don't currently know which
111488a800aSTeresa Johnson   // functions reference which local variables/functions, we must treat
112488a800aSTeresa Johnson   // all as potentially exported if this module is exporting anything.
113488a800aSTeresa Johnson   if (isModuleExporting()) {
1141b9c2be8STeresa Johnson     if (SGV->hasLocalLinkage() && DoPromote)
115488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
116488a800aSTeresa Johnson     return SGV->getLinkage();
117488a800aSTeresa Johnson   }
118488a800aSTeresa Johnson 
119488a800aSTeresa Johnson   // Otherwise, if we aren't importing, no linkage change is needed.
120488a800aSTeresa Johnson   if (!isPerformingImport())
121488a800aSTeresa Johnson     return SGV->getLinkage();
122488a800aSTeresa Johnson 
123488a800aSTeresa Johnson   switch (SGV->getLinkage()) {
1242f0cc477SDavid Blaikie   case GlobalValue::LinkOnceODRLinkage:
125488a800aSTeresa Johnson   case GlobalValue::ExternalLinkage:
1262f0cc477SDavid Blaikie     // External and linkonce definitions are converted to available_externally
127488a800aSTeresa Johnson     // definitions upon import, so that they are available for inlining
128488a800aSTeresa Johnson     // and/or optimization, but are turned into declarations later
129488a800aSTeresa Johnson     // during the EliminateAvailableExternally pass.
1302c5c12c0SFangrui Song     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
131488a800aSTeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
132488a800aSTeresa Johnson     // An imported external declaration stays external.
133488a800aSTeresa Johnson     return SGV->getLinkage();
134488a800aSTeresa Johnson 
135488a800aSTeresa Johnson   case GlobalValue::AvailableExternallyLinkage:
136488a800aSTeresa Johnson     // An imported available_externally definition converts
137488a800aSTeresa Johnson     // to external if imported as a declaration.
138488a800aSTeresa Johnson     if (!doImportAsDefinition(SGV))
139488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
140488a800aSTeresa Johnson     // An imported available_externally declaration stays that way.
141488a800aSTeresa Johnson     return SGV->getLinkage();
142488a800aSTeresa Johnson 
14353e52e47SXin Tong   case GlobalValue::LinkOnceAnyLinkage:
144488a800aSTeresa Johnson   case GlobalValue::WeakAnyLinkage:
14553e52e47SXin Tong     // Can't import linkonce_any/weak_any definitions correctly, or we might
14653e52e47SXin Tong     // change the program semantics, since the linker will pick the first
14753e52e47SXin Tong     // linkonce_any/weak_any definition and importing would change the order
14853e52e47SXin Tong     // they are seen by the linker. The module linking caller needs to enforce
14953e52e47SXin Tong     // this.
150488a800aSTeresa Johnson     assert(!doImportAsDefinition(SGV));
151488a800aSTeresa Johnson     // If imported as a declaration, it becomes external_weak.
152bb3a1d92SMehdi Amini     return SGV->getLinkage();
153488a800aSTeresa Johnson 
154488a800aSTeresa Johnson   case GlobalValue::WeakODRLinkage:
155488a800aSTeresa Johnson     // For weak_odr linkage, there is a guarantee that all copies will be
156488a800aSTeresa Johnson     // equivalent, so the issue described above for weak_any does not exist,
157488a800aSTeresa Johnson     // and the definition can be imported. It can be treated similarly
158488a800aSTeresa Johnson     // to an imported externally visible global value.
1592c5c12c0SFangrui Song     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
160488a800aSTeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
161488a800aSTeresa Johnson     else
162488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
163488a800aSTeresa Johnson 
164488a800aSTeresa Johnson   case GlobalValue::AppendingLinkage:
165488a800aSTeresa Johnson     // It would be incorrect to import an appending linkage variable,
166488a800aSTeresa Johnson     // since it would cause global constructors/destructors to be
167488a800aSTeresa Johnson     // executed multiple times. This should have already been handled
168488a800aSTeresa Johnson     // by linkIfNeeded, and we will assert in shouldLinkFromSource
169488a800aSTeresa Johnson     // if we try to import, so we simply return AppendingLinkage.
170488a800aSTeresa Johnson     return GlobalValue::AppendingLinkage;
171488a800aSTeresa Johnson 
172488a800aSTeresa Johnson   case GlobalValue::InternalLinkage:
173488a800aSTeresa Johnson   case GlobalValue::PrivateLinkage:
174488a800aSTeresa Johnson     // If we are promoting the local to global scope, it is handled
175488a800aSTeresa Johnson     // similarly to a normal externally visible global.
1761b9c2be8STeresa Johnson     if (DoPromote) {
1772c5c12c0SFangrui Song       if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
178488a800aSTeresa Johnson         return GlobalValue::AvailableExternallyLinkage;
179488a800aSTeresa Johnson       else
180488a800aSTeresa Johnson         return GlobalValue::ExternalLinkage;
181488a800aSTeresa Johnson     }
182488a800aSTeresa Johnson     // A non-promoted imported local definition stays local.
183488a800aSTeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
184488a800aSTeresa Johnson     return SGV->getLinkage();
185488a800aSTeresa Johnson 
186488a800aSTeresa Johnson   case GlobalValue::ExternalWeakLinkage:
187488a800aSTeresa Johnson     // External weak doesn't apply to definitions, must be a declaration.
188488a800aSTeresa Johnson     assert(!doImportAsDefinition(SGV));
189488a800aSTeresa Johnson     // Linkage stays external_weak.
190488a800aSTeresa Johnson     return SGV->getLinkage();
191488a800aSTeresa Johnson 
192488a800aSTeresa Johnson   case GlobalValue::CommonLinkage:
193488a800aSTeresa Johnson     // Linkage stays common on definitions.
194488a800aSTeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
195488a800aSTeresa Johnson     return SGV->getLinkage();
196488a800aSTeresa Johnson   }
197488a800aSTeresa Johnson 
198488a800aSTeresa Johnson   llvm_unreachable("unknown linkage type");
199488a800aSTeresa Johnson }
200488a800aSTeresa Johnson 
201488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
2024595a915SSean Fertile 
203bf46e741SEugene Leviant   ValueInfo VI;
2044595a915SSean Fertile   if (GV.hasName()) {
205bf46e741SEugene Leviant     VI = ImportIndex.getValueInfo(GV.getGUID());
2065a7056faSEaswaran Raman     // Set synthetic function entry counts.
2075a7056faSEaswaran Raman     if (VI && ImportIndex.hasSyntheticEntryCounts()) {
2085a7056faSEaswaran Raman       if (Function *F = dyn_cast<Function>(&GV)) {
2095a7056faSEaswaran Raman         if (!F->isDeclaration()) {
2105a7056faSEaswaran Raman           for (auto &S : VI.getSummaryList()) {
211f71f23d1SSimon Pilgrim             auto *FS = cast<FunctionSummary>(S->getBaseObject());
2125a7056faSEaswaran Raman             if (FS->modulePath() == M.getModuleIdentifier()) {
2135a7056faSEaswaran Raman               F->setEntryCount(Function::ProfileCount(FS->entryCount(),
2145a7056faSEaswaran Raman                                                       Function::PCT_Synthetic));
2155a7056faSEaswaran Raman               break;
2165a7056faSEaswaran Raman             }
2175a7056faSEaswaran Raman           }
2185a7056faSEaswaran Raman         }
2195a7056faSEaswaran Raman       }
2205a7056faSEaswaran Raman     }
2215a7056faSEaswaran Raman     // Check the summaries to see if the symbol gets resolved to a known local
2225a7056faSEaswaran Raman     // definition.
223f5220fb6SRafael Espindola     if (VI && VI.isDSOLocal()) {
2244595a915SSean Fertile       GV.setDSOLocal(true);
225f5220fb6SRafael Espindola       if (GV.hasDLLImportStorageClass())
226f5220fb6SRafael Espindola         GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
227f5220fb6SRafael Espindola     }
2284595a915SSean Fertile   }
2294595a915SSean Fertile 
2303aef3528SEugene Leviant   // Mark read/write-only variables which can be imported with specific
2313aef3528SEugene Leviant   // attribute. We can't internalize them now because IRMover will fail
2323aef3528SEugene Leviant   // to link variable definitions to their external declarations during
2333aef3528SEugene Leviant   // ThinLTO import. We'll internalize read-only variables later, after
2343aef3528SEugene Leviant   // import is finished. See internalizeGVsAfterImport.
235bf46e741SEugene Leviant   //
236bf46e741SEugene Leviant   // If global value dead stripping is not enabled in summary then
237bf46e741SEugene Leviant   // propagateConstants hasn't been run. We can't internalize GV
238bf46e741SEugene Leviant   // in such case.
239dde58938Sevgeny   if (!GV.isDeclaration() && VI && ImportIndex.withAttributePropagation()) {
24016ec00eeSTeresa Johnson     if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
24116ec00eeSTeresa Johnson       // We can have more than one local with the same GUID, in the case of
24216ec00eeSTeresa Johnson       // same-named locals in different but same-named source files that were
24316ec00eeSTeresa Johnson       // compiled in their respective directories (so the source file name
24416ec00eeSTeresa Johnson       // and resulting GUID is the same). Find the one in this module.
24516ec00eeSTeresa Johnson       // Handle the case where there is no summary found in this module. That
24616ec00eeSTeresa Johnson       // can happen in the distributed ThinLTO backend, because the index only
24716ec00eeSTeresa Johnson       // contains summaries from the source modules if they are being imported.
24816ec00eeSTeresa Johnson       // We might have a non-null VI and get here even in that case if the name
24916ec00eeSTeresa Johnson       // matches one in this module (e.g. weak or appending linkage).
25016ec00eeSTeresa Johnson       auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
25116ec00eeSTeresa Johnson           ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
2527f92d66fSevgeny       if (GVS &&
2537f92d66fSevgeny           (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) {
25416ec00eeSTeresa Johnson         V->addAttribute("thinlto-internalize");
2557f92d66fSevgeny         // Objects referenced by writeonly GV initializer should not be
2567f92d66fSevgeny         // promoted, because there is no any kind of read access to them
2577f92d66fSevgeny         // on behalf of this writeonly GV. To avoid promotion we convert
2587f92d66fSevgeny         // GV initializer to 'zeroinitializer'. This effectively drops
2597f92d66fSevgeny         // references in IR module (not in combined index), so we can
2607f92d66fSevgeny         // ignore them when computing import. We do not export references
2617f92d66fSevgeny         // of writeonly object. See computeImportForReferencedGlobals
2627f92d66fSevgeny         if (ImportIndex.isWriteOnly(GVS) && GVS->refs().size())
2637f92d66fSevgeny           V->setInitializer(Constant::getNullValue(V->getValueType()));
2647f92d66fSevgeny       }
26516ec00eeSTeresa Johnson     }
266bf46e741SEugene Leviant   }
267bf46e741SEugene Leviant 
268*3be6dbcaSTeresa Johnson   if (GV.hasLocalLinkage() && shouldPromoteLocalToGlobal(&GV)) {
269f59242e5STeresa Johnson     // Save the original name string before we rename GV below.
270f59242e5STeresa Johnson     auto Name = GV.getName().str();
271*3be6dbcaSTeresa Johnson     GV.setName(getPromotedName(&GV));
272*3be6dbcaSTeresa Johnson     GV.setLinkage(getLinkage(&GV, /* DoPromote */ true));
273*3be6dbcaSTeresa Johnson     assert(!GV.hasLocalLinkage());
274488a800aSTeresa Johnson     GV.setVisibility(GlobalValue::HiddenVisibility);
275f59242e5STeresa Johnson 
276f59242e5STeresa Johnson     // If we are renaming a COMDAT leader, ensure that we record the COMDAT
277f59242e5STeresa Johnson     // for later renaming as well. This is required for COFF.
278f59242e5STeresa Johnson     if (const auto *C = GV.getComdat())
279f59242e5STeresa Johnson       if (C->getName() == Name)
280f59242e5STeresa Johnson         RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
281488a800aSTeresa Johnson   } else
2821b9c2be8STeresa Johnson     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
283488a800aSTeresa Johnson 
284488a800aSTeresa Johnson   // Remove functions imported as available externally defs from comdats,
285488a800aSTeresa Johnson   // as this is a declaration for the linker, and will be dropped eventually.
286488a800aSTeresa Johnson   // It is illegal for comdats to contain declarations.
287bf46e741SEugene Leviant   auto *GO = dyn_cast<GlobalObject>(&GV);
288488a800aSTeresa Johnson   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
289488a800aSTeresa Johnson     // The IRMover should not have placed any imported declarations in
290488a800aSTeresa Johnson     // a comdat, so the only declaration that should be in a comdat
291488a800aSTeresa Johnson     // at this point would be a definition imported as available_externally.
292488a800aSTeresa Johnson     assert(GO->hasAvailableExternallyLinkage() &&
293488a800aSTeresa Johnson            "Expected comdat on definition (possibly available external)");
294488a800aSTeresa Johnson     GO->setComdat(nullptr);
295488a800aSTeresa Johnson   }
296488a800aSTeresa Johnson }
297488a800aSTeresa Johnson 
298488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
299488a800aSTeresa Johnson   for (GlobalVariable &GV : M.globals())
300488a800aSTeresa Johnson     processGlobalForThinLTO(GV);
301488a800aSTeresa Johnson   for (Function &SF : M)
302488a800aSTeresa Johnson     processGlobalForThinLTO(SF);
303488a800aSTeresa Johnson   for (GlobalAlias &GA : M.aliases())
304488a800aSTeresa Johnson     processGlobalForThinLTO(GA);
305f59242e5STeresa Johnson 
306f59242e5STeresa Johnson   // Replace any COMDATS that required renaming (because the COMDAT leader was
307f59242e5STeresa Johnson   // promoted and renamed).
308f59242e5STeresa Johnson   if (!RenamedComdats.empty())
309f59242e5STeresa Johnson     for (auto &GO : M.global_objects())
310f59242e5STeresa Johnson       if (auto *C = GO.getComdat()) {
311f59242e5STeresa Johnson         auto Replacement = RenamedComdats.find(C);
312f59242e5STeresa Johnson         if (Replacement != RenamedComdats.end())
313f59242e5STeresa Johnson           GO.setComdat(Replacement->second);
314f59242e5STeresa Johnson       }
315488a800aSTeresa Johnson }
316488a800aSTeresa Johnson 
317488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::run() {
318488a800aSTeresa Johnson   processGlobalsForThinLTO();
319488a800aSTeresa Johnson   return false;
320488a800aSTeresa Johnson }
321488a800aSTeresa Johnson 
3226d8f817fSPeter Collingbourne bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
3236d8f817fSPeter Collingbourne                                   SetVector<GlobalValue *> *GlobalsToImport) {
3248d05185aSMehdi Amini   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
325488a800aSTeresa Johnson   return ThinLTOProcessing.run();
326488a800aSTeresa Johnson }
327