1//===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===//
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 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
14// constant.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_IR_GLOBALVALUE_H
19#define LLVM_IR_GLOBALVALUE_H
20
21#include "llvm/IR/Constant.h"
22#include "llvm/IR/DerivedTypes.h"
23#include <system_error>
24
25namespace llvm {
26
27class Comdat;
28class PointerType;
29class Module;
30
31class GlobalValue : public Constant {
32  GlobalValue(const GlobalValue &) = delete;
33public:
34  /// @brief An enumeration for the kinds of linkage for global values.
35  enum LinkageTypes {
36    ExternalLinkage = 0,///< Externally visible function
37    AvailableExternallyLinkage, ///< Available for inspection, not emission.
38    LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
39    LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
40    WeakAnyLinkage,     ///< Keep one copy of named function when linking (weak)
41    WeakODRLinkage,     ///< Same, but only replaced by something equivalent.
42    AppendingLinkage,   ///< Special purpose, only applies to global arrays
43    InternalLinkage,    ///< Rename collisions when linking (static functions).
44    PrivateLinkage,     ///< Like Internal, but omit from symbol table.
45    ExternalWeakLinkage,///< ExternalWeak linkage description.
46    CommonLinkage       ///< Tentative definitions.
47  };
48
49  /// @brief An enumeration for the kinds of visibility of global values.
50  enum VisibilityTypes {
51    DefaultVisibility = 0,  ///< The GV is visible
52    HiddenVisibility,       ///< The GV is hidden
53    ProtectedVisibility     ///< The GV is protected
54  };
55
56  /// @brief Storage classes of global values for PE targets.
57  enum DLLStorageClassTypes {
58    DefaultStorageClass   = 0,
59    DLLImportStorageClass = 1, ///< Function to be imported from DLL
60    DLLExportStorageClass = 2  ///< Function to be accessible from DLL.
61  };
62
63protected:
64  GlobalValue(PointerType *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
65              LinkageTypes Linkage, const Twine &Name)
66      : Constant(Ty, VTy, Ops, NumOps), Linkage(Linkage),
67        Visibility(DefaultVisibility), UnnamedAddr(0),
68        DllStorageClass(DefaultStorageClass),
69        ThreadLocal(NotThreadLocal), Parent(nullptr) {
70    setName(Name);
71  }
72
73  // Note: VC++ treats enums as signed, so an extra bit is required to prevent
74  // Linkage and Visibility from turning into negative values.
75  LinkageTypes Linkage : 5;   // The linkage of this global
76  unsigned Visibility : 2;    // The visibility style of this global
77  unsigned UnnamedAddr : 1;   // This value's address is not significant
78  unsigned DllStorageClass : 2; // DLL storage class
79
80  unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
81                            // the desired model?
82
83private:
84  // Give subclasses access to what otherwise would be wasted padding.
85  // (19 + 3 + 2 + 1 + 2 + 5) == 32.
86  unsigned SubClassData : 19;
87protected:
88  static const unsigned GlobalValueSubClassDataBits = 19;
89  unsigned getGlobalValueSubClassData() const {
90    return SubClassData;
91  }
92  void setGlobalValueSubClassData(unsigned V) {
93    assert(V < (1 << 19) && "It will not fit");
94    SubClassData = V;
95  }
96
97  Module *Parent;             // The containing module.
98public:
99  enum ThreadLocalMode {
100    NotThreadLocal = 0,
101    GeneralDynamicTLSModel,
102    LocalDynamicTLSModel,
103    InitialExecTLSModel,
104    LocalExecTLSModel
105  };
106
107  ~GlobalValue() override {
108    removeDeadConstantUsers();   // remove any dead constants using this.
109  }
110
111  unsigned getAlignment() const;
112
113  bool hasUnnamedAddr() const { return UnnamedAddr; }
114  void setUnnamedAddr(bool Val) { UnnamedAddr = Val; }
115
116  bool hasComdat() const { return getComdat() != nullptr; }
117  Comdat *getComdat();
118  const Comdat *getComdat() const {
119    return const_cast<GlobalValue *>(this)->getComdat();
120  }
121
122  VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
123  bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
124  bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
125  bool hasProtectedVisibility() const {
126    return Visibility == ProtectedVisibility;
127  }
128  void setVisibility(VisibilityTypes V) {
129    assert((!hasLocalLinkage() || V == DefaultVisibility) &&
130           "local linkage requires default visibility");
131    Visibility = V;
132  }
133
134  /// If the value is "Thread Local", its value isn't shared by the threads.
135  bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
136  void setThreadLocal(bool Val) {
137    setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
138  }
139  void setThreadLocalMode(ThreadLocalMode Val) {
140    assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
141    ThreadLocal = Val;
142  }
143  ThreadLocalMode getThreadLocalMode() const {
144    return static_cast<ThreadLocalMode>(ThreadLocal);
145  }
146
147  DLLStorageClassTypes getDLLStorageClass() const {
148    return DLLStorageClassTypes(DllStorageClass);
149  }
150  bool hasDLLImportStorageClass() const {
151    return DllStorageClass == DLLImportStorageClass;
152  }
153  bool hasDLLExportStorageClass() const {
154    return DllStorageClass == DLLExportStorageClass;
155  }
156  void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
157
158  bool hasSection() const { return !StringRef(getSection()).empty(); }
159  // It is unfortunate that we have to use "char *" in here since this is
160  // always non NULL, but:
161  // * The C API expects a null terminated string, so we cannot use StringRef.
162  // * The C API expects us to own it, so we cannot use a std:string.
163  // * For GlobalAliases we can fail to find the section and we have to
164  //   return "", so we cannot use a "const std::string &".
165  const char *getSection() const;
166
167  /// Global values are always pointers.
168  PointerType *getType() const { return cast<PointerType>(User::getType()); }
169
170  Type *getValueType() const { return getType()->getElementType(); }
171
172  static LinkageTypes getLinkOnceLinkage(bool ODR) {
173    return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
174  }
175  static LinkageTypes getWeakLinkage(bool ODR) {
176    return ODR ? WeakODRLinkage : WeakAnyLinkage;
177  }
178
179  static bool isExternalLinkage(LinkageTypes Linkage) {
180    return Linkage == ExternalLinkage;
181  }
182  static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
183    return Linkage == AvailableExternallyLinkage;
184  }
185  static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
186    return Linkage == LinkOnceODRLinkage;
187  }
188  static bool isLinkOnceLinkage(LinkageTypes Linkage) {
189    return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage;
190  }
191  static bool isWeakAnyLinkage(LinkageTypes Linkage) {
192    return Linkage == WeakAnyLinkage;
193  }
194  static bool isWeakODRLinkage(LinkageTypes Linkage) {
195    return Linkage == WeakODRLinkage;
196  }
197  static bool isWeakLinkage(LinkageTypes Linkage) {
198    return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
199  }
200  static bool isAppendingLinkage(LinkageTypes Linkage) {
201    return Linkage == AppendingLinkage;
202  }
203  static bool isInternalLinkage(LinkageTypes Linkage) {
204    return Linkage == InternalLinkage;
205  }
206  static bool isPrivateLinkage(LinkageTypes Linkage) {
207    return Linkage == PrivateLinkage;
208  }
209  static bool isLocalLinkage(LinkageTypes Linkage) {
210    return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
211  }
212  static bool isExternalWeakLinkage(LinkageTypes Linkage) {
213    return Linkage == ExternalWeakLinkage;
214  }
215  static bool isCommonLinkage(LinkageTypes Linkage) {
216    return Linkage == CommonLinkage;
217  }
218
219  /// Whether the definition of this global may be discarded if it is not used
220  /// in its compilation unit.
221  static bool isDiscardableIfUnused(LinkageTypes Linkage) {
222    return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage);
223  }
224
225  /// Whether the definition of this global may be replaced by something
226  /// non-equivalent at link time. For example, if a function has weak linkage
227  /// then the code defining it may be replaced by different code.
228  static bool mayBeOverridden(LinkageTypes Linkage) {
229    return Linkage == WeakAnyLinkage || Linkage == LinkOnceAnyLinkage ||
230           Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
231  }
232
233  /// Whether the definition of this global may be replaced at link time.  NB:
234  /// Using this method outside of the code generators is almost always a
235  /// mistake: when working at the IR level use mayBeOverridden instead as it
236  /// knows about ODR semantics.
237  static bool isWeakForLinker(LinkageTypes Linkage)  {
238    return Linkage == AvailableExternallyLinkage || Linkage == WeakAnyLinkage ||
239           Linkage == WeakODRLinkage || Linkage == LinkOnceAnyLinkage ||
240           Linkage == LinkOnceODRLinkage || Linkage == CommonLinkage ||
241           Linkage == ExternalWeakLinkage;
242  }
243
244  bool hasExternalLinkage() const { return isExternalLinkage(Linkage); }
245  bool hasAvailableExternallyLinkage() const {
246    return isAvailableExternallyLinkage(Linkage);
247  }
248  bool hasLinkOnceLinkage() const {
249    return isLinkOnceLinkage(Linkage);
250  }
251  bool hasLinkOnceODRLinkage() const { return isLinkOnceODRLinkage(Linkage); }
252  bool hasWeakLinkage() const {
253    return isWeakLinkage(Linkage);
254  }
255  bool hasWeakAnyLinkage() const {
256    return isWeakAnyLinkage(Linkage);
257  }
258  bool hasWeakODRLinkage() const {
259    return isWeakODRLinkage(Linkage);
260  }
261  bool hasAppendingLinkage() const { return isAppendingLinkage(Linkage); }
262  bool hasInternalLinkage() const { return isInternalLinkage(Linkage); }
263  bool hasPrivateLinkage() const { return isPrivateLinkage(Linkage); }
264  bool hasLocalLinkage() const { return isLocalLinkage(Linkage); }
265  bool hasExternalWeakLinkage() const { return isExternalWeakLinkage(Linkage); }
266  bool hasCommonLinkage() const { return isCommonLinkage(Linkage); }
267
268  void setLinkage(LinkageTypes LT) {
269    if (isLocalLinkage(LT))
270      Visibility = DefaultVisibility;
271    Linkage = LT;
272  }
273  LinkageTypes getLinkage() const { return Linkage; }
274
275  bool isDiscardableIfUnused() const {
276    return isDiscardableIfUnused(Linkage);
277  }
278
279  bool mayBeOverridden() const { return mayBeOverridden(Linkage); }
280
281  bool isWeakForLinker() const { return isWeakForLinker(Linkage); }
282
283  /// Copy all additional attributes (those not needed to create a GlobalValue)
284  /// from the GlobalValue Src to this one.
285  virtual void copyAttributesFrom(const GlobalValue *Src);
286
287  /// If special LLVM prefix that is used to inform the asm printer to not emit
288  /// usual symbol prefix before the symbol name is used then return linkage
289  /// name after skipping this special LLVM prefix.
290  static StringRef getRealLinkageName(StringRef Name) {
291    if (!Name.empty() && Name[0] == '\1')
292      return Name.substr(1);
293    return Name;
294  }
295
296/// @name Materialization
297/// Materialization is used to construct functions only as they're needed. This
298/// is useful to reduce memory usage in LLVM or parsing work done by the
299/// BitcodeReader to load the Module.
300/// @{
301
302  /// If this function's Module is being lazily streamed in functions from disk
303  /// or some other source, this method can be used to check to see if the
304  /// function has been read in yet or not.
305  bool isMaterializable() const;
306
307  /// Returns true if this function was loaded from a GVMaterializer that's
308  /// still attached to its Module and that knows how to dematerialize the
309  /// function.
310  bool isDematerializable() const;
311
312  /// Make sure this GlobalValue is fully read. If the module is corrupt, this
313  /// returns true and fills in the optional string with information about the
314  /// problem.  If successful, this returns false.
315  std::error_code materialize();
316
317  /// If this GlobalValue is read in, and if the GVMaterializer supports it,
318  /// release the memory for the function, and set it up to be materialized
319  /// lazily. If !isDematerializable(), this method is a noop.
320  void Dematerialize();
321
322/// @}
323
324  /// Override from Constant class.
325  void destroyConstant() override;
326
327  /// Return true if the primary definition of this global value is outside of
328  /// the current translation unit.
329  bool isDeclaration() const;
330
331  bool isDeclarationForLinker() const {
332    if (hasAvailableExternallyLinkage())
333      return true;
334
335    return isDeclaration();
336  }
337
338  /// This method unlinks 'this' from the containing module, but does not delete
339  /// it.
340  virtual void removeFromParent() = 0;
341
342  /// This method unlinks 'this' from the containing module and deletes it.
343  virtual void eraseFromParent() = 0;
344
345  /// Get the module that this global value is contained inside of...
346  Module *getParent() { return Parent; }
347  const Module *getParent() const { return Parent; }
348
349  // Methods for support type inquiry through isa, cast, and dyn_cast:
350  static bool classof(const Value *V) {
351    return V->getValueID() == Value::FunctionVal ||
352           V->getValueID() == Value::GlobalVariableVal ||
353           V->getValueID() == Value::GlobalAliasVal;
354  }
355};
356
357} // End llvm namespace
358
359#endif
360