1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the GlobalValue & GlobalVariable classes for the IR
12 //===----------------------------------------------------------------------===//
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/IR/ConstantRange.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 // GlobalValue should be a Constant, plus a type, a module, some flags, and an
34 // intrinsic ID. Add an assert to prevent people from accidentally growing
35 // GlobalValue while adding flags.
36 static_assert(sizeof(GlobalValue
) ==
37 sizeof(Constant
) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
38 "unexpected GlobalValue size growth");
40 // GlobalObject adds a comdat.
41 static_assert(sizeof(GlobalObject
) == sizeof(GlobalValue
) + sizeof(void *),
42 "unexpected GlobalObject size growth");
44 bool GlobalValue::isMaterializable() const {
45 if (const Function
*F
= dyn_cast
<Function
>(this))
46 return F
->isMaterializable();
49 Error
GlobalValue::materialize() {
50 return getParent()->materialize(this);
53 /// Override destroyConstantImpl to make sure it doesn't get called on
54 /// GlobalValue's because they shouldn't be treated like other constants.
55 void GlobalValue::destroyConstantImpl() {
56 llvm_unreachable("You can't GV->destroyConstantImpl()!");
59 Value
*GlobalValue::handleOperandChangeImpl(Value
*From
, Value
*To
) {
60 llvm_unreachable("Unsupported class for handleOperandChange()!");
63 /// copyAttributesFrom - copy all additional attributes (those not needed to
64 /// create a GlobalValue) from the GlobalValue Src to this one.
65 void GlobalValue::copyAttributesFrom(const GlobalValue
*Src
) {
66 setVisibility(Src
->getVisibility());
67 setUnnamedAddr(Src
->getUnnamedAddr());
68 setThreadLocalMode(Src
->getThreadLocalMode());
69 setDLLStorageClass(Src
->getDLLStorageClass());
70 setDSOLocal(Src
->isDSOLocal());
71 setPartition(Src
->getPartition());
74 void GlobalValue::removeFromParent() {
75 switch (getValueID()) {
76 #define HANDLE_GLOBAL_VALUE(NAME) \
77 case Value::NAME##Val: \
78 return static_cast<NAME *>(this)->removeFromParent();
79 #include "llvm/IR/Value.def"
83 llvm_unreachable("not a global");
86 void GlobalValue::eraseFromParent() {
87 switch (getValueID()) {
88 #define HANDLE_GLOBAL_VALUE(NAME) \
89 case Value::NAME##Val: \
90 return static_cast<NAME *>(this)->eraseFromParent();
91 #include "llvm/IR/Value.def"
95 llvm_unreachable("not a global");
98 bool GlobalValue::isInterposable() const {
99 if (isInterposableLinkage(getLinkage()))
101 return getParent() && getParent()->getSemanticInterposition() &&
105 bool GlobalValue::canBenefitFromLocalAlias() const {
106 // See AsmPrinter::getSymbolPreferLocal().
107 return hasDefaultVisibility() &&
108 GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
109 !isa
<GlobalIFunc
>(this) && !hasComdat();
112 unsigned GlobalValue::getAddressSpace() const {
113 PointerType
*PtrTy
= getType();
114 return PtrTy
->getAddressSpace();
117 void GlobalObject::setAlignment(MaybeAlign Align
) {
118 assert((!Align
|| *Align
<= MaximumAlignment
) &&
119 "Alignment is greater than MaximumAlignment!");
120 unsigned AlignmentData
= encode(Align
);
121 unsigned OldData
= getGlobalValueSubClassData();
122 setGlobalValueSubClassData((OldData
& ~AlignmentMask
) | AlignmentData
);
123 assert(MaybeAlign(getAlignment()) == Align
&&
124 "Alignment representation error!");
127 void GlobalObject::copyAttributesFrom(const GlobalObject
*Src
) {
128 GlobalValue::copyAttributesFrom(Src
);
129 setAlignment(MaybeAlign(Src
->getAlignment()));
130 setSection(Src
->getSection());
133 std::string
GlobalValue::getGlobalIdentifier(StringRef Name
,
134 GlobalValue::LinkageTypes Linkage
,
135 StringRef FileName
) {
137 // Value names may be prefixed with a binary '1' to indicate
138 // that the backend should not modify the symbols due to any platform
139 // naming convention. Do not include that '1' in the PGO profile name.
141 Name
= Name
.substr(1);
143 std::string NewName
= std::string(Name
);
144 if (llvm::GlobalValue::isLocalLinkage(Linkage
)) {
145 // For local symbols, prepend the main file name to distinguish them.
146 // Do not include the full path in the file name since there's no guarantee
147 // that it will stay the same, e.g., if the files are checked out from
148 // version control in different locations.
149 if (FileName
.empty())
150 NewName
= NewName
.insert(0, "<unknown>:");
152 NewName
= NewName
.insert(0, FileName
.str() + ":");
157 std::string
GlobalValue::getGlobalIdentifier() const {
158 return getGlobalIdentifier(getName(), getLinkage(),
159 getParent()->getSourceFileName());
162 StringRef
GlobalValue::getSection() const {
163 if (auto *GA
= dyn_cast
<GlobalAlias
>(this)) {
164 // In general we cannot compute this at the IR level, but we try.
165 if (const GlobalObject
*GO
= GA
->getBaseObject())
166 return GO
->getSection();
169 return cast
<GlobalObject
>(this)->getSection();
172 const Comdat
*GlobalValue::getComdat() const {
173 if (auto *GA
= dyn_cast
<GlobalAlias
>(this)) {
174 // In general we cannot compute this at the IR level, but we try.
175 if (const GlobalObject
*GO
= GA
->getBaseObject())
176 return const_cast<GlobalObject
*>(GO
)->getComdat();
179 // ifunc and its resolver are separate things so don't use resolver comdat.
180 if (isa
<GlobalIFunc
>(this))
182 return cast
<GlobalObject
>(this)->getComdat();
185 StringRef
GlobalValue::getPartition() const {
188 return getContext().pImpl
->GlobalValuePartitions
[this];
191 void GlobalValue::setPartition(StringRef S
) {
192 // Do nothing if we're clearing the partition and it is already empty.
193 if (!hasPartition() && S
.empty())
196 // Get or create a stable partition name string and put it in the table in the
199 S
= getContext().pImpl
->Saver
.save(S
);
200 getContext().pImpl
->GlobalValuePartitions
[this] = S
;
202 // Update the HasPartition field. Setting the partition to the empty string
203 // means this global no longer has a partition.
204 HasPartition
= !S
.empty();
207 StringRef
GlobalObject::getSectionImpl() const {
208 assert(hasSection());
209 return getContext().pImpl
->GlobalObjectSections
[this];
212 void GlobalObject::setSection(StringRef S
) {
213 // Do nothing if we're clearing the section and it is already empty.
214 if (!hasSection() && S
.empty())
217 // Get or create a stable section name string and put it in the table in the
220 S
= getContext().pImpl
->Saver
.save(S
);
221 getContext().pImpl
->GlobalObjectSections
[this] = S
;
223 // Update the HasSectionHashEntryBit. Setting the section to the empty string
224 // means this global no longer has a section.
225 setGlobalObjectFlag(HasSectionHashEntryBit
, !S
.empty());
228 bool GlobalValue::isDeclaration() const {
229 // Globals are definitions if they have an initializer.
230 if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(this))
231 return GV
->getNumOperands() == 0;
233 // Functions are definitions if they have a body.
234 if (const Function
*F
= dyn_cast
<Function
>(this))
235 return F
->empty() && !F
->isMaterializable();
237 // Aliases and ifuncs are always definitions.
238 assert(isa
<GlobalIndirectSymbol
>(this));
242 bool GlobalObject::canIncreaseAlignment() const {
243 // Firstly, can only increase the alignment of a global if it
244 // is a strong definition.
245 if (!isStrongDefinitionForLinker())
248 // It also has to either not have a section defined, or, not have
249 // alignment specified. (If it is assigned a section, the global
250 // could be densely packed with other objects in the section, and
251 // increasing the alignment could cause padding issues.)
252 if (hasSection() && getAlignment() > 0)
255 // On ELF platforms, we're further restricted in that we can't
256 // increase the alignment of any variable which might be emitted
257 // into a shared library, and which is exported. If the main
258 // executable accesses a variable found in a shared-lib, the main
259 // exe actually allocates memory for and exports the symbol ITSELF,
260 // overriding the symbol found in the library. That is, at link
261 // time, the observed alignment of the variable is copied into the
262 // executable binary. (A COPY relocation is also generated, to copy
263 // the initial data from the shadowed variable in the shared-lib
264 // into the location in the main binary, before running code.)
266 // And thus, even though you might think you are defining the
267 // global, and allocating the memory for the global in your object
268 // file, and thus should be able to set the alignment arbitrarily,
269 // that's not actually true. Doing so can cause an ABI breakage; an
270 // executable might have already been built with the previous
271 // alignment of the variable, and then assuming an increased
272 // alignment will be incorrect.
274 // Conservatively assume ELF if there's no parent pointer.
276 (!Parent
|| Triple(Parent
->getTargetTriple()).isOSBinFormatELF());
277 if (isELF
&& !isDSOLocal())
283 const GlobalObject
*GlobalValue::getBaseObject() const {
284 if (auto *GO
= dyn_cast
<GlobalObject
>(this))
286 if (auto *GA
= dyn_cast
<GlobalIndirectSymbol
>(this))
287 return GA
->getBaseObject();
291 bool GlobalValue::isAbsoluteSymbolRef() const {
292 auto *GO
= dyn_cast
<GlobalObject
>(this);
296 return GO
->getMetadata(LLVMContext::MD_absolute_symbol
);
299 Optional
<ConstantRange
> GlobalValue::getAbsoluteSymbolRange() const {
300 auto *GO
= dyn_cast
<GlobalObject
>(this);
304 MDNode
*MD
= GO
->getMetadata(LLVMContext::MD_absolute_symbol
);
308 return getConstantRangeFromMetadata(*MD
);
311 bool GlobalValue::canBeOmittedFromSymbolTable() const {
312 if (!hasLinkOnceODRLinkage())
315 // We assume that anyone who sets global unnamed_addr on a non-constant
316 // knows what they're doing.
317 if (hasGlobalUnnamedAddr())
320 // If it is a non constant variable, it needs to be uniqued across shared
322 if (auto *Var
= dyn_cast
<GlobalVariable
>(this))
323 if (!Var
->isConstant())
326 return hasAtLeastLocalUnnamedAddr();
329 //===----------------------------------------------------------------------===//
330 // GlobalVariable Implementation
331 //===----------------------------------------------------------------------===//
333 GlobalVariable::GlobalVariable(Type
*Ty
, bool constant
, LinkageTypes Link
,
334 Constant
*InitVal
, const Twine
&Name
,
335 ThreadLocalMode TLMode
, unsigned AddressSpace
,
336 bool isExternallyInitialized
)
337 : GlobalObject(Ty
, Value::GlobalVariableVal
,
338 OperandTraits
<GlobalVariable
>::op_begin(this),
339 InitVal
!= nullptr, Link
, Name
, AddressSpace
),
340 isConstantGlobal(constant
),
341 isExternallyInitializedConstant(isExternallyInitialized
) {
342 assert(!Ty
->isFunctionTy() && PointerType::isValidElementType(Ty
) &&
343 "invalid type for global variable");
344 setThreadLocalMode(TLMode
);
346 assert(InitVal
->getType() == Ty
&&
347 "Initializer should be the same type as the GlobalVariable!");
352 GlobalVariable::GlobalVariable(Module
&M
, Type
*Ty
, bool constant
,
353 LinkageTypes Link
, Constant
*InitVal
,
354 const Twine
&Name
, GlobalVariable
*Before
,
355 ThreadLocalMode TLMode
,
356 Optional
<unsigned> AddressSpace
,
357 bool isExternallyInitialized
)
358 : GlobalObject(Ty
, Value::GlobalVariableVal
,
359 OperandTraits
<GlobalVariable
>::op_begin(this),
360 InitVal
!= nullptr, Link
, Name
,
363 : M
.getDataLayout().getDefaultGlobalsAddressSpace()),
364 isConstantGlobal(constant
),
365 isExternallyInitializedConstant(isExternallyInitialized
) {
366 assert(!Ty
->isFunctionTy() && PointerType::isValidElementType(Ty
) &&
367 "invalid type for global variable");
368 setThreadLocalMode(TLMode
);
370 assert(InitVal
->getType() == Ty
&&
371 "Initializer should be the same type as the GlobalVariable!");
376 Before
->getParent()->getGlobalList().insert(Before
->getIterator(), this);
378 M
.getGlobalList().push_back(this);
381 void GlobalVariable::removeFromParent() {
382 getParent()->getGlobalList().remove(getIterator());
385 void GlobalVariable::eraseFromParent() {
386 getParent()->getGlobalList().erase(getIterator());
389 void GlobalVariable::setInitializer(Constant
*InitVal
) {
391 if (hasInitializer()) {
392 // Note, the num operands is used to compute the offset of the operand, so
393 // the order here matters. Clearing the operand then clearing the num
394 // operands ensures we have the correct offset to the operand.
395 Op
<0>().set(nullptr);
396 setGlobalVariableNumOperands(0);
399 assert(InitVal
->getType() == getValueType() &&
400 "Initializer type must match GlobalVariable type");
401 // Note, the num operands is used to compute the offset of the operand, so
402 // the order here matters. We need to set num operands to 1 first so that
403 // we get the correct offset to the first operand when we set it.
404 if (!hasInitializer())
405 setGlobalVariableNumOperands(1);
406 Op
<0>().set(InitVal
);
410 /// Copy all additional attributes (those not needed to create a GlobalVariable)
411 /// from the GlobalVariable Src to this one.
412 void GlobalVariable::copyAttributesFrom(const GlobalVariable
*Src
) {
413 GlobalObject::copyAttributesFrom(Src
);
414 setExternallyInitialized(Src
->isExternallyInitialized());
415 setAttributes(Src
->getAttributes());
418 void GlobalVariable::dropAllReferences() {
419 User::dropAllReferences();
423 //===----------------------------------------------------------------------===//
424 // GlobalIndirectSymbol Implementation
425 //===----------------------------------------------------------------------===//
427 GlobalIndirectSymbol::GlobalIndirectSymbol(Type
*Ty
, ValueTy VTy
,
428 unsigned AddressSpace
, LinkageTypes Linkage
, const Twine
&Name
,
430 : GlobalValue(Ty
, VTy
, &Op
<0>(), 1, Linkage
, Name
, AddressSpace
) {
434 static const GlobalObject
*
435 findBaseObject(const Constant
*C
, DenseSet
<const GlobalAlias
*> &Aliases
) {
436 if (auto *GO
= dyn_cast
<GlobalObject
>(C
))
438 if (auto *GA
= dyn_cast
<GlobalAlias
>(C
))
439 if (Aliases
.insert(GA
).second
)
440 return findBaseObject(GA
->getOperand(0), Aliases
);
441 if (auto *CE
= dyn_cast
<ConstantExpr
>(C
)) {
442 switch (CE
->getOpcode()) {
443 case Instruction::Add
: {
444 auto *LHS
= findBaseObject(CE
->getOperand(0), Aliases
);
445 auto *RHS
= findBaseObject(CE
->getOperand(1), Aliases
);
448 return LHS
? LHS
: RHS
;
450 case Instruction::Sub
: {
451 if (findBaseObject(CE
->getOperand(1), Aliases
))
453 return findBaseObject(CE
->getOperand(0), Aliases
);
455 case Instruction::IntToPtr
:
456 case Instruction::PtrToInt
:
457 case Instruction::BitCast
:
458 case Instruction::GetElementPtr
:
459 return findBaseObject(CE
->getOperand(0), Aliases
);
467 const GlobalObject
*GlobalIndirectSymbol::getBaseObject() const {
468 DenseSet
<const GlobalAlias
*> Aliases
;
469 return findBaseObject(getOperand(0), Aliases
);
472 //===----------------------------------------------------------------------===//
473 // GlobalAlias Implementation
474 //===----------------------------------------------------------------------===//
476 GlobalAlias::GlobalAlias(Type
*Ty
, unsigned AddressSpace
, LinkageTypes Link
,
477 const Twine
&Name
, Constant
*Aliasee
,
478 Module
*ParentModule
)
479 : GlobalIndirectSymbol(Ty
, Value::GlobalAliasVal
, AddressSpace
, Link
, Name
,
482 ParentModule
->getAliasList().push_back(this);
485 GlobalAlias
*GlobalAlias::create(Type
*Ty
, unsigned AddressSpace
,
486 LinkageTypes Link
, const Twine
&Name
,
487 Constant
*Aliasee
, Module
*ParentModule
) {
488 return new GlobalAlias(Ty
, AddressSpace
, Link
, Name
, Aliasee
, ParentModule
);
491 GlobalAlias
*GlobalAlias::create(Type
*Ty
, unsigned AddressSpace
,
492 LinkageTypes Linkage
, const Twine
&Name
,
494 return create(Ty
, AddressSpace
, Linkage
, Name
, nullptr, Parent
);
497 GlobalAlias
*GlobalAlias::create(Type
*Ty
, unsigned AddressSpace
,
498 LinkageTypes Linkage
, const Twine
&Name
,
499 GlobalValue
*Aliasee
) {
500 return create(Ty
, AddressSpace
, Linkage
, Name
, Aliasee
, Aliasee
->getParent());
503 GlobalAlias
*GlobalAlias::create(LinkageTypes Link
, const Twine
&Name
,
504 GlobalValue
*Aliasee
) {
505 return create(Aliasee
->getValueType(), Aliasee
->getAddressSpace(), Link
, Name
,
509 GlobalAlias
*GlobalAlias::create(const Twine
&Name
, GlobalValue
*Aliasee
) {
510 return create(Aliasee
->getLinkage(), Name
, Aliasee
);
513 void GlobalAlias::removeFromParent() {
514 getParent()->getAliasList().remove(getIterator());
517 void GlobalAlias::eraseFromParent() {
518 getParent()->getAliasList().erase(getIterator());
521 void GlobalAlias::setAliasee(Constant
*Aliasee
) {
522 assert((!Aliasee
|| Aliasee
->getType() == getType()) &&
523 "Alias and aliasee types should match!");
524 setIndirectSymbol(Aliasee
);
527 //===----------------------------------------------------------------------===//
528 // GlobalIFunc Implementation
529 //===----------------------------------------------------------------------===//
531 GlobalIFunc::GlobalIFunc(Type
*Ty
, unsigned AddressSpace
, LinkageTypes Link
,
532 const Twine
&Name
, Constant
*Resolver
,
533 Module
*ParentModule
)
534 : GlobalIndirectSymbol(Ty
, Value::GlobalIFuncVal
, AddressSpace
, Link
, Name
,
537 ParentModule
->getIFuncList().push_back(this);
540 GlobalIFunc
*GlobalIFunc::create(Type
*Ty
, unsigned AddressSpace
,
541 LinkageTypes Link
, const Twine
&Name
,
542 Constant
*Resolver
, Module
*ParentModule
) {
543 return new GlobalIFunc(Ty
, AddressSpace
, Link
, Name
, Resolver
, ParentModule
);
546 void GlobalIFunc::removeFromParent() {
547 getParent()->getIFuncList().remove(getIterator());
550 void GlobalIFunc::eraseFromParent() {
551 getParent()->getIFuncList().erase(getIterator());