[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-core.git] / include / llvm / IR / GlobalValue.h
blob2209881dbda6221fd810df3b3fd7fbc954f9b7c9
1 //===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===//
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 is a common base class of all globally definable objects. As such,
10 // it is subclassed by GlobalVariable, GlobalAlias and by Function. This is
11 // used because you can do certain things with these global objects that you
12 // can't do to anything else. For example, use the address of one as a
13 // constant.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_IR_GLOBALVALUE_H
18 #define LLVM_IR_GLOBALVALUE_H
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MD5.h"
28 #include <cassert>
29 #include <cstdint>
30 #include <string>
32 namespace llvm {
34 class Comdat;
35 class ConstantRange;
36 class Error;
37 class GlobalObject;
38 class Module;
40 namespace Intrinsic {
41 enum ID : unsigned;
42 } // end namespace Intrinsic
44 class GlobalValue : public Constant {
45 public:
46 /// An enumeration for the kinds of linkage for global values.
47 enum LinkageTypes {
48 ExternalLinkage = 0,///< Externally visible function
49 AvailableExternallyLinkage, ///< Available for inspection, not emission.
50 LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
51 LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
52 WeakAnyLinkage, ///< Keep one copy of named function when linking (weak)
53 WeakODRLinkage, ///< Same, but only replaced by something equivalent.
54 AppendingLinkage, ///< Special purpose, only applies to global arrays
55 InternalLinkage, ///< Rename collisions when linking (static functions).
56 PrivateLinkage, ///< Like Internal, but omit from symbol table.
57 ExternalWeakLinkage,///< ExternalWeak linkage description.
58 CommonLinkage ///< Tentative definitions.
61 /// An enumeration for the kinds of visibility of global values.
62 enum VisibilityTypes {
63 DefaultVisibility = 0, ///< The GV is visible
64 HiddenVisibility, ///< The GV is hidden
65 ProtectedVisibility ///< The GV is protected
68 /// Storage classes of global values for PE targets.
69 enum DLLStorageClassTypes {
70 DefaultStorageClass = 0,
71 DLLImportStorageClass = 1, ///< Function to be imported from DLL
72 DLLExportStorageClass = 2 ///< Function to be accessible from DLL.
75 protected:
76 GlobalValue(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
77 LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace)
78 : Constant(PointerType::get(Ty, AddressSpace), VTy, Ops, NumOps),
79 ValueType(Ty), Visibility(DefaultVisibility),
80 UnnamedAddrVal(unsigned(UnnamedAddr::None)),
81 DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal),
82 HasLLVMReservedName(false), IsDSOLocal(false), HasPartition(false),
83 IntID((Intrinsic::ID)0U), Parent(nullptr) {
84 setLinkage(Linkage);
85 setName(Name);
88 Type *ValueType;
90 static const unsigned GlobalValueSubClassDataBits = 16;
92 // All bitfields use unsigned as the underlying type so that MSVC will pack
93 // them.
94 unsigned Linkage : 4; // The linkage of this global
95 unsigned Visibility : 2; // The visibility style of this global
96 unsigned UnnamedAddrVal : 2; // This value's address is not significant
97 unsigned DllStorageClass : 2; // DLL storage class
99 unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
100 // the desired model?
102 /// True if the function's name starts with "llvm.". This corresponds to the
103 /// value of Function::isIntrinsic(), which may be true even if
104 /// Function::intrinsicID() returns Intrinsic::not_intrinsic.
105 unsigned HasLLVMReservedName : 1;
107 /// If true then there is a definition within the same linkage unit and that
108 /// definition cannot be runtime preempted.
109 unsigned IsDSOLocal : 1;
111 /// True if this symbol has a partition name assigned (see
112 /// https://lld.llvm.org/Partitions.html).
113 unsigned HasPartition : 1;
115 private:
116 // Give subclasses access to what otherwise would be wasted padding.
117 // (16 + 4 + 2 + 2 + 2 + 3 + 1 + 1 + 1) == 32.
118 unsigned SubClassData : GlobalValueSubClassDataBits;
120 friend class Constant;
122 void destroyConstantImpl();
123 Value *handleOperandChangeImpl(Value *From, Value *To);
125 /// Returns true if the definition of this global may be replaced by a
126 /// differently optimized variant of the same source level function at link
127 /// time.
128 bool mayBeDerefined() const {
129 switch (getLinkage()) {
130 case WeakODRLinkage:
131 case LinkOnceODRLinkage:
132 case AvailableExternallyLinkage:
133 return true;
135 case WeakAnyLinkage:
136 case LinkOnceAnyLinkage:
137 case CommonLinkage:
138 case ExternalWeakLinkage:
139 case ExternalLinkage:
140 case AppendingLinkage:
141 case InternalLinkage:
142 case PrivateLinkage:
143 return isInterposable();
146 llvm_unreachable("Fully covered switch above!");
149 void maybeSetDsoLocal() {
150 if (hasLocalLinkage() ||
151 (!hasDefaultVisibility() && !hasExternalWeakLinkage()))
152 setDSOLocal(true);
155 protected:
156 /// The intrinsic ID for this subclass (which must be a Function).
158 /// This member is defined by this class, but not used for anything.
159 /// Subclasses can use it to store their intrinsic ID, if they have one.
161 /// This is stored here to save space in Function on 64-bit hosts.
162 Intrinsic::ID IntID;
164 unsigned getGlobalValueSubClassData() const {
165 return SubClassData;
167 void setGlobalValueSubClassData(unsigned V) {
168 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
169 SubClassData = V;
172 Module *Parent; // The containing module.
174 // Used by SymbolTableListTraits.
175 void setParent(Module *parent) {
176 Parent = parent;
179 ~GlobalValue() {
180 removeDeadConstantUsers(); // remove any dead constants using this.
183 public:
184 enum ThreadLocalMode {
185 NotThreadLocal = 0,
186 GeneralDynamicTLSModel,
187 LocalDynamicTLSModel,
188 InitialExecTLSModel,
189 LocalExecTLSModel
192 GlobalValue(const GlobalValue &) = delete;
194 unsigned getAlignment() const;
195 unsigned getAddressSpace() const;
197 enum class UnnamedAddr {
198 None,
199 Local,
200 Global,
203 bool hasGlobalUnnamedAddr() const {
204 return getUnnamedAddr() == UnnamedAddr::Global;
207 /// Returns true if this value's address is not significant in this module.
208 /// This attribute is intended to be used only by the code generator and LTO
209 /// to allow the linker to decide whether the global needs to be in the symbol
210 /// table. It should probably not be used in optimizations, as the value may
211 /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
212 bool hasAtLeastLocalUnnamedAddr() const {
213 return getUnnamedAddr() != UnnamedAddr::None;
216 UnnamedAddr getUnnamedAddr() const {
217 return UnnamedAddr(UnnamedAddrVal);
219 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
221 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
222 if (A == UnnamedAddr::None || B == UnnamedAddr::None)
223 return UnnamedAddr::None;
224 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
225 return UnnamedAddr::Local;
226 return UnnamedAddr::Global;
229 bool hasComdat() const { return getComdat() != nullptr; }
230 const Comdat *getComdat() const;
231 Comdat *getComdat() {
232 return const_cast<Comdat *>(
233 static_cast<const GlobalValue *>(this)->getComdat());
236 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
237 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
238 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
239 bool hasProtectedVisibility() const {
240 return Visibility == ProtectedVisibility;
242 void setVisibility(VisibilityTypes V) {
243 assert((!hasLocalLinkage() || V == DefaultVisibility) &&
244 "local linkage requires default visibility");
245 Visibility = V;
246 maybeSetDsoLocal();
249 /// If the value is "Thread Local", its value isn't shared by the threads.
250 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
251 void setThreadLocal(bool Val) {
252 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
254 void setThreadLocalMode(ThreadLocalMode Val) {
255 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
256 ThreadLocal = Val;
258 ThreadLocalMode getThreadLocalMode() const {
259 return static_cast<ThreadLocalMode>(ThreadLocal);
262 DLLStorageClassTypes getDLLStorageClass() const {
263 return DLLStorageClassTypes(DllStorageClass);
265 bool hasDLLImportStorageClass() const {
266 return DllStorageClass == DLLImportStorageClass;
268 bool hasDLLExportStorageClass() const {
269 return DllStorageClass == DLLExportStorageClass;
271 void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
273 bool hasSection() const { return !getSection().empty(); }
274 StringRef getSection() const;
276 /// Global values are always pointers.
277 PointerType *getType() const { return cast<PointerType>(User::getType()); }
279 Type *getValueType() const { return ValueType; }
281 void setDSOLocal(bool Local) { IsDSOLocal = Local; }
283 bool isDSOLocal() const {
284 return IsDSOLocal;
287 bool hasPartition() const {
288 return HasPartition;
290 StringRef getPartition() const;
291 void setPartition(StringRef Part);
293 static LinkageTypes getLinkOnceLinkage(bool ODR) {
294 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
296 static LinkageTypes getWeakLinkage(bool ODR) {
297 return ODR ? WeakODRLinkage : WeakAnyLinkage;
300 static bool isExternalLinkage(LinkageTypes Linkage) {
301 return Linkage == ExternalLinkage;
303 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
304 return Linkage == AvailableExternallyLinkage;
306 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
307 return Linkage == LinkOnceODRLinkage;
309 static bool isLinkOnceLinkage(LinkageTypes Linkage) {
310 return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage;
312 static bool isWeakAnyLinkage(LinkageTypes Linkage) {
313 return Linkage == WeakAnyLinkage;
315 static bool isWeakODRLinkage(LinkageTypes Linkage) {
316 return Linkage == WeakODRLinkage;
318 static bool isWeakLinkage(LinkageTypes Linkage) {
319 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
321 static bool isAppendingLinkage(LinkageTypes Linkage) {
322 return Linkage == AppendingLinkage;
324 static bool isInternalLinkage(LinkageTypes Linkage) {
325 return Linkage == InternalLinkage;
327 static bool isPrivateLinkage(LinkageTypes Linkage) {
328 return Linkage == PrivateLinkage;
330 static bool isLocalLinkage(LinkageTypes Linkage) {
331 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
333 static bool isExternalWeakLinkage(LinkageTypes Linkage) {
334 return Linkage == ExternalWeakLinkage;
336 static bool isCommonLinkage(LinkageTypes Linkage) {
337 return Linkage == CommonLinkage;
339 static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
340 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
343 /// Whether the definition of this global may be replaced by something
344 /// non-equivalent at link time. For example, if a function has weak linkage
345 /// then the code defining it may be replaced by different code.
346 static bool isInterposableLinkage(LinkageTypes Linkage) {
347 switch (Linkage) {
348 case WeakAnyLinkage:
349 case LinkOnceAnyLinkage:
350 case CommonLinkage:
351 case ExternalWeakLinkage:
352 return true;
354 case AvailableExternallyLinkage:
355 case LinkOnceODRLinkage:
356 case WeakODRLinkage:
357 // The above three cannot be overridden but can be de-refined.
359 case ExternalLinkage:
360 case AppendingLinkage:
361 case InternalLinkage:
362 case PrivateLinkage:
363 return false;
365 llvm_unreachable("Fully covered switch above!");
368 /// Whether the definition of this global may be discarded if it is not used
369 /// in its compilation unit.
370 static bool isDiscardableIfUnused(LinkageTypes Linkage) {
371 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
372 isAvailableExternallyLinkage(Linkage);
375 /// Whether the definition of this global may be replaced at link time. NB:
376 /// Using this method outside of the code generators is almost always a
377 /// mistake: when working at the IR level use isInterposable instead as it
378 /// knows about ODR semantics.
379 static bool isWeakForLinker(LinkageTypes Linkage) {
380 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
381 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
382 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
385 /// Return true if the currently visible definition of this global (if any) is
386 /// exactly the definition we will see at runtime.
388 /// Non-exact linkage types inhibits most non-inlining IPO, since a
389 /// differently optimized variant of the same function can have different
390 /// observable or undefined behavior than in the variant currently visible.
391 /// For instance, we could have started with
393 /// void foo(int *v) {
394 /// int t = 5 / v[0];
395 /// (void) t;
396 /// }
398 /// and "refined" it to
400 /// void foo(int *v) { }
402 /// However, we cannot infer readnone for `foo`, since that would justify
403 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
404 /// undefined behavior if the linker replaces the actual call destination with
405 /// the unoptimized `foo`.
407 /// Inlining is okay across non-exact linkage types as long as they're not
408 /// interposable (see \c isInterposable), since in such cases the currently
409 /// visible variant is *a* correct implementation of the original source
410 /// function; it just isn't the *only* correct implementation.
411 bool isDefinitionExact() const {
412 return !mayBeDerefined();
415 /// Return true if this global has an exact defintion.
416 bool hasExactDefinition() const {
417 // While this computes exactly the same thing as
418 // isStrongDefinitionForLinker, the intended uses are different. This
419 // function is intended to help decide if specific inter-procedural
420 // transforms are correct, while isStrongDefinitionForLinker's intended use
421 // is in low level code generation.
422 return !isDeclaration() && isDefinitionExact();
425 /// Return true if this global's definition can be substituted with an
426 /// *arbitrary* definition at link time. We cannot do any IPO or inlinining
427 /// across interposable call edges, since the callee can be replaced with
428 /// something arbitrary at link time.
429 bool isInterposable() const { return isInterposableLinkage(getLinkage()); }
431 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
432 bool hasAvailableExternallyLinkage() const {
433 return isAvailableExternallyLinkage(getLinkage());
435 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
436 bool hasLinkOnceODRLinkage() const {
437 return isLinkOnceODRLinkage(getLinkage());
439 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
440 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
441 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
442 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
443 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
444 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
445 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
446 bool hasExternalWeakLinkage() const {
447 return isExternalWeakLinkage(getLinkage());
449 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
450 bool hasValidDeclarationLinkage() const {
451 return isValidDeclarationLinkage(getLinkage());
454 void setLinkage(LinkageTypes LT) {
455 if (isLocalLinkage(LT))
456 Visibility = DefaultVisibility;
457 Linkage = LT;
458 maybeSetDsoLocal();
460 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
462 bool isDiscardableIfUnused() const {
463 return isDiscardableIfUnused(getLinkage());
466 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
468 protected:
469 /// Copy all additional attributes (those not needed to create a GlobalValue)
470 /// from the GlobalValue Src to this one.
471 void copyAttributesFrom(const GlobalValue *Src);
473 public:
474 /// If the given string begins with the GlobalValue name mangling escape
475 /// character '\1', drop it.
477 /// This function applies a specific mangling that is used in PGO profiles,
478 /// among other things. If you're trying to get a symbol name for an
479 /// arbitrary GlobalValue, this is not the function you're looking for; see
480 /// Mangler.h.
481 static StringRef dropLLVMManglingEscape(StringRef Name) {
482 if (!Name.empty() && Name[0] == '\1')
483 return Name.substr(1);
484 return Name;
487 /// Return the modified name for a global value suitable to be
488 /// used as the key for a global lookup (e.g. profile or ThinLTO).
489 /// The value's original name is \c Name and has linkage of type
490 /// \c Linkage. The value is defined in module \c FileName.
491 static std::string getGlobalIdentifier(StringRef Name,
492 GlobalValue::LinkageTypes Linkage,
493 StringRef FileName);
495 /// Return the modified name for this global value suitable to be
496 /// used as the key for a global lookup (e.g. profile or ThinLTO).
497 std::string getGlobalIdentifier() const;
499 /// Declare a type to represent a global unique identifier for a global value.
500 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
501 /// unique way to identify a symbol.
502 using GUID = uint64_t;
504 /// Return a 64-bit global unique ID constructed from global value name
505 /// (i.e. returned by getGlobalIdentifier()).
506 static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
508 /// Return a 64-bit global unique ID constructed from global value name
509 /// (i.e. returned by getGlobalIdentifier()).
510 GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
512 /// @name Materialization
513 /// Materialization is used to construct functions only as they're needed.
514 /// This
515 /// is useful to reduce memory usage in LLVM or parsing work done by the
516 /// BitcodeReader to load the Module.
517 /// @{
519 /// If this function's Module is being lazily streamed in functions from disk
520 /// or some other source, this method can be used to check to see if the
521 /// function has been read in yet or not.
522 bool isMaterializable() const;
524 /// Make sure this GlobalValue is fully read.
525 Error materialize();
527 /// @}
529 /// Return true if the primary definition of this global value is outside of
530 /// the current translation unit.
531 bool isDeclaration() const;
533 bool isDeclarationForLinker() const {
534 if (hasAvailableExternallyLinkage())
535 return true;
537 return isDeclaration();
540 /// Returns true if this global's definition will be the one chosen by the
541 /// linker.
543 /// NB! Ideally this should not be used at the IR level at all. If you're
544 /// interested in optimization constraints implied by the linker's ability to
545 /// choose an implementation, prefer using \c hasExactDefinition.
546 bool isStrongDefinitionForLinker() const {
547 return !(isDeclarationForLinker() || isWeakForLinker());
550 // Returns true if the alignment of the value can be unilaterally
551 // increased.
552 bool canIncreaseAlignment() const;
554 const GlobalObject *getBaseObject() const;
555 GlobalObject *getBaseObject() {
556 return const_cast<GlobalObject *>(
557 static_cast<const GlobalValue *>(this)->getBaseObject());
560 /// Returns whether this is a reference to an absolute symbol.
561 bool isAbsoluteSymbolRef() const;
563 /// If this is an absolute symbol reference, returns the range of the symbol,
564 /// otherwise returns None.
565 Optional<ConstantRange> getAbsoluteSymbolRange() const;
567 /// This method unlinks 'this' from the containing module, but does not delete
568 /// it.
569 void removeFromParent();
571 /// This method unlinks 'this' from the containing module and deletes it.
572 void eraseFromParent();
574 /// Get the module that this global value is contained inside of...
575 Module *getParent() { return Parent; }
576 const Module *getParent() const { return Parent; }
578 // Methods for support type inquiry through isa, cast, and dyn_cast:
579 static bool classof(const Value *V) {
580 return V->getValueID() == Value::FunctionVal ||
581 V->getValueID() == Value::GlobalVariableVal ||
582 V->getValueID() == Value::GlobalAliasVal ||
583 V->getValueID() == Value::GlobalIFuncVal;
586 /// True if GV can be left out of the object symbol table. This is the case
587 /// for linkonce_odr values whose address is not significant. While legal, it
588 /// is not normally profitable to omit them from the .o symbol table. Using
589 /// this analysis makes sense when the information can be passed down to the
590 /// linker or we are in LTO.
591 bool canBeOmittedFromSymbolTable() const;
594 } // end namespace llvm
596 #endif // LLVM_IR_GLOBALVALUE_H