LLVM  4.0.0
FunctionImportUtils.cpp
Go to the documentation of this file.
1 //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the FunctionImportGlobalProcessing class, used
11 // to perform the necessary global value handling for function importing.
12 //
13 //===----------------------------------------------------------------------===//
14 
17 #include "llvm/IR/InstIterator.h"
18 #include "llvm/IR/Instructions.h"
19 using namespace llvm;
20 
21 /// Checks if we should import SGV as a definition, otherwise import as a
22 /// declaration.
23 bool FunctionImportGlobalProcessing::doImportAsDefinition(
24  const GlobalValue *SGV, DenseSet<const GlobalValue *> *GlobalsToImport) {
25 
26  // For alias, we tie the definition to the base object. Extract it and recurse
27  if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
28  if (GA->hasWeakAnyLinkage())
29  return false;
30  const GlobalObject *GO = GA->getBaseObject();
31  if (!GO->hasLinkOnceODRLinkage())
32  return false;
33  return FunctionImportGlobalProcessing::doImportAsDefinition(
34  GO, GlobalsToImport);
35  }
36  // Only import the globals requested for importing.
37  if (GlobalsToImport->count(SGV))
38  return true;
39  // Otherwise no.
40  return false;
41 }
42 
43 bool FunctionImportGlobalProcessing::doImportAsDefinition(
44  const GlobalValue *SGV) {
45  if (!isPerformingImport())
46  return false;
47  return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
48  GlobalsToImport);
49 }
50 
51 bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
52  const GlobalValue *SGV) {
53  assert(SGV->hasLocalLinkage());
54  // Both the imported references and the original local variable must
55  // be promoted.
56  if (!isPerformingImport() && !isModuleExporting())
57  return false;
58 
59  if (isPerformingImport()) {
60  assert((!GlobalsToImport->count(SGV) || !isNonRenamableLocal(*SGV)) &&
61  "Attempting to promote non-renamable local");
62  // We don't know for sure yet if we are importing this value (as either
63  // a reference or a def), since we are simply walking all values in the
64  // module. But by necessity if we end up importing it and it is local,
65  // it must be promoted, so unconditionally promote all values in the
66  // importing module.
67  return true;
68  }
69 
70  // When exporting, consult the index. We can have more than one local
71  // with the same GUID, in the case of same-named locals in different but
72  // same-named source files that were compiled in their respective directories
73  // (so the source file name and resulting GUID is the same). Find the one
74  // in this module.
75  auto Summary = ImportIndex.findSummaryInModule(
76  SGV->getGUID(), SGV->getParent()->getModuleIdentifier());
77  assert(Summary && "Missing summary for global value when exporting");
78  auto Linkage = Summary->linkage();
79  if (!GlobalValue::isLocalLinkage(Linkage)) {
80  assert(!isNonRenamableLocal(*SGV) &&
81  "Attempting to promote non-renamable local");
82  return true;
83  }
84 
85  return false;
86 }
87 
88 #ifndef NDEBUG
89 bool FunctionImportGlobalProcessing::isNonRenamableLocal(
90  const GlobalValue &GV) const {
91  if (!GV.hasLocalLinkage())
92  return false;
93  // This needs to stay in sync with the logic in buildModuleSummaryIndex.
94  if (GV.hasSection())
95  return true;
96  if (Used.count(const_cast<GlobalValue *>(&GV)))
97  return true;
98  return false;
99 }
100 #endif
101 
102 std::string FunctionImportGlobalProcessing::getName(const GlobalValue *SGV,
103  bool DoPromote) {
104  // For locals that must be promoted to global scope, ensure that
105  // the promoted name uniquely identifies the copy in the original module,
106  // using the ID assigned during combined index creation. When importing,
107  // we rename all locals (not just those that are promoted) in order to
108  // avoid naming conflicts between locals imported from different modules.
109  if (SGV->hasLocalLinkage() && (DoPromote || isPerformingImport()))
111  SGV->getName(),
112  ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
113  return SGV->getName();
114 }
115 
117 FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
118  bool DoPromote) {
119  // Any local variable that is referenced by an exported function needs
120  // to be promoted to global scope. Since we don't currently know which
121  // functions reference which local variables/functions, we must treat
122  // all as potentially exported if this module is exporting anything.
123  if (isModuleExporting()) {
124  if (SGV->hasLocalLinkage() && DoPromote)
126  return SGV->getLinkage();
127  }
128 
129  // Otherwise, if we aren't importing, no linkage change is needed.
130  if (!isPerformingImport())
131  return SGV->getLinkage();
132 
133  switch (SGV->getLinkage()) {
135  // External defnitions are converted to available_externally
136  // definitions upon import, so that they are available for inlining
137  // and/or optimization, but are turned into declarations later
138  // during the EliminateAvailableExternally pass.
139  if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
141  // An imported external declaration stays external.
142  return SGV->getLinkage();
143 
145  // An imported available_externally definition converts
146  // to external if imported as a declaration.
147  if (!doImportAsDefinition(SGV))
149  // An imported available_externally declaration stays that way.
150  return SGV->getLinkage();
151 
154  // These both stay the same when importing the definition.
155  // The ThinLTO pass will eventually force-import their definitions.
156  return SGV->getLinkage();
157 
159  // Can't import weak_any definitions correctly, or we might change the
160  // program semantics, since the linker will pick the first weak_any
161  // definition and importing would change the order they are seen by the
162  // linker. The module linking caller needs to enforce this.
163  assert(!doImportAsDefinition(SGV));
164  // If imported as a declaration, it becomes external_weak.
165  return SGV->getLinkage();
166 
168  // For weak_odr linkage, there is a guarantee that all copies will be
169  // equivalent, so the issue described above for weak_any does not exist,
170  // and the definition can be imported. It can be treated similarly
171  // to an imported externally visible global value.
172  if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
174  else
176 
178  // It would be incorrect to import an appending linkage variable,
179  // since it would cause global constructors/destructors to be
180  // executed multiple times. This should have already been handled
181  // by linkIfNeeded, and we will assert in shouldLinkFromSource
182  // if we try to import, so we simply return AppendingLinkage.
184 
187  // If we are promoting the local to global scope, it is handled
188  // similarly to a normal externally visible global.
189  if (DoPromote) {
190  if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
192  else
194  }
195  // A non-promoted imported local definition stays local.
196  // The ThinLTO pass will eventually force-import their definitions.
197  return SGV->getLinkage();
198 
200  // External weak doesn't apply to definitions, must be a declaration.
201  assert(!doImportAsDefinition(SGV));
202  // Linkage stays external_weak.
203  return SGV->getLinkage();
204 
206  // Linkage stays common on definitions.
207  // The ThinLTO pass will eventually force-import their definitions.
208  return SGV->getLinkage();
209  }
210 
211  llvm_unreachable("unknown linkage type");
212 }
213 
214 void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
215  bool DoPromote = false;
216  if (GV.hasLocalLinkage() &&
217  ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) {
218  // Once we change the name or linkage it is difficult to determine
219  // again whether we should promote since shouldPromoteLocalToGlobal needs
220  // to locate the summary (based on GUID from name and linkage). Therefore,
221  // use DoPromote result saved above.
222  GV.setName(getName(&GV, DoPromote));
223  GV.setLinkage(getLinkage(&GV, DoPromote));
224  if (!GV.hasLocalLinkage())
226  } else
227  GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
228 
229  // Remove functions imported as available externally defs from comdats,
230  // as this is a declaration for the linker, and will be dropped eventually.
231  // It is illegal for comdats to contain declarations.
232  auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
233  if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
234  // The IRMover should not have placed any imported declarations in
235  // a comdat, so the only declaration that should be in a comdat
236  // at this point would be a definition imported as available_externally.
237  assert(GO->hasAvailableExternallyLinkage() &&
238  "Expected comdat on definition (possibly available external)");
239  GO->setComdat(nullptr);
240  }
241 }
242 
243 void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
244  for (GlobalVariable &GV : M.globals())
245  processGlobalForThinLTO(GV);
246  for (Function &SF : M)
247  processGlobalForThinLTO(SF);
248  for (GlobalAlias &GA : M.aliases())
249  processGlobalForThinLTO(GA);
250 }
251 
253  processGlobalsForThinLTO();
254  return false;
255 }
256 
258  Module &M, const ModuleSummaryIndex &Index,
259  DenseSet<const GlobalValue *> *GlobalsToImport) {
260  FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
261  return ThinLTOProcessing.run();
262 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:225
LinkageTypes getLinkage() const
Definition: GlobalValue.h:429
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:55
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:54
This is the interface to build a ModuleSummaryIndex for a module.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:202
Available for inspection, not emission.
Definition: GlobalValue.h:50
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
Class to handle necessary GlobalValue changes required by ThinLTO function importing, including linkage changes and any necessary renaming.
Tentative definitions.
Definition: GlobalValue.h:59
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:300
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
bool hasSection() const
Definition: GlobalValue.h:255
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local...
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:257
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:193
Class to hold module path string table and global value map, and encapsulate methods for operating on...
ExternalWeak linkage description.
Definition: GlobalValue.h:58
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
static GUID getGUID(StringRef GlobalName)
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:469
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:51
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, DenseSet< const GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
GlobalValueSummary * findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const
Find the summary for global GUID in module ModuleId, or nullptr if not found.
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:424
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
const GlobalObject * getBaseObject() const
Definition: GlobalValue.h:517
size_type count(const ValueT &V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:81
bool hasLinkOnceODRLinkage() const
Definition: GlobalValue.h:406
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:287
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:53
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
bool hasLocalLinkage() const
Definition: GlobalValue.h:415
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
iterator_range< global_iterator > globals()
Definition: Module.h:524