LLVM 20.0.0git
GlobalVariable.h
Go to the documentation of this file.
1//===-- llvm/GlobalVariable.h - GlobalVariable class ------------*- 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 contains the declaration of the GlobalVariable class, which
10// represents a single global variable (or constant) in the VM.
11//
12// Global variables are constant pointers that refer to hunks of space that are
13// allocated by either the VM, or by the linker in a static compiler. A global
14// variable may have an initial value, which is copied into the executables .data
15// area. Global Constants are required to have initializers.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_IR_GLOBALVARIABLE_H
20#define LLVM_IR_GLOBALVARIABLE_H
21
22#include "llvm/ADT/Twine.h"
23#include "llvm/ADT/ilist_node.h"
24#include "llvm/IR/Attributes.h"
27#include "llvm/IR/Value.h"
28#include <cassert>
29#include <cstddef>
30
31namespace llvm {
32
33class Constant;
34class Module;
35
36template <typename ValueSubClass, typename... Args> class SymbolTableListTraits;
38
39class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> {
41
42 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1};
43
44 AttributeSet Attrs;
45
46 // Is this a global constant?
47 bool isConstantGlobal : 1;
48 // Is this a global whose value can change from its initial value before
49 // global initializers are run?
50 bool isExternallyInitializedConstant : 1;
51
52private:
53 static const unsigned CodeModelBits = LastCodeModelBit - LastAlignmentBit;
54 static const unsigned CodeModelMask = (1 << CodeModelBits) - 1;
55 static const unsigned CodeModelShift = LastAlignmentBit + 1;
56
57public:
58 /// GlobalVariable ctor - If a parent module is specified, the global is
59 /// automatically inserted into the end of the specified modules global list.
61 Constant *Initializer = nullptr, const Twine &Name = "",
63 bool isExternallyInitialized = false);
64 /// GlobalVariable ctor - This creates a global and inserts it before the
65 /// specified other global.
67 Constant *Initializer, const Twine &Name = "",
68 GlobalVariable *InsertBefore = nullptr,
70 std::optional<unsigned> AddressSpace = std::nullopt,
71 bool isExternallyInitialized = false);
72 GlobalVariable(const GlobalVariable &) = delete;
74
75private:
76 /// Set the number of operands on a GlobalVariable.
77 ///
78 /// GlobalVariable always allocates space for a single operands, but
79 /// doesn't always use it.
80 void setGlobalVariableNumOperands(unsigned NumOps) {
81 assert(NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands");
82 NumUserOperands = NumOps;
83 }
84
85public:
88
89 // Number of operands can be set to 0 after construction and initialization.
90 // Make sure that number of operands is reset to 1, as this is needed in
91 // User::operator delete
92 setGlobalVariableNumOperands(1);
93 }
94
95 // allocate space for exactly one operand
96 void *operator new(size_t s) { return User::operator new(s, AllocMarker); }
97
98 // delete space for exactly one operand as created in the corresponding new operator
99 void operator delete(void *ptr) { User::operator delete(ptr); }
100
101 /// Provide fast operand accessors
103
104 /// Definitions have initializers, declarations don't.
105 ///
106 inline bool hasInitializer() const { return !isDeclaration(); }
107
108 /// hasDefinitiveInitializer - Whether the global variable has an initializer,
109 /// and any other instances of the global (this can happen due to weak
110 /// linkage) are guaranteed to have the same initializer.
111 ///
112 /// Note that if you want to transform a global, you must use
113 /// hasUniqueInitializer() instead, because of the *_odr linkage type.
114 ///
115 /// Example:
116 ///
117 /// @a = global SomeType* null - Initializer is both definitive and unique.
118 ///
119 /// @b = global weak SomeType* null - Initializer is neither definitive nor
120 /// unique.
121 ///
122 /// @c = global weak_odr SomeType* null - Initializer is definitive, but not
123 /// unique.
124 inline bool hasDefinitiveInitializer() const {
125 return hasInitializer() &&
126 // The initializer of a global variable may change to something arbitrary
127 // at link time.
128 !isInterposable() &&
129 // The initializer of a global variable with the externally_initialized
130 // marker may change at runtime before C++ initializers are evaluated.
132 }
133
134 /// hasUniqueInitializer - Whether the global variable has an initializer, and
135 /// any changes made to the initializer will turn up in the final executable.
136 inline bool hasUniqueInitializer() const {
137 return
138 // We need to be sure this is the definition that will actually be used
140 // It is not safe to modify initializers of global variables with the
141 // external_initializer marker since the value may be changed at runtime
142 // before C++ initializers are evaluated.
144 }
145
146 /// getInitializer - Return the initializer for this global variable. It is
147 /// illegal to call this method if the global is external, because we cannot
148 /// tell what the value is initialized to!
149 ///
150 inline const Constant *getInitializer() const {
151 assert(hasInitializer() && "GV doesn't have initializer!");
152 return static_cast<Constant*>(Op<0>().get());
153 }
155 assert(hasInitializer() && "GV doesn't have initializer!");
156 return static_cast<Constant*>(Op<0>().get());
157 }
158 /// setInitializer - Sets the initializer for this global variable, removing
159 /// any existing initializer if InitVal==NULL. The initializer must have the
160 /// type getValueType().
161 void setInitializer(Constant *InitVal);
162
163 /// replaceInitializer - Sets the initializer for this global variable, and
164 /// sets the value type of the global to the type of the initializer. The
165 /// initializer must not be null. This may affect the global's alignment if
166 /// it isn't explicitly set.
167 void replaceInitializer(Constant *InitVal);
168
169 /// If the value is a global constant, its value is immutable throughout the
170 /// runtime execution of the program. Assigning a value into the constant
171 /// leads to undefined behavior.
172 ///
173 bool isConstant() const { return isConstantGlobal; }
174 void setConstant(bool Val) { isConstantGlobal = Val; }
175
177 return isExternallyInitializedConstant;
178 }
180 isExternallyInitializedConstant = Val;
181 }
182
183 /// copyAttributesFrom - copy all additional attributes (those not needed to
184 /// create a GlobalVariable) from the GlobalVariable Src to this one.
185 void copyAttributesFrom(const GlobalVariable *Src);
186
187 /// removeFromParent - This method unlinks 'this' from the containing module,
188 /// but does not delete it.
189 ///
190 void removeFromParent();
191
192 /// eraseFromParent - This method unlinks 'this' from the containing module
193 /// and deletes it.
194 ///
195 void eraseFromParent();
196
197 /// Drop all references in preparation to destroy the GlobalVariable. This
198 /// drops not only the reference to the initializer but also to any metadata.
199 void dropAllReferences();
200
201 /// Attach a DIGlobalVariableExpression.
203
204 /// Fill the vector with all debug info attachements.
206
207 /// Add attribute to this global.
209 Attrs = Attrs.addAttribute(getContext(), Kind);
210 }
211
212 /// Add attribute to this global.
214 Attrs = Attrs.addAttribute(getContext(), Kind, Val);
215 }
216
217 /// Return true if the attribute exists.
219 return Attrs.hasAttribute(Kind);
220 }
221
222 /// Return true if the attribute exists.
223 bool hasAttribute(StringRef Kind) const {
224 return Attrs.hasAttribute(Kind);
225 }
226
227 /// Return true if any attributes exist.
228 bool hasAttributes() const {
229 return Attrs.hasAttributes();
230 }
231
232 /// Return the attribute object.
234 return Attrs.getAttribute(Kind);
235 }
236
237 /// Return the attribute object.
239 return Attrs.getAttribute(Kind);
240 }
241
242 /// Return the attribute set for this global
244 return Attrs;
245 }
246
247 /// Return attribute set as list with index.
248 /// FIXME: This may not be required once ValueEnumerators
249 /// in bitcode-writer can enumerate attribute-set.
250 AttributeList getAttributesAsList(unsigned index) const {
251 if (!hasAttributes())
252 return AttributeList();
253 std::pair<unsigned, AttributeSet> AS[1] = {{index, Attrs}};
254 return AttributeList::get(getContext(), AS);
255 }
256
257 /// Set attribute list for this global
259 Attrs = A;
260 }
261
262 /// Check if section name is present
263 bool hasImplicitSection() const {
264 return getAttributes().hasAttribute("bss-section") ||
265 getAttributes().hasAttribute("data-section") ||
266 getAttributes().hasAttribute("relro-section") ||
267 getAttributes().hasAttribute("rodata-section");
268 }
269
270 /// Get the custom code model raw value of this global.
271 ///
272 unsigned getCodeModelRaw() const {
273 unsigned Data = getGlobalValueSubClassData();
274 return (Data >> CodeModelShift) & CodeModelMask;
275 }
276
277 /// Get the custom code model of this global if it has one.
278 ///
279 /// If this global does not have a custom code model, the empty instance
280 /// will be returned.
281 std::optional<CodeModel::Model> getCodeModel() const {
282 unsigned CodeModelData = getCodeModelRaw();
283 if (CodeModelData > 0)
284 return static_cast<CodeModel::Model>(CodeModelData - 1);
285 return {};
286 }
287
288 /// Change the code model for this global.
289 ///
291
292 // Methods for support type inquiry through isa, cast, and dyn_cast:
293 static bool classof(const Value *V) {
294 return V->getValueID() == Value::GlobalVariableVal;
295 }
296};
297
298template <>
300 public OptionalOperandTraits<GlobalVariable> {
301};
302
304
305} // end namespace llvm
306
307#endif // LLVM_IR_GLOBALVARIABLE_H
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
std::string Name
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS)
Macro for generating out-of-class operand accessor definitions.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
This is an important base class in LLVM.
Definition: Constant.h:42
A pair of DIGlobalVariable and DIExpression.
This class represents an Operation in the Expression.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:296
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
Definition: GlobalValue.h:631
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition: Globals.cpp:105
unsigned getGlobalValueSubClassData() const
Definition: GlobalValue.h:175
unsigned Linkage
Definition: GlobalValue.h:98
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:492
unsigned getCodeModelRaw() const
Get the custom code model raw value of this global.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists.
bool isExternallyInitialized() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
Attribute getAttribute(Attribute::AttrKind Kind) const
Return the attribute object.
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition: Globals.cpp:484
bool hasAttributes() const
Return true if any attributes exist.
AttributeSet getAttributes() const
Return the attribute set for this global.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)
Provide fast operand accessors.
std::optional< CodeModel::Model > getCodeModel() const
Get the custom code model of this global if it has one.
void setAttributes(AttributeSet A)
Set attribute list for this global.
void replaceInitializer(Constant *InitVal)
replaceInitializer - Sets the initializer for this global variable, and sets the value type of the gl...
Definition: Globals.cpp:513
void setConstant(bool Val)
GlobalVariable & operator=(const GlobalVariable &)=delete
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:521
GlobalVariable(const GlobalVariable &)=delete
void addAttribute(StringRef Kind, StringRef Val=StringRef())
Add attribute to this global.
Constant * getInitializer()
bool hasImplicitSection() const
Check if section name is present.
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1891
AttributeList getAttributesAsList(unsigned index) const
Return attribute set as list with index.
Attribute getAttribute(StringRef Kind) const
Return the attribute object.
static bool classof(const Value *V)
bool hasAttribute(StringRef Kind) const
Return true if the attribute exists.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition: Globals.cpp:534
bool hasUniqueInitializer() const
hasUniqueInitializer - Whether the global variable has an initializer, and any changes made to the in...
void setExternallyInitialized(bool Val)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:488
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1887
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
void addAttribute(Attribute::AttrKind Kind)
Add attribute to this global.
void dropAllReferences()
Drop all references in preparation to destroy the GlobalVariable.
Definition: Globals.cpp:529
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
unsigned NumUserOperands
Definition: Value.h:108
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Compile-time customization of User operands.
Definition: User.h:42
OptionalOperandTraits - when the number of operands may change at runtime.
Definition: OperandTraits.h:53
Indicates this User has operands co-allocated.
Definition: User.h:60