LLVM 23.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 DataLayout;
36class Module;
37
38template <typename ValueSubClass, typename... Args> class SymbolTableListTraits;
40
41class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> {
43
44 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1};
45
46 AttributeSet Attrs;
47
48 // Is this a global constant?
49 bool isConstantGlobal : 1;
50 // Is this a global whose value can change from its initial value before
51 // global initializers are run?
52 bool isExternallyInitializedConstant : 1;
53
54private:
55 static const unsigned CodeModelBits = LastCodeModelBit - LastAlignmentBit;
56 static const unsigned CodeModelMask = (1 << CodeModelBits) - 1;
57 static const unsigned CodeModelShift = LastAlignmentBit + 1;
58
59public:
60 /// GlobalVariable ctor - If a parent module is specified, the global is
61 /// automatically inserted into the end of the specified modules global list.
63 Constant *Initializer = nullptr,
64 const Twine &Name = "",
66 unsigned AddressSpace = 0,
67 bool isExternallyInitialized = false);
68 /// GlobalVariable ctor - This creates a global and inserts it before the
69 /// specified other global.
71 LinkageTypes Linkage, Constant *Initializer,
72 const Twine &Name = "",
73 GlobalVariable *InsertBefore = nullptr,
75 std::optional<unsigned> AddressSpace = std::nullopt,
76 bool isExternallyInitialized = false);
77 GlobalVariable(const GlobalVariable &) = delete;
79
80private:
81 /// Set the number of operands on a GlobalVariable.
82 ///
83 /// GlobalVariable always allocates space for a single operands, but
84 /// doesn't always use it.
85 void setGlobalVariableNumOperands(unsigned NumOps) {
86 assert(NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands");
88 }
89
90public:
93
94 // Number of operands can be set to 0 after construction and initialization.
95 // Make sure that number of operands is reset to 1, as this is needed in
96 // User::operator delete
97 setGlobalVariableNumOperands(1);
98 }
99
100 // allocate space for exactly one operand
101 void *operator new(size_t s) { return User::operator new(s, AllocMarker); }
102
103 // delete space for exactly one operand as created in the corresponding new operator
104 void operator delete(void *ptr) { User::operator delete(ptr, AllocMarker); }
105
106 /// Provide fast operand accessors
108
109 /// Definitions have initializers, declarations don't.
110 ///
111 inline bool hasInitializer() const { return !isDeclaration(); }
112
113 /// hasDefinitiveInitializer - Whether the global variable has an initializer,
114 /// and any other instances of the global (this can happen due to weak
115 /// linkage) are guaranteed to have the same initializer.
116 ///
117 /// Note that if you want to transform a global, you must use
118 /// hasUniqueInitializer() instead, because of the *_odr linkage type.
119 ///
120 /// Example:
121 ///
122 /// @a = global SomeType* null - Initializer is both definitive and unique.
123 ///
124 /// @b = global weak SomeType* null - Initializer is neither definitive nor
125 /// unique.
126 ///
127 /// @c = global weak_odr SomeType* null - Initializer is definitive, but not
128 /// unique.
129 inline bool hasDefinitiveInitializer() const {
130 return hasInitializer() &&
131 // The initializer of a global variable may change to something arbitrary
132 // at link time.
133 !isInterposable() &&
134 // The initializer of a global variable with the externally_initialized
135 // marker may change at runtime before C++ initializers are evaluated.
137 }
138
139 /// hasUniqueInitializer - Whether the global variable has an initializer, and
140 /// any changes made to the initializer will turn up in the final executable.
141 inline bool hasUniqueInitializer() const {
142 return
143 // We need to be sure this is the definition that will actually be used
145 // It is not safe to modify initializers of global variables with the
146 // external_initializer marker since the value may be changed at runtime
147 // before C++ initializers are evaluated.
149 }
150
151 /// getInitializer - Return the initializer for this global variable. It is
152 /// illegal to call this method if the global is external, because we cannot
153 /// tell what the value is initialized to!
154 ///
155 inline const Constant *getInitializer() const {
156 assert(hasInitializer() && "GV doesn't have initializer!");
157 return static_cast<Constant*>(Op<0>().get());
158 }
160 assert(hasInitializer() && "GV doesn't have initializer!");
161 return static_cast<Constant*>(Op<0>().get());
162 }
163 /// setInitializer - Sets the initializer for this global variable, removing
164 /// any existing initializer if InitVal==NULL. The initializer must have the
165 /// type getValueType().
166 LLVM_ABI void setInitializer(Constant *InitVal);
167
168 /// replaceInitializer - Sets the initializer for this global variable, and
169 /// sets the value type of the global to the type of the initializer. The
170 /// initializer must not be null. This may affect the global's alignment if
171 /// it isn't explicitly set.
172 LLVM_ABI void replaceInitializer(Constant *InitVal);
173
174 /// Get the size of this global variable in bytes.
175 /// This is only a minimum size if this is a declaration or a replaceable
176 /// definition.
178
179 /// If the value is a global constant, its value is immutable throughout the
180 /// runtime execution of the program. Assigning a value into the constant
181 /// leads to undefined behavior.
182 ///
183 bool isConstant() const { return isConstantGlobal; }
184 void setConstant(bool Val) { isConstantGlobal = Val; }
185
187 return isExternallyInitializedConstant;
188 }
190 isExternallyInitializedConstant = Val;
191 }
192
193 /// copyAttributesFrom - copy all additional attributes (those not needed to
194 /// create a GlobalVariable) from the GlobalVariable Src to this one.
196
197 /// removeFromParent - This method unlinks 'this' from the containing module,
198 /// but does not delete it.
199 ///
201
202 /// eraseFromParent - This method unlinks 'this' from the containing module
203 /// and deletes it.
204 ///
206
207 /// Drop all references in preparation to destroy the GlobalVariable. This
208 /// drops not only the reference to the initializer but also to any metadata.
210
211 /// Attach a DIGlobalVariableExpression.
213
214 /// Fill the vector with all debug info attachements.
215 LLVM_ABI void
217
218 /// Add attribute to this global.
220 Attrs = Attrs.addAttribute(getContext(), Kind);
221 }
222
223 /// Add attribute to this global.
225 Attrs = Attrs.addAttribute(getContext(), Kind, Val);
226 }
227
228 /// Add attributes to this global.
229 void addAttributes(const AttrBuilder &AttrBuilder) {
230 Attrs = Attrs.addAttributes(getContext(), AttrBuilder);
231 }
232
233 /// Return true if the attribute exists.
235 return Attrs.hasAttribute(Kind);
236 }
237
238 /// Return true if the attribute exists.
239 bool hasAttribute(StringRef Kind) const {
240 return Attrs.hasAttribute(Kind);
241 }
242
243 /// Return true if any attributes exist.
244 bool hasAttributes() const {
245 return Attrs.hasAttributes();
246 }
247
248 /// Return the attribute object.
250 return Attrs.getAttribute(Kind);
251 }
252
253 /// Return the attribute object.
255 return Attrs.getAttribute(Kind);
256 }
257
258 /// Return the attribute set for this global
260 return Attrs;
261 }
262
263 /// Return attribute set as list with index.
264 /// FIXME: This may not be required once ValueEnumerators
265 /// in bitcode-writer can enumerate attribute-set.
266 AttributeList getAttributesAsList(unsigned index) const {
267 if (!hasAttributes())
268 return AttributeList();
269 std::pair<unsigned, AttributeSet> AS[1] = {{index, Attrs}};
270 return AttributeList::get(getContext(), AS);
271 }
272
273 /// Set attribute list for this global
275 Attrs = A;
276 }
277
278 /// Check if section name is present
279 bool hasImplicitSection() const {
280 return getAttributes().hasAttribute("bss-section") ||
281 getAttributes().hasAttribute("data-section") ||
282 getAttributes().hasAttribute("relro-section") ||
283 getAttributes().hasAttribute("rodata-section");
284 }
285
286 /// Get the custom code model raw value of this global.
287 ///
288 unsigned getCodeModelRaw() const {
289 unsigned Data = getGlobalValueSubClassData();
290 return (Data >> CodeModelShift) & CodeModelMask;
291 }
292
293 /// Get the custom code model of this global if it has one.
294 ///
295 /// If this global does not have a custom code model, the empty instance
296 /// will be returned.
297 std::optional<CodeModel::Model> getCodeModel() const {
298 unsigned CodeModelData = getCodeModelRaw();
299 if (CodeModelData > 0)
300 return static_cast<CodeModel::Model>(CodeModelData - 1);
301 return {};
302 }
303
304 /// Change the code model for this global.
305 ///
307
308 /// Remove the code model for this global.
309 ///
311
312 /// FIXME: Remove this function once transition to Align is over.
315 return Align ? Align->value() : 0;
316 }
317
318 /// Returns the alignment of the given variable.
320
321 /// Sets the alignment attribute of the GlobalVariable.
323
324 /// Sets the alignment attribute of the GlobalVariable.
325 /// This method will be deprecated as the alignment property should always be
326 /// defined.
328
329 // Methods for support type inquiry through isa, cast, and dyn_cast:
330 static bool classof(const Value *V) {
331 return V->getValueID() == Value::GlobalVariableVal;
332 }
333};
334
335template <>
337 public OptionalOperandTraits<GlobalVariable> {
338};
339
341
342} // end namespace llvm
343
344#endif // LLVM_IR_GLOBALVARIABLE_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS)
Macro for generating out-of-class operand accessor definitions.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:402
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:103
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:122
This is an important base class in LLVM.
Definition Constant.h:43
A pair of DIGlobalVariable and DIExpression.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
LLVM_ABI void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition Globals.cpp:146
GlobalObject(Type *Ty, ValueTy VTy, AllocInfo AllocInfo, LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace=0)
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:329
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
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:108
unsigned getGlobalValueSubClassData() const
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:534
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:526
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:555
LLVM_ABI void clearCodeModel()
Remove the code model for this global.
Definition Globals.cpp:590
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:568
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.
AttributeList getAttributesAsList(unsigned index) const
Return attribute set as list with index.
Attribute getAttribute(StringRef Kind) const
Return the attribute object.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:561
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:581
void addAttributes(const AttrBuilder &AttrBuilder)
Add attributes to this global.
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:530
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
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:576
LLVM_ABI GlobalVariable(Type *Ty, bool isConstant, LinkageTypes Linkage, Constant *Initializer=nullptr, const Twine &Name="", ThreadLocalMode=NotThreadLocal, unsigned AddressSpace=0, bool isExternallyInitialized=false)
GlobalVariable ctor - If a parent module is specified, the global is automatically inserted into the ...
Definition Globals.cpp:489
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...
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
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
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 Types.h:26
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
DWARFExpression::Operation Op
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Compile-time customization of User operands.
Definition User.h:42
OptionalOperandTraits - when the number of operands may change at runtime.
Indicates this User has operands co-allocated.
Definition User.h:60