1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the GlobalValue & GlobalVariable classes for the IR
13 //===----------------------------------------------------------------------===//
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/ConstantRange.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
30 //===----------------------------------------------------------------------===//
32 //===----------------------------------------------------------------------===//
34 // GlobalValue should be a Constant, plus a type, a module, some flags, and an
35 // intrinsic ID. Add an assert to prevent people from accidentally growing
36 // GlobalValue while adding flags.
37 static_assert(sizeof(GlobalValue
) ==
38 sizeof(Constant
) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
39 "unexpected GlobalValue size growth");
41 // GlobalObject adds a comdat.
42 static_assert(sizeof(GlobalObject
) == sizeof(GlobalValue
) + sizeof(void *),
43 "unexpected GlobalObject size growth");
45 bool GlobalValue::isMaterializable() const {
46 if (const Function
*F
= dyn_cast
<Function
>(this))
47 return F
->isMaterializable();
50 Error
GlobalValue::materialize() {
51 return getParent()->materialize(this);
54 /// Override destroyConstantImpl to make sure it doesn't get called on
55 /// GlobalValue's because they shouldn't be treated like other constants.
56 void GlobalValue::destroyConstantImpl() {
57 llvm_unreachable("You can't GV->destroyConstantImpl()!");
60 Value
*GlobalValue::handleOperandChangeImpl(Value
*From
, Value
*To
) {
61 llvm_unreachable("Unsupported class for handleOperandChange()!");
64 /// copyAttributesFrom - copy all additional attributes (those not needed to
65 /// create a GlobalValue) from the GlobalValue Src to this one.
66 void GlobalValue::copyAttributesFrom(const GlobalValue
*Src
) {
67 setVisibility(Src
->getVisibility());
68 setUnnamedAddr(Src
->getUnnamedAddr());
69 setDLLStorageClass(Src
->getDLLStorageClass());
70 setDSOLocal(Src
->isDSOLocal());
73 void GlobalValue::removeFromParent() {
74 switch (getValueID()) {
75 #define HANDLE_GLOBAL_VALUE(NAME) \
76 case Value::NAME##Val: \
77 return static_cast<NAME *>(this)->removeFromParent();
78 #include "llvm/IR/Value.def"
82 llvm_unreachable("not a global");
85 void GlobalValue::eraseFromParent() {
86 switch (getValueID()) {
87 #define HANDLE_GLOBAL_VALUE(NAME) \
88 case Value::NAME##Val: \
89 return static_cast<NAME *>(this)->eraseFromParent();
90 #include "llvm/IR/Value.def"
94 llvm_unreachable("not a global");
97 unsigned GlobalValue::getAlignment() const {
98 if (auto *GA
= dyn_cast
<GlobalAlias
>(this)) {
99 // In general we cannot compute this at the IR level, but we try.
100 if (const GlobalObject
*GO
= GA
->getBaseObject())
101 return GO
->getAlignment();
103 // FIXME: we should also be able to handle:
104 // Alias = Global + Offset
108 return cast
<GlobalObject
>(this)->getAlignment();
111 unsigned GlobalValue::getAddressSpace() const {
112 PointerType
*PtrTy
= getType();
113 return PtrTy
->getAddressSpace();
116 void GlobalObject::setAlignment(unsigned Align
) {
117 assert((Align
& (Align
-1)) == 0 && "Alignment is not a power of 2!");
118 assert(Align
<= MaximumAlignment
&&
119 "Alignment is greater than MaximumAlignment!");
120 unsigned AlignmentData
= Log2_32(Align
) + 1;
121 unsigned OldData
= getGlobalValueSubClassData();
122 setGlobalValueSubClassData((OldData
& ~AlignmentMask
) | AlignmentData
);
123 assert(getAlignment() == Align
&& "Alignment representation error!");
126 void GlobalObject::copyAttributesFrom(const GlobalObject
*Src
) {
127 GlobalValue::copyAttributesFrom(Src
);
128 setAlignment(Src
->getAlignment());
129 setSection(Src
->getSection());
132 std::string
GlobalValue::getGlobalIdentifier(StringRef Name
,
133 GlobalValue::LinkageTypes Linkage
,
134 StringRef FileName
) {
136 // Value names may be prefixed with a binary '1' to indicate
137 // that the backend should not modify the symbols due to any platform
138 // naming convention. Do not include that '1' in the PGO profile name.
140 Name
= Name
.substr(1);
142 std::string NewName
= Name
;
143 if (llvm::GlobalValue::isLocalLinkage(Linkage
)) {
144 // For local symbols, prepend the main file name to distinguish them.
145 // Do not include the full path in the file name since there's no guarantee
146 // that it will stay the same, e.g., if the files are checked out from
147 // version control in different locations.
148 if (FileName
.empty())
149 NewName
= NewName
.insert(0, "<unknown>:");
151 NewName
= NewName
.insert(0, FileName
.str() + ":");
156 std::string
GlobalValue::getGlobalIdentifier() const {
157 return getGlobalIdentifier(getName(), getLinkage(),
158 getParent()->getSourceFileName());
161 StringRef
GlobalValue::getSection() const {
162 if (auto *GA
= dyn_cast
<GlobalAlias
>(this)) {
163 // In general we cannot compute this at the IR level, but we try.
164 if (const GlobalObject
*GO
= GA
->getBaseObject())
165 return GO
->getSection();
168 return cast
<GlobalObject
>(this)->getSection();
171 const Comdat
*GlobalValue::getComdat() const {
172 if (auto *GA
= dyn_cast
<GlobalAlias
>(this)) {
173 // In general we cannot compute this at the IR level, but we try.
174 if (const GlobalObject
*GO
= GA
->getBaseObject())
175 return const_cast<GlobalObject
*>(GO
)->getComdat();
178 // ifunc and its resolver are separate things so don't use resolver comdat.
179 if (isa
<GlobalIFunc
>(this))
181 return cast
<GlobalObject
>(this)->getComdat();
184 StringRef
GlobalObject::getSectionImpl() const {
185 assert(hasSection());
186 return getContext().pImpl
->GlobalObjectSections
[this];
189 void GlobalObject::setSection(StringRef S
) {
190 // Do nothing if we're clearing the section and it is already empty.
191 if (!hasSection() && S
.empty())
194 // Get or create a stable section name string and put it in the table in the
197 S
= getContext().pImpl
->SectionStrings
.insert(S
).first
->first();
199 getContext().pImpl
->GlobalObjectSections
[this] = S
;
201 // Update the HasSectionHashEntryBit. Setting the section to the empty string
202 // means this global no longer has a section.
203 setGlobalObjectFlag(HasSectionHashEntryBit
, !S
.empty());
206 bool GlobalValue::isDeclaration() const {
207 // Globals are definitions if they have an initializer.
208 if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(this))
209 return GV
->getNumOperands() == 0;
211 // Functions are definitions if they have a body.
212 if (const Function
*F
= dyn_cast
<Function
>(this))
213 return F
->empty() && !F
->isMaterializable();
215 // Aliases and ifuncs are always definitions.
216 assert(isa
<GlobalIndirectSymbol
>(this));
220 bool GlobalValue::canIncreaseAlignment() const {
221 // Firstly, can only increase the alignment of a global if it
222 // is a strong definition.
223 if (!isStrongDefinitionForLinker())
226 // It also has to either not have a section defined, or, not have
227 // alignment specified. (If it is assigned a section, the global
228 // could be densely packed with other objects in the section, and
229 // increasing the alignment could cause padding issues.)
230 if (hasSection() && getAlignment() > 0)
233 // On ELF platforms, we're further restricted in that we can't
234 // increase the alignment of any variable which might be emitted
235 // into a shared library, and which is exported. If the main
236 // executable accesses a variable found in a shared-lib, the main
237 // exe actually allocates memory for and exports the symbol ITSELF,
238 // overriding the symbol found in the library. That is, at link
239 // time, the observed alignment of the variable is copied into the
240 // executable binary. (A COPY relocation is also generated, to copy
241 // the initial data from the shadowed variable in the shared-lib
242 // into the location in the main binary, before running code.)
244 // And thus, even though you might think you are defining the
245 // global, and allocating the memory for the global in your object
246 // file, and thus should be able to set the alignment arbitrarily,
247 // that's not actually true. Doing so can cause an ABI breakage; an
248 // executable might have already been built with the previous
249 // alignment of the variable, and then assuming an increased
250 // alignment will be incorrect.
252 // Conservatively assume ELF if there's no parent pointer.
254 (!Parent
|| Triple(Parent
->getTargetTriple()).isOSBinFormatELF());
255 if (isELF
&& hasDefaultVisibility() && !hasLocalLinkage())
261 const GlobalObject
*GlobalValue::getBaseObject() const {
262 if (auto *GO
= dyn_cast
<GlobalObject
>(this))
264 if (auto *GA
= dyn_cast
<GlobalIndirectSymbol
>(this))
265 return GA
->getBaseObject();
269 bool GlobalValue::isAbsoluteSymbolRef() const {
270 auto *GO
= dyn_cast
<GlobalObject
>(this);
274 return GO
->getMetadata(LLVMContext::MD_absolute_symbol
);
277 Optional
<ConstantRange
> GlobalValue::getAbsoluteSymbolRange() const {
278 auto *GO
= dyn_cast
<GlobalObject
>(this);
282 MDNode
*MD
= GO
->getMetadata(LLVMContext::MD_absolute_symbol
);
286 return getConstantRangeFromMetadata(*MD
);
289 bool GlobalValue::canBeOmittedFromSymbolTable() const {
290 if (!hasLinkOnceODRLinkage())
293 // We assume that anyone who sets global unnamed_addr on a non-constant
294 // knows what they're doing.
295 if (hasGlobalUnnamedAddr())
298 // If it is a non constant variable, it needs to be uniqued across shared
300 if (auto *Var
= dyn_cast
<GlobalVariable
>(this))
301 if (!Var
->isConstant())
304 return hasAtLeastLocalUnnamedAddr();
307 //===----------------------------------------------------------------------===//
308 // GlobalVariable Implementation
309 //===----------------------------------------------------------------------===//
311 GlobalVariable::GlobalVariable(Type
*Ty
, bool constant
, LinkageTypes Link
,
312 Constant
*InitVal
, const Twine
&Name
,
313 ThreadLocalMode TLMode
, unsigned AddressSpace
,
314 bool isExternallyInitialized
)
315 : GlobalObject(Ty
, Value::GlobalVariableVal
,
316 OperandTraits
<GlobalVariable
>::op_begin(this),
317 InitVal
!= nullptr, Link
, Name
, AddressSpace
),
318 isConstantGlobal(constant
),
319 isExternallyInitializedConstant(isExternallyInitialized
) {
320 assert(!Ty
->isFunctionTy() && PointerType::isValidElementType(Ty
) &&
321 "invalid type for global variable");
322 setThreadLocalMode(TLMode
);
324 assert(InitVal
->getType() == Ty
&&
325 "Initializer should be the same type as the GlobalVariable!");
330 GlobalVariable::GlobalVariable(Module
&M
, Type
*Ty
, bool constant
,
331 LinkageTypes Link
, Constant
*InitVal
,
332 const Twine
&Name
, GlobalVariable
*Before
,
333 ThreadLocalMode TLMode
, unsigned AddressSpace
,
334 bool isExternallyInitialized
)
335 : GlobalObject(Ty
, Value::GlobalVariableVal
,
336 OperandTraits
<GlobalVariable
>::op_begin(this),
337 InitVal
!= nullptr, Link
, Name
, AddressSpace
),
338 isConstantGlobal(constant
),
339 isExternallyInitializedConstant(isExternallyInitialized
) {
340 assert(!Ty
->isFunctionTy() && PointerType::isValidElementType(Ty
) &&
341 "invalid type for global variable");
342 setThreadLocalMode(TLMode
);
344 assert(InitVal
->getType() == Ty
&&
345 "Initializer should be the same type as the GlobalVariable!");
350 Before
->getParent()->getGlobalList().insert(Before
->getIterator(), this);
352 M
.getGlobalList().push_back(this);
355 void GlobalVariable::removeFromParent() {
356 getParent()->getGlobalList().remove(getIterator());
359 void GlobalVariable::eraseFromParent() {
360 getParent()->getGlobalList().erase(getIterator());
363 void GlobalVariable::setInitializer(Constant
*InitVal
) {
365 if (hasInitializer()) {
366 // Note, the num operands is used to compute the offset of the operand, so
367 // the order here matters. Clearing the operand then clearing the num
368 // operands ensures we have the correct offset to the operand.
369 Op
<0>().set(nullptr);
370 setGlobalVariableNumOperands(0);
373 assert(InitVal
->getType() == getValueType() &&
374 "Initializer type must match GlobalVariable type");
375 // Note, the num operands is used to compute the offset of the operand, so
376 // the order here matters. We need to set num operands to 1 first so that
377 // we get the correct offset to the first operand when we set it.
378 if (!hasInitializer())
379 setGlobalVariableNumOperands(1);
380 Op
<0>().set(InitVal
);
384 /// Copy all additional attributes (those not needed to create a GlobalVariable)
385 /// from the GlobalVariable Src to this one.
386 void GlobalVariable::copyAttributesFrom(const GlobalVariable
*Src
) {
387 GlobalObject::copyAttributesFrom(Src
);
388 setThreadLocalMode(Src
->getThreadLocalMode());
389 setExternallyInitialized(Src
->isExternallyInitialized());
390 setAttributes(Src
->getAttributes());
393 void GlobalVariable::dropAllReferences() {
394 User::dropAllReferences();
398 //===----------------------------------------------------------------------===//
399 // GlobalIndirectSymbol Implementation
400 //===----------------------------------------------------------------------===//
402 GlobalIndirectSymbol::GlobalIndirectSymbol(Type
*Ty
, ValueTy VTy
,
403 unsigned AddressSpace
, LinkageTypes Linkage
, const Twine
&Name
,
405 : GlobalValue(Ty
, VTy
, &Op
<0>(), 1, Linkage
, Name
, AddressSpace
) {
410 //===----------------------------------------------------------------------===//
411 // GlobalAlias Implementation
412 //===----------------------------------------------------------------------===//
414 GlobalAlias::GlobalAlias(Type
*Ty
, unsigned AddressSpace
, LinkageTypes Link
,
415 const Twine
&Name
, Constant
*Aliasee
,
416 Module
*ParentModule
)
417 : GlobalIndirectSymbol(Ty
, Value::GlobalAliasVal
, AddressSpace
, Link
, Name
,
420 ParentModule
->getAliasList().push_back(this);
423 GlobalAlias
*GlobalAlias::create(Type
*Ty
, unsigned AddressSpace
,
424 LinkageTypes Link
, const Twine
&Name
,
425 Constant
*Aliasee
, Module
*ParentModule
) {
426 return new GlobalAlias(Ty
, AddressSpace
, Link
, Name
, Aliasee
, ParentModule
);
429 GlobalAlias
*GlobalAlias::create(Type
*Ty
, unsigned AddressSpace
,
430 LinkageTypes Linkage
, const Twine
&Name
,
432 return create(Ty
, AddressSpace
, Linkage
, Name
, nullptr, Parent
);
435 GlobalAlias
*GlobalAlias::create(Type
*Ty
, unsigned AddressSpace
,
436 LinkageTypes Linkage
, const Twine
&Name
,
437 GlobalValue
*Aliasee
) {
438 return create(Ty
, AddressSpace
, Linkage
, Name
, Aliasee
, Aliasee
->getParent());
441 GlobalAlias
*GlobalAlias::create(LinkageTypes Link
, const Twine
&Name
,
442 GlobalValue
*Aliasee
) {
443 PointerType
*PTy
= Aliasee
->getType();
444 return create(PTy
->getElementType(), PTy
->getAddressSpace(), Link
, Name
,
448 GlobalAlias
*GlobalAlias::create(const Twine
&Name
, GlobalValue
*Aliasee
) {
449 return create(Aliasee
->getLinkage(), Name
, Aliasee
);
452 void GlobalAlias::removeFromParent() {
453 getParent()->getAliasList().remove(getIterator());
456 void GlobalAlias::eraseFromParent() {
457 getParent()->getAliasList().erase(getIterator());
460 void GlobalAlias::setAliasee(Constant
*Aliasee
) {
461 assert((!Aliasee
|| Aliasee
->getType() == getType()) &&
462 "Alias and aliasee types should match!");
463 setIndirectSymbol(Aliasee
);
466 //===----------------------------------------------------------------------===//
467 // GlobalIFunc Implementation
468 //===----------------------------------------------------------------------===//
470 GlobalIFunc::GlobalIFunc(Type
*Ty
, unsigned AddressSpace
, LinkageTypes Link
,
471 const Twine
&Name
, Constant
*Resolver
,
472 Module
*ParentModule
)
473 : GlobalIndirectSymbol(Ty
, Value::GlobalIFuncVal
, AddressSpace
, Link
, Name
,
476 ParentModule
->getIFuncList().push_back(this);
479 GlobalIFunc
*GlobalIFunc::create(Type
*Ty
, unsigned AddressSpace
,
480 LinkageTypes Link
, const Twine
&Name
,
481 Constant
*Resolver
, Module
*ParentModule
) {
482 return new GlobalIFunc(Ty
, AddressSpace
, Link
, Name
, Resolver
, ParentModule
);
485 void GlobalIFunc::removeFromParent() {
486 getParent()->getIFuncList().remove(getIterator());
489 void GlobalIFunc::eraseFromParent() {
490 getParent()->getIFuncList().erase(getIterator());