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.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_IR_GLOBALVALUE_H
18#define LLVM_IR_GLOBALVALUE_H
19
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>
31
32namespace llvm {
33
34class Comdat;
35class ConstantRange;
36class Error;
37class GlobalObject;
38class Module;
39
40namespace Intrinsic {
41typedef unsigned ID;
42} // end namespace Intrinsic
43
44class GlobalValue : public Constant {
45public:
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.
59 };
60
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
66 };
67
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.
73 };
74
75protected:
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);
86 }
87
88 Type *ValueType;
89
90 static const unsigned GlobalValueSubClassDataBits = 16;
91
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
98
99 unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
100 // the desired model?
101
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;
106
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;
110
111 /// True if this symbol has a partition name assigned (see
112 /// https://lld.llvm.org/Partitions.html).
113 unsigned HasPartition : 1;
114
115private:
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;
119
120 friend class Constant;
121
122 void destroyConstantImpl();
123 Value *handleOperandChangeImpl(Value *From, Value *To);
124
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;
134
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();
144 }
145
146 llvm_unreachable("Fully covered switch above!");
147 }
148
149protected:
150 /// The intrinsic ID for this subclass (which must be a Function).
151 ///
152 /// This member is defined by this class, but not used for anything.
153 /// Subclasses can use it to store their intrinsic ID, if they have one.
154 ///
155 /// This is stored here to save space in Function on 64-bit hosts.
156 Intrinsic::ID IntID;
157
158 unsigned getGlobalValueSubClassData() const {
159 return SubClassData;
160 }
161 void setGlobalValueSubClassData(unsigned V) {
162 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
163 SubClassData = V;
164 }
165
166 Module *Parent; // The containing module.
167
168 // Used by SymbolTableListTraits.
169 void setParent(Module *parent) {
170 Parent = parent;
171 }
172
173 ~GlobalValue() {
174 removeDeadConstantUsers(); // remove any dead constants using this.
175 }
176
177public:
178 enum ThreadLocalMode {
179 NotThreadLocal = 0,
180 GeneralDynamicTLSModel,
181 LocalDynamicTLSModel,
182 InitialExecTLSModel,
183 LocalExecTLSModel
184 };
185
186 GlobalValue(const GlobalValue &) = delete;
187
188 unsigned getAddressSpace() const;
189
190 enum class UnnamedAddr {
191 None,
192 Local,
193 Global,
194 };
195
196 bool hasGlobalUnnamedAddr() const {
197 return getUnnamedAddr() == UnnamedAddr::Global;
198 }
199
200 /// Returns true if this value's address is not significant in this module.
201 /// This attribute is intended to be used only by the code generator and LTO
202 /// to allow the linker to decide whether the global needs to be in the symbol
203 /// table. It should probably not be used in optimizations, as the value may
204 /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
205 bool hasAtLeastLocalUnnamedAddr() const {
206 return getUnnamedAddr() != UnnamedAddr::None;
207 }
208
209 UnnamedAddr getUnnamedAddr() const {
210 return UnnamedAddr(UnnamedAddrVal);
211 }
212 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
213
214 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
215 if (A == UnnamedAddr::None || B == UnnamedAddr::None)
216 return UnnamedAddr::None;
217 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
218 return UnnamedAddr::Local;
219 return UnnamedAddr::Global;
220 }
221
222 bool hasComdat() const { return getComdat() != nullptr; }
223 const Comdat *getComdat() const;
224 Comdat *getComdat() {
225 return const_cast<Comdat *>(
226 static_cast<const GlobalValue *>(this)->getComdat());
227 }
228
229 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
230 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
231 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
232 bool hasProtectedVisibility() const {
233 return Visibility == ProtectedVisibility;
234 }
235 void setVisibility(VisibilityTypes V) {
236 assert((!hasLocalLinkage() || V == DefaultVisibility) &&
237 "local linkage requires default visibility");
238 Visibility = V;
239 if (isImplicitDSOLocal())
240 setDSOLocal(true);
241 }
242
243 /// If the value is "Thread Local", its value isn't shared by the threads.
244 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
245 void setThreadLocal(bool Val) {
246 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
247 }
248 void setThreadLocalMode(ThreadLocalMode Val) {
249 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
250 ThreadLocal = Val;
251 }
252 ThreadLocalMode getThreadLocalMode() const {
253 return static_cast<ThreadLocalMode>(ThreadLocal);
254 }
255
256 DLLStorageClassTypes getDLLStorageClass() const {
257 return DLLStorageClassTypes(DllStorageClass);
258 }
259 bool hasDLLImportStorageClass() const {
260 return DllStorageClass == DLLImportStorageClass;
261 }
262 bool hasDLLExportStorageClass() const {
263 return DllStorageClass == DLLExportStorageClass;
264 }
265 void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
266
267 bool hasSection() const { return !getSection().empty(); }
268 StringRef getSection() const;
269
270 /// Global values are always pointers.
271 PointerType *getType() const { return cast<PointerType>(User::getType()); }
272
273 Type *getValueType() const { return ValueType; }
274
275 bool isImplicitDSOLocal() const {
276 return hasLocalLinkage() ||
277 (!hasDefaultVisibility() && !hasExternalWeakLinkage());
278 }
279
280 void setDSOLocal(bool Local) { IsDSOLocal = Local; }
281
282 bool isDSOLocal() const {
283 return IsDSOLocal;
284 }
285
286 bool hasPartition() const {
287 return HasPartition;
288 }
289 StringRef getPartition() const;
290 void setPartition(StringRef Part);
291
292 static LinkageTypes getLinkOnceLinkage(bool ODR) {
293 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
294 }
295 static LinkageTypes getWeakLinkage(bool ODR) {
296 return ODR ? WeakODRLinkage : WeakAnyLinkage;
297 }
298
299 static bool isExternalLinkage(LinkageTypes Linkage) {
300 return Linkage == ExternalLinkage;
301 }
302 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
303 return Linkage == AvailableExternallyLinkage;
304 }
305 static bool isLinkOnceAnyLinkage(LinkageTypes Linkage) {
306 return Linkage == LinkOnceAnyLinkage;
307 }
308 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
309 return Linkage == LinkOnceODRLinkage;
310 }
311 static bool isLinkOnceLinkage(LinkageTypes Linkage) {
312 return isLinkOnceAnyLinkage(Linkage) || isLinkOnceODRLinkage(Linkage);
313 }
314 static bool isWeakAnyLinkage(LinkageTypes Linkage) {
315 return Linkage == WeakAnyLinkage;
316 }
317 static bool isWeakODRLinkage(LinkageTypes Linkage) {
318 return Linkage == WeakODRLinkage;
319 }
320 static bool isWeakLinkage(LinkageTypes Linkage) {
321 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
322 }
323 static bool isAppendingLinkage(LinkageTypes Linkage) {
324 return Linkage == AppendingLinkage;
325 }
326 static bool isInternalLinkage(LinkageTypes Linkage) {
327 return Linkage == InternalLinkage;
328 }
329 static bool isPrivateLinkage(LinkageTypes Linkage) {
330 return Linkage == PrivateLinkage;
331 }
332 static bool isLocalLinkage(LinkageTypes Linkage) {
333 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
334 }
335 static bool isExternalWeakLinkage(LinkageTypes Linkage) {
336 return Linkage == ExternalWeakLinkage;
337 }
338 static bool isCommonLinkage(LinkageTypes Linkage) {
339 return Linkage == CommonLinkage;
340 }
341 static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
342 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
343 }
344
345 /// Whether the definition of this global may be replaced by something
346 /// non-equivalent at link time. For example, if a function has weak linkage
347 /// then the code defining it may be replaced by different code.
348 static bool isInterposableLinkage(LinkageTypes Linkage) {
349 switch (Linkage) {
350 case WeakAnyLinkage:
351 case LinkOnceAnyLinkage:
352 case CommonLinkage:
353 case ExternalWeakLinkage:
354 return true;
355
356 case AvailableExternallyLinkage:
357 case LinkOnceODRLinkage:
358 case WeakODRLinkage:
359 // The above three cannot be overridden but can be de-refined.
360
361 case ExternalLinkage:
362 case AppendingLinkage:
363 case InternalLinkage:
364 case PrivateLinkage:
365 return false;
366 }
367 llvm_unreachable("Fully covered switch above!");
368 }
369
370 /// Whether the definition of this global may be discarded if it is not used
371 /// in its compilation unit.
372 static bool isDiscardableIfUnused(LinkageTypes Linkage) {
373 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
374 isAvailableExternallyLinkage(Linkage);
375 }
376
377 /// Whether the definition of this global may be replaced at link time. NB:
378 /// Using this method outside of the code generators is almost always a
379 /// mistake: when working at the IR level use isInterposable instead as it
380 /// knows about ODR semantics.
381 static bool isWeakForLinker(LinkageTypes Linkage) {
382 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
383 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
384 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
385 }
386
387 /// Return true if the currently visible definition of this global (if any) is
388 /// exactly the definition we will see at runtime.
389 ///
390 /// Non-exact linkage types inhibits most non-inlining IPO, since a
391 /// differently optimized variant of the same function can have different
392 /// observable or undefined behavior than in the variant currently visible.
393 /// For instance, we could have started with
394 ///
395 /// void foo(int *v) {
396 /// int t = 5 / v[0];
397 /// (void) t;
398 /// }
399 ///
400 /// and "refined" it to
401 ///
402 /// void foo(int *v) { }
403 ///
404 /// However, we cannot infer readnone for `foo`, since that would justify
405 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
406 /// undefined behavior if the linker replaces the actual call destination with
407 /// the unoptimized `foo`.
408 ///
409 /// Inlining is okay across non-exact linkage types as long as they're not
410 /// interposable (see \c isInterposable), since in such cases the currently
411 /// visible variant is *a* correct implementation of the original source
412 /// function; it just isn't the *only* correct implementation.
413 bool isDefinitionExact() const {
414 return !mayBeDerefined();
415 }
416
417 /// Return true if this global has an exact defintion.
418 bool hasExactDefinition() const {
419 // While this computes exactly the same thing as
420 // isStrongDefinitionForLinker, the intended uses are different. This
421 // function is intended to help decide if specific inter-procedural
422 // transforms are correct, while isStrongDefinitionForLinker's intended use
423 // is in low level code generation.
424 return !isDeclaration() && isDefinitionExact();
425 }
426
427 /// Return true if this global's definition can be substituted with an
428 /// *arbitrary* definition at link time or load time. We cannot do any IPO or
429 /// inlining across interposable call edges, since the callee can be
430 /// replaced with something arbitrary.
431 bool isInterposable() const;
432 bool canBenefitFromLocalAlias() const;
433
434 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
435 bool hasAvailableExternallyLinkage() const {
436 return isAvailableExternallyLinkage(getLinkage());
437 }
438 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
439 bool hasLinkOnceAnyLinkage() const {
440 return isLinkOnceAnyLinkage(getLinkage());
441 }
442 bool hasLinkOnceODRLinkage() const {
443 return isLinkOnceODRLinkage(getLinkage());
444 }
445 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
446 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
447 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
448 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
449 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
450 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
451 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
452 bool hasExternalWeakLinkage() const {
453 return isExternalWeakLinkage(getLinkage());
454 }
455 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
456 bool hasValidDeclarationLinkage() const {
457 return isValidDeclarationLinkage(getLinkage());
458 }
459
460 void setLinkage(LinkageTypes LT) {
461 if (isLocalLinkage(LT))
462 Visibility = DefaultVisibility;
463 Linkage = LT;
464 if (isImplicitDSOLocal())
465 setDSOLocal(true);
466 }
467 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
468
469 bool isDiscardableIfUnused() const {
470 return isDiscardableIfUnused(getLinkage());
471 }
472
473 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
474
475protected:
476 /// Copy all additional attributes (those not needed to create a GlobalValue)
477 /// from the GlobalValue Src to this one.
478 void copyAttributesFrom(const GlobalValue *Src);
479
480public:
481 /// If the given string begins with the GlobalValue name mangling escape
482 /// character '\1', drop it.
483 ///
484 /// This function applies a specific mangling that is used in PGO profiles,
485 /// among other things. If you're trying to get a symbol name for an
486 /// arbitrary GlobalValue, this is not the function you're looking for; see
487 /// Mangler.h.
488 static StringRef dropLLVMManglingEscape(StringRef Name) {
489 if (!Name.empty() && Name[0] == '\1')
490 return Name.substr(1);
491 return Name;
492 }
493
494 /// Return the modified name for a global value suitable to be
495 /// used as the key for a global lookup (e.g. profile or ThinLTO).
496 /// The value's original name is \c Name and has linkage of type
497 /// \c Linkage. The value is defined in module \c FileName.
498 static std::string getGlobalIdentifier(StringRef Name,
499 GlobalValue::LinkageTypes Linkage,
500 StringRef FileName);
501
502 /// Return the modified name for this global value suitable to be
503 /// used as the key for a global lookup (e.g. profile or ThinLTO).
504 std::string getGlobalIdentifier() const;
505
506 /// Declare a type to represent a global unique identifier for a global value.
507 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
508 /// unique way to identify a symbol.
509 using GUID = uint64_t;
510
511 /// Return a 64-bit global unique ID constructed from global value name
512 /// (i.e. returned by getGlobalIdentifier()).
513 static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
514
515 /// Return a 64-bit global unique ID constructed from global value name
516 /// (i.e. returned by getGlobalIdentifier()).
517 GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
518
519 /// @name Materialization
520 /// Materialization is used to construct functions only as they're needed.
521 /// This
522 /// is useful to reduce memory usage in LLVM or parsing work done by the
523 /// BitcodeReader to load the Module.
524 /// @{
525
526 /// If this function's Module is being lazily streamed in functions from disk
527 /// or some other source, this method can be used to check to see if the
528 /// function has been read in yet or not.
529 bool isMaterializable() const;
530
531 /// Make sure this GlobalValue is fully read.
532 Error materialize();
533
534/// @}
535
536 /// Return true if the primary definition of this global value is outside of
537 /// the current translation unit.
538 bool isDeclaration() const;
539
540 bool isDeclarationForLinker() const {
541 if (hasAvailableExternallyLinkage())
542 return true;
543
544 return isDeclaration();
545 }
546
547 /// Returns true if this global's definition will be the one chosen by the
548 /// linker.
549 ///
550 /// NB! Ideally this should not be used at the IR level at all. If you're
551 /// interested in optimization constraints implied by the linker's ability to
552 /// choose an implementation, prefer using \c hasExactDefinition.
553 bool isStrongDefinitionForLinker() const {
554 return !(isDeclarationForLinker() || isWeakForLinker());
555 }
556
557 const GlobalObject *getAliaseeObject() const;
558 GlobalObject *getAliaseeObject() {
559 return const_cast<GlobalObject *>(
560 static_cast<const GlobalValue *>(this)->getAliaseeObject());
561 }
562
563 /// Returns whether this is a reference to an absolute symbol.
564 bool isAbsoluteSymbolRef() const;
565
566 /// If this is an absolute symbol reference, returns the range of the symbol,
567 /// otherwise returns None.
568 Optional<ConstantRange> getAbsoluteSymbolRange() const;
569
570 /// This method unlinks 'this' from the containing module, but does not delete
571 /// it.
572 void removeFromParent();
573
574 /// This method unlinks 'this' from the containing module and deletes it.
575 void eraseFromParent();
576
577 /// Get the module that this global value is contained inside of...
578 Module *getParent() { return Parent; }
579 const Module *getParent() const { return Parent; }
580
581 // Methods for support type inquiry through isa, cast, and dyn_cast:
582 static bool classof(const Value *V) {
583 return V->getValueID() == Value::FunctionVal ||
584 V->getValueID() == Value::GlobalVariableVal ||
585 V->getValueID() == Value::GlobalAliasVal ||
586 V->getValueID() == Value::GlobalIFuncVal;
587 }
588
589 /// True if GV can be left out of the object symbol table. This is the case
590 /// for linkonce_odr values whose address is not significant. While legal, it
591 /// is not normally profitable to omit them from the .o symbol table. Using
592 /// this analysis makes sense when the information can be passed down to the
593 /// linker or we are in LTO.
594 bool canBeOmittedFromSymbolTable() const;
595};
596
597} // end namespace llvm
598
599#endif // LLVM_IR_GLOBALVALUE_H
600