1 //===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a common base class of all globally definable objects. As such,
11 // it is subclassed by GlobalVariable, GlobalAlias and by Function. This is
12 // used because you can do certain things with these global objects that you
13 // can't do to anything else. For example, use the address of one as a
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_IR_GLOBALVALUE_H
19 #define LLVM_IR_GLOBALVALUE_H
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/Support/MD5.h"
24 #include <system_error>
36 class GlobalValue : public Constant {
37 GlobalValue(const GlobalValue &) = delete;
39 /// @brief An enumeration for the kinds of linkage for global values.
41 ExternalLinkage = 0,///< Externally visible function
42 AvailableExternallyLinkage, ///< Available for inspection, not emission.
43 LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
44 LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
45 WeakAnyLinkage, ///< Keep one copy of named function when linking (weak)
46 WeakODRLinkage, ///< Same, but only replaced by something equivalent.
47 AppendingLinkage, ///< Special purpose, only applies to global arrays
48 InternalLinkage, ///< Rename collisions when linking (static functions).
49 PrivateLinkage, ///< Like Internal, but omit from symbol table.
50 ExternalWeakLinkage,///< ExternalWeak linkage description.
51 CommonLinkage ///< Tentative definitions.
54 /// @brief An enumeration for the kinds of visibility of global values.
55 enum VisibilityTypes {
56 DefaultVisibility = 0, ///< The GV is visible
57 HiddenVisibility, ///< The GV is hidden
58 ProtectedVisibility ///< The GV is protected
61 /// @brief Storage classes of global values for PE targets.
62 enum DLLStorageClassTypes {
63 DefaultStorageClass = 0,
64 DLLImportStorageClass = 1, ///< Function to be imported from DLL
65 DLLExportStorageClass = 2 ///< Function to be accessible from DLL.
69 GlobalValue(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
70 LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace)
71 : Constant(PointerType::get(Ty, AddressSpace), VTy, Ops, NumOps),
72 ValueType(Ty), Linkage(Linkage), Visibility(DefaultVisibility),
73 UnnamedAddrVal(unsigned(UnnamedAddr::None)),
74 DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal),
75 IntID((Intrinsic::ID)0U), Parent(nullptr) {
80 // All bitfields use unsigned as the underlying type so that MSVC will pack
82 unsigned Linkage : 4; // The linkage of this global
83 unsigned Visibility : 2; // The visibility style of this global
84 unsigned UnnamedAddrVal : 2; // This value's address is not significant
85 unsigned DllStorageClass : 2; // DLL storage class
87 unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
89 static const unsigned GlobalValueSubClassDataBits = 19;
92 // Give subclasses access to what otherwise would be wasted padding.
93 // (19 + 4 + 2 + 2 + 2 + 3) == 32.
94 unsigned SubClassData : GlobalValueSubClassDataBits;
96 friend class Constant;
97 void destroyConstantImpl();
98 Value *handleOperandChangeImpl(Value *From, Value *To);
100 /// Returns true if the definition of this global may be replaced by a
101 /// differently optimized variant of the same source level function at link
103 bool mayBeDerefined() const {
104 switch (getLinkage()) {
106 case LinkOnceODRLinkage:
107 case AvailableExternallyLinkage:
111 case LinkOnceAnyLinkage:
113 case ExternalWeakLinkage:
114 case ExternalLinkage:
115 case AppendingLinkage:
116 case InternalLinkage:
118 return isInterposable();
121 llvm_unreachable("Fully covered switch above!");
125 /// \brief The intrinsic ID for this subclass (which must be a Function).
127 /// This member is defined by this class, but not used for anything.
128 /// Subclasses can use it to store their intrinsic ID, if they have one.
130 /// This is stored here to save space in Function on 64-bit hosts.
133 unsigned getGlobalValueSubClassData() const {
136 void setGlobalValueSubClassData(unsigned V) {
137 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
141 Module *Parent; // The containing module.
143 enum ThreadLocalMode {
145 GeneralDynamicTLSModel,
146 LocalDynamicTLSModel,
151 ~GlobalValue() override {
152 removeDeadConstantUsers(); // remove any dead constants using this.
155 unsigned getAlignment() const;
157 enum class UnnamedAddr {
163 bool hasGlobalUnnamedAddr() const {
164 return getUnnamedAddr() == UnnamedAddr::Global;
167 /// Returns true if this value's address is not significant in this module.
168 /// This attribute is intended to be used only by the code generator and LTO
169 /// to allow the linker to decide whether the global needs to be in the symbol
170 /// table. It should probably not be used in optimizations, as the value may
171 /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
172 bool hasAtLeastLocalUnnamedAddr() const {
173 return getUnnamedAddr() != UnnamedAddr::None;
176 UnnamedAddr getUnnamedAddr() const {
177 return UnnamedAddr(UnnamedAddrVal);
179 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
181 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
182 if (A == UnnamedAddr::None || B == UnnamedAddr::None)
183 return UnnamedAddr::None;
184 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
185 return UnnamedAddr::Local;
186 return UnnamedAddr::Global;
189 bool hasComdat() const { return getComdat() != nullptr; }
191 const Comdat *getComdat() const {
192 return const_cast<GlobalValue *>(this)->getComdat();
195 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
196 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
197 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
198 bool hasProtectedVisibility() const {
199 return Visibility == ProtectedVisibility;
201 void setVisibility(VisibilityTypes V) {
202 assert((!hasLocalLinkage() || V == DefaultVisibility) &&
203 "local linkage requires default visibility");
207 /// If the value is "Thread Local", its value isn't shared by the threads.
208 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
209 void setThreadLocal(bool Val) {
210 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
212 void setThreadLocalMode(ThreadLocalMode Val) {
213 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
216 ThreadLocalMode getThreadLocalMode() const {
217 return static_cast<ThreadLocalMode>(ThreadLocal);
220 DLLStorageClassTypes getDLLStorageClass() const {
221 return DLLStorageClassTypes(DllStorageClass);
223 bool hasDLLImportStorageClass() const {
224 return DllStorageClass == DLLImportStorageClass;
226 bool hasDLLExportStorageClass() const {
227 return DllStorageClass == DLLExportStorageClass;
229 void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
231 bool hasSection() const { return !getSection().empty(); }
232 StringRef getSection() const;
234 /// Global values are always pointers.
235 PointerType *getType() const { return cast<PointerType>(User::getType()); }
237 Type *getValueType() const { return ValueType; }
239 static LinkageTypes getLinkOnceLinkage(bool ODR) {
240 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
242 static LinkageTypes getWeakLinkage(bool ODR) {
243 return ODR ? WeakODRLinkage : WeakAnyLinkage;
246 static bool isExternalLinkage(LinkageTypes Linkage) {
247 return Linkage == ExternalLinkage;
249 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
250 return Linkage == AvailableExternallyLinkage;
252 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
253 return Linkage == LinkOnceODRLinkage;
255 static bool isLinkOnceLinkage(LinkageTypes Linkage) {
256 return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage;
258 static bool isWeakAnyLinkage(LinkageTypes Linkage) {
259 return Linkage == WeakAnyLinkage;
261 static bool isWeakODRLinkage(LinkageTypes Linkage) {
262 return Linkage == WeakODRLinkage;
264 static bool isWeakLinkage(LinkageTypes Linkage) {
265 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
267 static bool isAppendingLinkage(LinkageTypes Linkage) {
268 return Linkage == AppendingLinkage;
270 static bool isInternalLinkage(LinkageTypes Linkage) {
271 return Linkage == InternalLinkage;
273 static bool isPrivateLinkage(LinkageTypes Linkage) {
274 return Linkage == PrivateLinkage;
276 static bool isLocalLinkage(LinkageTypes Linkage) {
277 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
279 static bool isExternalWeakLinkage(LinkageTypes Linkage) {
280 return Linkage == ExternalWeakLinkage;
282 static bool isCommonLinkage(LinkageTypes Linkage) {
283 return Linkage == CommonLinkage;
285 static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
286 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
289 /// Whether the definition of this global may be replaced by something
290 /// non-equivalent at link time. For example, if a function has weak linkage
291 /// then the code defining it may be replaced by different code.
292 static bool isInterposableLinkage(LinkageTypes Linkage) {
295 case LinkOnceAnyLinkage:
297 case ExternalWeakLinkage:
300 case AvailableExternallyLinkage:
301 case LinkOnceODRLinkage:
303 // The above three cannot be overridden but can be de-refined.
305 case ExternalLinkage:
306 case AppendingLinkage:
307 case InternalLinkage:
311 llvm_unreachable("Fully covered switch above!");
314 /// Whether the definition of this global may be discarded if it is not used
315 /// in its compilation unit.
316 static bool isDiscardableIfUnused(LinkageTypes Linkage) {
317 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
318 isAvailableExternallyLinkage(Linkage);
321 /// Whether the definition of this global may be replaced at link time. NB:
322 /// Using this method outside of the code generators is almost always a
323 /// mistake: when working at the IR level use isInterposable instead as it
324 /// knows about ODR semantics.
325 static bool isWeakForLinker(LinkageTypes Linkage) {
326 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
327 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
328 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
331 /// Return true if the currently visible definition of this global (if any) is
332 /// exactly the definition we will see at runtime.
334 /// Non-exact linkage types inhibits most non-inlining IPO, since a
335 /// differently optimized variant of the same function can have different
336 /// observable or undefined behavior than in the variant currently visible.
337 /// For instance, we could have started with
339 /// void foo(int *v) {
340 /// int t = 5 / v[0];
344 /// and "refined" it to
346 /// void foo(int *v) { }
348 /// However, we cannot infer readnone for `foo`, since that would justify
349 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
350 /// undefined behavior if the linker replaces the actual call destination with
351 /// the unoptimized `foo`.
353 /// Inlining is okay across non-exact linkage types as long as they're not
354 /// interposable (see \c isInterposable), since in such cases the currently
355 /// visible variant is *a* correct implementation of the original source
356 /// function; it just isn't the *only* correct implementation.
357 bool isDefinitionExact() const {
358 return !mayBeDerefined();
361 /// Return true if this global has an exact defintion.
362 bool hasExactDefinition() const {
363 // While this computes exactly the same thing as
364 // isStrongDefinitionForLinker, the intended uses are different. This
365 // function is intended to help decide if specific inter-procedural
366 // transforms are correct, while isStrongDefinitionForLinker's intended use
367 // is in low level code generation.
368 return !isDeclaration() && isDefinitionExact();
371 /// Return true if this global's definition can be substituted with an
372 /// *arbitrary* definition at link time. We cannot do any IPO or inlinining
373 /// across interposable call edges, since the callee can be replaced with
374 /// something arbitrary at link time.
375 bool isInterposable() const { return isInterposableLinkage(getLinkage()); }
377 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
378 bool hasAvailableExternallyLinkage() const {
379 return isAvailableExternallyLinkage(getLinkage());
381 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
382 bool hasLinkOnceODRLinkage() const {
383 return isLinkOnceODRLinkage(getLinkage());
385 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
386 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
387 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
388 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
389 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
390 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
391 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
392 bool hasExternalWeakLinkage() const {
393 return isExternalWeakLinkage(getLinkage());
395 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
396 bool hasValidDeclarationLinkage() const {
397 return isValidDeclarationLinkage(getLinkage());
400 void setLinkage(LinkageTypes LT) {
401 if (isLocalLinkage(LT))
402 Visibility = DefaultVisibility;
405 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
407 bool isDiscardableIfUnused() const {
408 return isDiscardableIfUnused(getLinkage());
411 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
413 /// Copy all additional attributes (those not needed to create a GlobalValue)
414 /// from the GlobalValue Src to this one.
415 virtual void copyAttributesFrom(const GlobalValue *Src);
417 /// If special LLVM prefix that is used to inform the asm printer to not emit
418 /// usual symbol prefix before the symbol name is used then return linkage
419 /// name after skipping this special LLVM prefix.
420 static StringRef getRealLinkageName(StringRef Name) {
421 if (!Name.empty() && Name[0] == '\1')
422 return Name.substr(1);
426 /// Return the modified name for a global value suitable to be
427 /// used as the key for a global lookup (e.g. profile or ThinLTO).
428 /// The value's original name is \c Name and has linkage of type
429 /// \c Linkage. The value is defined in module \c FileName.
430 static std::string getGlobalIdentifier(StringRef Name,
431 GlobalValue::LinkageTypes Linkage,
434 /// Return the modified name for this global value suitable to be
435 /// used as the key for a global lookup (e.g. profile or ThinLTO).
436 std::string getGlobalIdentifier() const;
438 /// Declare a type to represent a global unique identifier for a global value.
439 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
440 /// unique way to identify a symbol.
441 using GUID = uint64_t;
443 /// Return a 64-bit global unique ID constructed from global value name
444 /// (i.e. returned by getGlobalIdentifier()).
445 static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
447 /// Return a 64-bit global unique ID constructed from global value name
448 /// (i.e. returned by getGlobalIdentifier()).
449 GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
451 /// @name Materialization
452 /// Materialization is used to construct functions only as they're needed.
454 /// is useful to reduce memory usage in LLVM or parsing work done by the
455 /// BitcodeReader to load the Module.
458 /// If this function's Module is being lazily streamed in functions from disk
459 /// or some other source, this method can be used to check to see if the
460 /// function has been read in yet or not.
461 bool isMaterializable() const;
463 /// Make sure this GlobalValue is fully read. If the module is corrupt, this
464 /// returns true and fills in the optional string with information about the
465 /// problem. If successful, this returns false.
466 std::error_code materialize();
470 /// Return true if the primary definition of this global value is outside of
471 /// the current translation unit.
472 bool isDeclaration() const;
474 bool isDeclarationForLinker() const {
475 if (hasAvailableExternallyLinkage())
478 return isDeclaration();
481 /// Returns true if this global's definition will be the one chosen by the
484 /// NB! Ideally this should not be used at the IR level at all. If you're
485 /// interested in optimization constraints implied by the linker's ability to
486 /// choose an implementation, prefer using \c hasExactDefinition.
487 bool isStrongDefinitionForLinker() const {
488 return !(isDeclarationForLinker() || isWeakForLinker());
491 // Returns true if the alignment of the value can be unilaterally
493 bool canIncreaseAlignment() const;
495 /// This method unlinks 'this' from the containing module, but does not delete
497 virtual void removeFromParent() = 0;
499 /// This method unlinks 'this' from the containing module and deletes it.
500 virtual void eraseFromParent() = 0;
502 /// Get the module that this global value is contained inside of...
503 Module *getParent() { return Parent; }
504 const Module *getParent() const { return Parent; }
506 // Methods for support type inquiry through isa, cast, and dyn_cast:
507 static bool classof(const Value *V) {
508 return V->getValueID() == Value::FunctionVal ||
509 V->getValueID() == Value::GlobalVariableVal ||
510 V->getValueID() == Value::GlobalAliasVal ||
511 V->getValueID() == Value::GlobalIFuncVal;
515 } // End llvm namespace