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/Triple.h"
16 #include "llvm/IR/ConstantRange.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/GlobalAlias.h"
20 #include "llvm/IR/GlobalValue.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/ErrorHandling.h"
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 // GlobalValue should be a Constant, plus a type, a module, some flags, and an
32 // intrinsic ID. Add an assert to prevent people from accidentally growing
33 // GlobalValue while adding flags.
34 static_assert(sizeof(GlobalValue) ==
35 sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
36 "unexpected GlobalValue size growth");
38 // GlobalObject adds a comdat.
39 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
40 "unexpected GlobalObject size growth");
42 bool GlobalValue::isMaterializable() const {
43 if (const Function *F = dyn_cast<Function>(this))
44 return F->isMaterializable();
47 Error GlobalValue::materialize() {
48 return getParent()->materialize(this);
51 /// Override destroyConstantImpl to make sure it doesn't get called on
52 /// GlobalValue's because they shouldn't be treated like other constants.
53 void GlobalValue::destroyConstantImpl() {
54 llvm_unreachable("You can't GV->destroyConstantImpl()!");
57 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
58 llvm_unreachable("Unsupported class for handleOperandChange()!");
61 /// copyAttributesFrom - copy all additional attributes (those not needed to
62 /// create a GlobalValue) from the GlobalValue Src to this one.
63 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
64 setVisibility(Src->getVisibility());
65 setUnnamedAddr(Src->getUnnamedAddr());
66 setThreadLocalMode(Src->getThreadLocalMode());
67 setDLLStorageClass(Src->getDLLStorageClass());
68 setDSOLocal(Src->isDSOLocal());
69 setPartition(Src->getPartition());
70 if (Src->hasSanitizerMetadata())
71 setSanitizerMetadata(Src->getSanitizerMetadata());
73 removeSanitizerMetadata();
76 void GlobalValue::removeFromParent() {
77 switch (getValueID()) {
78 #define HANDLE_GLOBAL_VALUE(NAME) \
79 case Value::NAME##Val: \
80 return static_cast<NAME *>(this)->removeFromParent();
81 #include "llvm/IR/Value.def"
85 llvm_unreachable("not a global");
88 void GlobalValue::eraseFromParent() {
89 switch (getValueID()) {
90 #define HANDLE_GLOBAL_VALUE(NAME) \
91 case Value::NAME##Val: \
92 return static_cast<NAME *>(this)->eraseFromParent();
93 #include "llvm/IR/Value.def"
97 llvm_unreachable("not a global");
100 GlobalObject::~GlobalObject() { setComdat(nullptr); }
102 bool GlobalValue::isInterposable() const {
103 if (isInterposableLinkage(getLinkage()))
105 return getParent() && getParent()->getSemanticInterposition() &&
109 bool GlobalValue::canBenefitFromLocalAlias() const {
110 // See AsmPrinter::getSymbolPreferLocal(). For a deduplicate comdat kind,
111 // references to a discarded local symbol from outside the group are not
112 // allowed, so avoid the local alias.
113 auto isDeduplicateComdat = [](const Comdat *C) {
114 return C && C->getSelectionKind() != Comdat::NoDeduplicate;
116 return hasDefaultVisibility() &&
117 GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
118 !isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat());
121 unsigned GlobalValue::getAddressSpace() const {
122 PointerType *PtrTy = getType();
123 return PtrTy->getAddressSpace();
126 void GlobalObject::setAlignment(MaybeAlign Align) {
127 assert((!Align || *Align <= MaximumAlignment) &&
128 "Alignment is greater than MaximumAlignment!");
129 unsigned AlignmentData = encode(Align);
130 unsigned OldData = getGlobalValueSubClassData();
131 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
132 assert(MaybeAlign(getAlignment()) == Align &&
133 "Alignment representation error!");
136 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
137 GlobalValue::copyAttributesFrom(Src);
138 setAlignment(Src->getAlign());
139 setSection(Src->getSection());
142 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
143 GlobalValue::LinkageTypes Linkage,
144 StringRef FileName) {
146 // Value names may be prefixed with a binary '1' to indicate
147 // that the backend should not modify the symbols due to any platform
148 // naming convention. Do not include that '1' in the PGO profile name.
150 Name = Name.substr(1);
152 std::string NewName = std::string(Name);
153 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
154 // For local symbols, prepend the main file name to distinguish them.
155 // Do not include the full path in the file name since there's no guarantee
156 // that it will stay the same, e.g., if the files are checked out from
157 // version control in different locations.
158 if (FileName.empty())
159 NewName = NewName.insert(0, "<unknown>:");
161 NewName = NewName.insert(0, FileName.str() + ":");
166 std::string GlobalValue::getGlobalIdentifier() const {
167 return getGlobalIdentifier(getName(), getLinkage(),
168 getParent()->getSourceFileName());
171 StringRef GlobalValue::getSection() 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->getAliaseeObject())
175 return GO->getSection();
178 return cast<GlobalObject>(this)->getSection();
181 const Comdat *GlobalValue::getComdat() const {
182 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
183 // In general we cannot compute this at the IR level, but we try.
184 if (const GlobalObject *GO = GA->getAliaseeObject())
185 return const_cast<GlobalObject *>(GO)->getComdat();
188 // ifunc and its resolver are separate things so don't use resolver comdat.
189 if (isa<GlobalIFunc>(this))
191 return cast<GlobalObject>(this)->getComdat();
194 void GlobalObject::setComdat(Comdat *C) {
196 ObjComdat->removeUser(this);
202 StringRef GlobalValue::getPartition() const {
205 return getContext().pImpl->GlobalValuePartitions[this];
208 void GlobalValue::setPartition(StringRef S) {
209 // Do nothing if we're clearing the partition and it is already empty.
210 if (!hasPartition() && S.empty())
213 // Get or create a stable partition name string and put it in the table in the
216 S = getContext().pImpl->Saver.save(S);
217 getContext().pImpl->GlobalValuePartitions[this] = S;
219 // Update the HasPartition field. Setting the partition to the empty string
220 // means this global no longer has a partition.
221 HasPartition = !S.empty();
224 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
225 const SanitizerMetadata &GlobalValue::getSanitizerMetadata() const {
226 assert(hasSanitizerMetadata());
227 assert(getContext().pImpl->GlobalValueSanitizerMetadata.count(this));
228 return getContext().pImpl->GlobalValueSanitizerMetadata[this];
231 void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) {
232 getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
233 HasSanitizerMetadata = true;
236 void GlobalValue::removeSanitizerMetadata() {
237 DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
238 getContext().pImpl->GlobalValueSanitizerMetadata;
239 MetadataMap.erase(this);
240 HasSanitizerMetadata = false;
243 StringRef GlobalObject::getSectionImpl() const {
244 assert(hasSection());
245 return getContext().pImpl->GlobalObjectSections[this];
248 void GlobalObject::setSection(StringRef S) {
249 // Do nothing if we're clearing the section and it is already empty.
250 if (!hasSection() && S.empty())
253 // Get or create a stable section name string and put it in the table in the
256 S = getContext().pImpl->Saver.save(S);
257 getContext().pImpl->GlobalObjectSections[this] = S;
259 // Update the HasSectionHashEntryBit. Setting the section to the empty string
260 // means this global no longer has a section.
261 setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
264 bool GlobalValue::isDeclaration() const {
265 // Globals are definitions if they have an initializer.
266 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
267 return GV->getNumOperands() == 0;
269 // Functions are definitions if they have a body.
270 if (const Function *F = dyn_cast<Function>(this))
271 return F->empty() && !F->isMaterializable();
273 // Aliases and ifuncs are always definitions.
274 assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
278 bool GlobalObject::canIncreaseAlignment() const {
279 // Firstly, can only increase the alignment of a global if it
280 // is a strong definition.
281 if (!isStrongDefinitionForLinker())
284 // It also has to either not have a section defined, or, not have
285 // alignment specified. (If it is assigned a section, the global
286 // could be densely packed with other objects in the section, and
287 // increasing the alignment could cause padding issues.)
288 if (hasSection() && getAlign())
291 // On ELF platforms, we're further restricted in that we can't
292 // increase the alignment of any variable which might be emitted
293 // into a shared library, and which is exported. If the main
294 // executable accesses a variable found in a shared-lib, the main
295 // exe actually allocates memory for and exports the symbol ITSELF,
296 // overriding the symbol found in the library. That is, at link
297 // time, the observed alignment of the variable is copied into the
298 // executable binary. (A COPY relocation is also generated, to copy
299 // the initial data from the shadowed variable in the shared-lib
300 // into the location in the main binary, before running code.)
302 // And thus, even though you might think you are defining the
303 // global, and allocating the memory for the global in your object
304 // file, and thus should be able to set the alignment arbitrarily,
305 // that's not actually true. Doing so can cause an ABI breakage; an
306 // executable might have already been built with the previous
307 // alignment of the variable, and then assuming an increased
308 // alignment will be incorrect.
310 // Conservatively assume ELF if there's no parent pointer.
312 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
313 if (isELF && !isDSOLocal())
319 template <typename Operation>
320 static const GlobalObject *
321 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases,
322 const Operation &Op) {
323 if (auto *GO = dyn_cast<GlobalObject>(C)) {
327 if (auto *GA = dyn_cast<GlobalAlias>(C)) {
329 if (Aliases.insert(GA).second)
330 return findBaseObject(GA->getOperand(0), Aliases, Op);
332 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
333 switch (CE->getOpcode()) {
334 case Instruction::Add: {
335 auto *LHS = findBaseObject(CE->getOperand(0), Aliases, Op);
336 auto *RHS = findBaseObject(CE->getOperand(1), Aliases, Op);
339 return LHS ? LHS : RHS;
341 case Instruction::Sub: {
342 if (findBaseObject(CE->getOperand(1), Aliases, Op))
344 return findBaseObject(CE->getOperand(0), Aliases, Op);
346 case Instruction::IntToPtr:
347 case Instruction::PtrToInt:
348 case Instruction::BitCast:
349 case Instruction::GetElementPtr:
350 return findBaseObject(CE->getOperand(0), Aliases, Op);
358 const GlobalObject *GlobalValue::getAliaseeObject() const {
359 DenseSet<const GlobalAlias *> Aliases;
360 return findBaseObject(this, Aliases, [](const GlobalValue &) {});
363 bool GlobalValue::isAbsoluteSymbolRef() const {
364 auto *GO = dyn_cast<GlobalObject>(this);
368 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
371 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
372 auto *GO = dyn_cast<GlobalObject>(this);
376 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
380 return getConstantRangeFromMetadata(*MD);
383 bool GlobalValue::canBeOmittedFromSymbolTable() const {
384 if (!hasLinkOnceODRLinkage())
387 // We assume that anyone who sets global unnamed_addr on a non-constant
388 // knows what they're doing.
389 if (hasGlobalUnnamedAddr())
392 // If it is a non constant variable, it needs to be uniqued across shared
394 if (auto *Var = dyn_cast<GlobalVariable>(this))
395 if (!Var->isConstant())
398 return hasAtLeastLocalUnnamedAddr();
401 //===----------------------------------------------------------------------===//
402 // GlobalVariable Implementation
403 //===----------------------------------------------------------------------===//
405 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
406 Constant *InitVal, const Twine &Name,
407 ThreadLocalMode TLMode, unsigned AddressSpace,
408 bool isExternallyInitialized)
409 : GlobalObject(Ty, Value::GlobalVariableVal,
410 OperandTraits<GlobalVariable>::op_begin(this),
411 InitVal != nullptr, Link, Name, AddressSpace),
412 isConstantGlobal(constant),
413 isExternallyInitializedConstant(isExternallyInitialized) {
414 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
415 "invalid type for global variable");
416 setThreadLocalMode(TLMode);
418 assert(InitVal->getType() == Ty &&
419 "Initializer should be the same type as the GlobalVariable!");
424 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
425 LinkageTypes Link, Constant *InitVal,
426 const Twine &Name, GlobalVariable *Before,
427 ThreadLocalMode TLMode,
428 Optional<unsigned> AddressSpace,
429 bool isExternallyInitialized)
430 : GlobalObject(Ty, Value::GlobalVariableVal,
431 OperandTraits<GlobalVariable>::op_begin(this),
432 InitVal != nullptr, Link, Name,
435 : M.getDataLayout().getDefaultGlobalsAddressSpace()),
436 isConstantGlobal(constant),
437 isExternallyInitializedConstant(isExternallyInitialized) {
438 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
439 "invalid type for global variable");
440 setThreadLocalMode(TLMode);
442 assert(InitVal->getType() == Ty &&
443 "Initializer should be the same type as the GlobalVariable!");
448 Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
450 M.getGlobalList().push_back(this);
453 void GlobalVariable::removeFromParent() {
454 getParent()->getGlobalList().remove(getIterator());
457 void GlobalVariable::eraseFromParent() {
458 getParent()->getGlobalList().erase(getIterator());
461 void GlobalVariable::setInitializer(Constant *InitVal) {
463 if (hasInitializer()) {
464 // Note, the num operands is used to compute the offset of the operand, so
465 // the order here matters. Clearing the operand then clearing the num
466 // operands ensures we have the correct offset to the operand.
467 Op<0>().set(nullptr);
468 setGlobalVariableNumOperands(0);
471 assert(InitVal->getType() == getValueType() &&
472 "Initializer type must match GlobalVariable type");
473 // Note, the num operands is used to compute the offset of the operand, so
474 // the order here matters. We need to set num operands to 1 first so that
475 // we get the correct offset to the first operand when we set it.
476 if (!hasInitializer())
477 setGlobalVariableNumOperands(1);
478 Op<0>().set(InitVal);
482 /// Copy all additional attributes (those not needed to create a GlobalVariable)
483 /// from the GlobalVariable Src to this one.
484 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
485 GlobalObject::copyAttributesFrom(Src);
486 setExternallyInitialized(Src->isExternallyInitialized());
487 setAttributes(Src->getAttributes());
490 void GlobalVariable::dropAllReferences() {
491 User::dropAllReferences();
495 //===----------------------------------------------------------------------===//
496 // GlobalAlias Implementation
497 //===----------------------------------------------------------------------===//
499 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
500 const Twine &Name, Constant *Aliasee,
501 Module *ParentModule)
502 : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
506 ParentModule->getAliasList().push_back(this);
509 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
510 LinkageTypes Link, const Twine &Name,
511 Constant *Aliasee, Module *ParentModule) {
512 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
515 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
516 LinkageTypes Linkage, const Twine &Name,
518 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
521 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
522 LinkageTypes Linkage, const Twine &Name,
523 GlobalValue *Aliasee) {
524 return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
527 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
528 GlobalValue *Aliasee) {
529 return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
533 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
534 return create(Aliasee->getLinkage(), Name, Aliasee);
537 void GlobalAlias::removeFromParent() {
538 getParent()->getAliasList().remove(getIterator());
541 void GlobalAlias::eraseFromParent() {
542 getParent()->getAliasList().erase(getIterator());
545 void GlobalAlias::setAliasee(Constant *Aliasee) {
546 assert((!Aliasee || Aliasee->getType() == getType()) &&
547 "Alias and aliasee types should match!");
548 Op<0>().set(Aliasee);
551 const GlobalObject *GlobalAlias::getAliaseeObject() const {
552 DenseSet<const GlobalAlias *> Aliases;
553 return findBaseObject(getOperand(0), Aliases, [](const GlobalValue &) {});
556 //===----------------------------------------------------------------------===//
557 // GlobalIFunc Implementation
558 //===----------------------------------------------------------------------===//
560 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
561 const Twine &Name, Constant *Resolver,
562 Module *ParentModule)
563 : GlobalObject(Ty, Value::GlobalIFuncVal, &Op<0>(), 1, Link, Name,
565 setResolver(Resolver);
567 ParentModule->getIFuncList().push_back(this);
570 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
571 LinkageTypes Link, const Twine &Name,
572 Constant *Resolver, Module *ParentModule) {
573 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
576 void GlobalIFunc::removeFromParent() {
577 getParent()->getIFuncList().remove(getIterator());
580 void GlobalIFunc::eraseFromParent() {
581 getParent()->getIFuncList().erase(getIterator());
584 const Function *GlobalIFunc::getResolverFunction() const {
585 DenseSet<const GlobalAlias *> Aliases;
586 return dyn_cast<Function>(
587 findBaseObject(getResolver(), Aliases, [](const GlobalValue &) {}));
590 void GlobalIFunc::applyAlongResolverPath(
591 function_ref<void(const GlobalValue &)> Op) const {
592 DenseSet<const GlobalAlias *> Aliases;
593 findBaseObject(getResolver(), Aliases, Op);