LLVM 22.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"
29#include <cassert>
30#include <cstddef>
31
32namespace llvm {
33
34class Constant;
35class Module;
36
37template <typename ValueSubClass, typename... Args> class SymbolTableListTraits;
39
40class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> {
42
43 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1};
44
45 AttributeSet Attrs;
46
47 // Is this a global constant?
48 bool isConstantGlobal : 1;
49 // Is this a global whose value can change from its initial value before
50 // global initializers are run?
51 bool isExternallyInitializedConstant : 1;
52
53private:
54 static const unsigned CodeModelBits = LastCodeModelBit - LastAlignmentBit;
55 static const unsigned CodeModelMask = (1 << CodeModelBits) - 1;
56 static const unsigned CodeModelShift = LastAlignmentBit + 1;
57
58public:
59 /// GlobalVariable ctor - If a parent module is specified, the global is
60 /// automatically inserted into the end of the specified modules global list.
62 Constant *Initializer = nullptr,
63 const Twine &Name = "",
65 unsigned AddressSpace = 0,
66 bool isExternallyInitialized = false);
67 /// GlobalVariable ctor - This creates a global and inserts it before the
68 /// specified other global.
70 LinkageTypes Linkage, Constant *Initializer,
71 const Twine &Name = "",
72 GlobalVariable *InsertBefore = nullptr,
74 std::optional<unsigned> AddressSpace = std::nullopt,
75 bool isExternallyInitialized = false);
76 GlobalVariable(const GlobalVariable &) = delete;
78
79private:
80 /// Set the number of operands on a GlobalVariable.
81 ///
82 /// GlobalVariable always allocates space for a single operands, but
83 /// doesn't always use it.
84 void setGlobalVariableNumOperands(unsigned NumOps) {
85 assert(NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands");
86 NumUserOperands = NumOps;
87 }
88
89public:
92
93 // Number of operands can be set to 0 after construction and initialization.
94 // Make sure that number of operands is reset to 1, as this is needed in
95 // User::operator delete
96 setGlobalVariableNumOperands(1);
97 }
98
99 // allocate space for exactly one operand
100 void *operator new(size_t s) { return User::operator new(s, AllocMarker); }
101
102 // delete space for exactly one operand as created in the corresponding new operator
103 void operator delete(void *ptr) { User::operator delete(ptr); }
104
105 /// Provide fast operand accessors
107
108 /// Definitions have initializers, declarations don't.
109 ///
110 inline bool hasInitializer() const { return !isDeclaration(); }
111
112 /// hasDefinitiveInitializer - Whether the global variable has an initializer,
113 /// and any other instances of the global (this can happen due to weak
114 /// linkage) are guaranteed to have the same initializer.
115 ///
116 /// Note that if you want to transform a global, you must use
117 /// hasUniqueInitializer() instead, because of the *_odr linkage type.
118 ///
119 /// Example:
120 ///
121 /// @a = global SomeType* null - Initializer is both definitive and unique.
122 ///
123 /// @b = global weak SomeType* null - Initializer is neither definitive nor
124 /// unique.
125 ///
126 /// @c = global weak_odr SomeType* null - Initializer is definitive, but not
127 /// unique.
128 inline bool hasDefinitiveInitializer() const {
129 return hasInitializer() &&
130 // The initializer of a global variable may change to something arbitrary
131 // at link time.
132 !isInterposable() &&
133 // The initializer of a global variable with the externally_initialized
134 // marker may change at runtime before C++ initializers are evaluated.
136 }
137
138 /// hasUniqueInitializer - Whether the global variable has an initializer, and
139 /// any changes made to the initializer will turn up in the final executable.
140 inline bool hasUniqueInitializer() const {
141 return
142 // We need to be sure this is the definition that will actually be used
144 // It is not safe to modify initializers of global variables with the
145 // external_initializer marker since the value may be changed at runtime
146 // before C++ initializers are evaluated.
148 }
149
150 /// getInitializer - Return the initializer for this global variable. It is
151 /// illegal to call this method if the global is external, because we cannot
152 /// tell what the value is initialized to!
153 ///
154 inline const Constant *getInitializer() const {
155 assert(hasInitializer() && "GV doesn't have initializer!");
156 return static_cast<Constant*>(Op<0>().get());
157 }
159 assert(hasInitializer() && "GV doesn't have initializer!");
160 return static_cast<Constant*>(Op<0>().get());
161 }
162 /// setInitializer - Sets the initializer for this global variable, removing
163 /// any existing initializer if InitVal==NULL. The initializer must have the
164 /// type getValueType().
165 LLVM_ABI void setInitializer(Constant *InitVal);
166
167 /// replaceInitializer - Sets the initializer for this global variable, and
168 /// sets the value type of the global to the type of the initializer. The
169 /// initializer must not be null. This may affect the global's alignment if
170 /// it isn't explicitly set.
171 LLVM_ABI void replaceInitializer(Constant *InitVal);
172
173 /// If the value is a global constant, its value is immutable throughout the
174 /// runtime execution of the program. Assigning a value into the constant
175 /// leads to undefined behavior.
176 ///
177 bool isConstant() const { return isConstantGlobal; }
178 void setConstant(bool Val) { isConstantGlobal = Val; }
179
181 return isExternallyInitializedConstant;
182 }
184 isExternallyInitializedConstant = Val;
185 }
186
187 /// copyAttributesFrom - copy all additional attributes (those not needed to
188 /// create a GlobalVariable) from the GlobalVariable Src to this one.
190
191 /// removeFromParent - This method unlinks 'this' from the containing module,
192 /// but does not delete it.
193 ///
195
196 /// eraseFromParent - This method unlinks 'this' from the containing module
197 /// and deletes it.
198 ///
200
201 /// Drop all references in preparation to destroy the GlobalVariable. This
202 /// drops not only the reference to the initializer but also to any metadata.
204
205 /// Attach a DIGlobalVariableExpression.
207
208 /// Fill the vector with all debug info attachements.
209 LLVM_ABI void
211
212 /// Add attribute to this global.
214 Attrs = Attrs.addAttribute(getContext(), Kind);
215 }
216
217 /// Add attribute to this global.
219 Attrs = Attrs.addAttribute(getContext(), Kind, Val);
220 }
221
222 /// Return true if the attribute exists.
224 return Attrs.hasAttribute(Kind);
225 }
226
227 /// Return true if the attribute exists.
228 bool hasAttribute(StringRef Kind) const {
229 return Attrs.hasAttribute(Kind);
230 }
231
232 /// Return true if any attributes exist.
233 bool hasAttributes() const {
234 return Attrs.hasAttributes();
235 }
236
237 /// Return the attribute object.
239 return Attrs.getAttribute(Kind);
240 }
241
242 /// Return the attribute object.
244 return Attrs.getAttribute(Kind);
245 }
246
247 /// Return the attribute set for this global
249 return Attrs;
250 }
251
252 /// Return attribute set as list with index.
253 /// FIXME: This may not be required once ValueEnumerators
254 /// in bitcode-writer can enumerate attribute-set.
255 AttributeList getAttributesAsList(unsigned index) const {
256 if (!hasAttributes())
257 return AttributeList();
258 std::pair<unsigned, AttributeSet> AS[1] = {{index, Attrs}};
259 return AttributeList::get(getContext(), AS);
260 }
261
262 /// Set attribute list for this global
264 Attrs = A;
265 }
266
267 /// Check if section name is present
268 bool hasImplicitSection() const {
269 return getAttributes().hasAttribute("bss-section") ||
270 getAttributes().hasAttribute("data-section") ||
271 getAttributes().hasAttribute("relro-section") ||
272 getAttributes().hasAttribute("rodata-section");
273 }
274
275 /// Get the custom code model raw value of this global.
276 ///
277 unsigned getCodeModelRaw() const {
278 unsigned Data = getGlobalValueSubClassData();
279 return (Data >> CodeModelShift) & CodeModelMask;
280 }
281
282 /// Get the custom code model of this global if it has one.
283 ///
284 /// If this global does not have a custom code model, the empty instance
285 /// will be returned.
286 std::optional<CodeModel::Model> getCodeModel() const {
287 unsigned CodeModelData = getCodeModelRaw();
288 if (CodeModelData > 0)
289 return static_cast<CodeModel::Model>(CodeModelData - 1);
290 return {};
291 }
292
293 /// Change the code model for this global.
294 ///
296
297 /// Remove the code model for this global.
298 ///
300
301 /// FIXME: Remove this function once transition to Align is over.
304 return Align ? Align->value() : 0;
305 }
306
307 /// Returns the alignment of the given variable.
309
310 /// Sets the alignment attribute of the GlobalVariable.
312
313 /// Sets the alignment attribute of the GlobalVariable.
314 /// This method will be deprecated as the alignment property should always be
315 /// defined.
317
318 // Methods for support type inquiry through isa, cast, and dyn_cast:
319 static bool classof(const Value *V) {
320 return V->getValueID() == Value::GlobalVariableVal;
321 }
322};
323
324template <>
326 public OptionalOperandTraits<GlobalVariable> {
327};
328
330
331} // end namespace llvm
332
333#endif // LLVM_IR_GLOBALVARIABLE_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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")
#define LLVM_ABI
Definition: Compiler.h:213
std::string Name
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS)
Macro for generating out-of-class operand accessor definitions.
static LLVM_ABI AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
LLVM_ABI 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:88
This is an important base class in LLVM.
Definition: Constant.h:43
A pair of DIGlobalVariable and DIExpression.
This class represents an Operation in the Expression.
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:75
LLVM_ABI void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:145
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:316
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
Definition: GlobalValue.h:638
LLVM_ABI bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition: Globals.cpp:107
unsigned getGlobalValueSubClassData() const
Definition: GlobalValue.h:177
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:52
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:511
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.
LLVM_ABI void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition: Globals.cpp:503
bool hasAttributes() const
Return true if any attributes exist.
void setAlignment(MaybeAlign Align)
Sets the alignment attribute of the GlobalVariable.
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.
LLVM_ABI void replaceInitializer(Constant *InitVal)
replaceInitializer - Sets the initializer for this global variable, and sets the value type of the gl...
Definition: Globals.cpp:532
LLVM_ABI void clearCodeModel()
Remove the code model for this global.
Definition: Globals.cpp:562
MaybeAlign getAlign() const
Returns the alignment of the given variable.
void setConstant(bool Val)
GlobalVariable & operator=(const GlobalVariable &)=delete
LLVM_ABI void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:540
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.
uint64_t getAlignment() const
FIXME: Remove this function once transition to Align is over.
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1932
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...
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition: Globals.cpp:553
bool hasUniqueInitializer() const
hasUniqueInitializer - Whether the global variable has an initializer, and any changes made to the in...
void setExternallyInitialized(bool Val)
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:507
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1928
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
void addAttribute(Attribute::AttrKind Kind)
Add attribute to this global.
LLVM_ABI void dropAllReferences()
Drop all references in preparation to destroy the GlobalVariable.
Definition: Globals.cpp:548
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
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:75
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1098
unsigned NumUserOperands
Definition: Value.h:109
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
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
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