1//===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
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 implements the GlobalValue & GlobalVariable classes for the IR
10// library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLVMContextImpl.h"
15#include "llvm/IR/ConstantRange.h"
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/DataLayout.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/MDBuilder.h"
23#include "llvm/IR/Module.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MD5.h"
27#include "llvm/TargetParser/Triple.h"
28using namespace llvm;
29
30//===----------------------------------------------------------------------===//
31// GlobalValue Class
32//===----------------------------------------------------------------------===//
33
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.
37static_assert(sizeof(GlobalValue) ==
38 sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
39 "unexpected GlobalValue size growth");
40
41// GlobalObject adds a comdat and metadata index.
42static_assert(sizeof(GlobalObject) ==
43 sizeof(GlobalValue) + sizeof(void *) +
44 alignTo(Value: sizeof(unsigned), Align: alignof(void *)),
45 "unexpected GlobalObject size growth");
46
47bool GlobalValue::isMaterializable() const {
48 if (const Function *F = dyn_cast<Function>(Val: this))
49 return F->isMaterializable();
50 return false;
51}
52Error GlobalValue::materialize() { return getParent()->materialize(GV: this); }
53
54/// Override destroyConstantImpl to make sure it doesn't get called on
55/// GlobalValue's because they shouldn't be treated like other constants.
56void GlobalValue::destroyConstantImpl() {
57 llvm_unreachable("You can't GV->destroyConstantImpl()!");
58}
59
60Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
61 llvm_unreachable("Unsupported class for handleOperandChange()!");
62}
63
64/// copyAttributesFrom - copy all additional attributes (those not needed to
65/// create a GlobalValue) from the GlobalValue Src to this one.
66void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
67 setVisibility(Src->getVisibility());
68 setUnnamedAddr(Src->getUnnamedAddr());
69 setThreadLocalMode(Src->getThreadLocalMode());
70 setDLLStorageClass(Src->getDLLStorageClass());
71 setDSOLocal(Src->isDSOLocal());
72 setPartition(Src->getPartition());
73 if (Src->hasSanitizerMetadata())
74 setSanitizerMetadata(Src->getSanitizerMetadata());
75 else
76 removeSanitizerMetadata();
77}
78
79GlobalValue::GUID
80GlobalValue::getGUIDAssumingExternalLinkage(StringRef GlobalIdentifier) {
81 return MD5Hash(Str: GlobalIdentifier);
82}
83
84void GlobalValue::assignGUID() {
85 if (getGUIDMetadata() != nullptr)
86 return;
87
88 const GUID G =
89 GlobalValue::getGUIDAssumingExternalLinkage(GlobalIdentifier: getGlobalIdentifier());
90 setMetadata(
91 KindID: LLVMContext::MD_guid,
92 Node: MDNode::get(Context&: getContext(), MDs: {ConstantAsMetadata::get(C: ConstantInt::get(
93 Ty: Type::getInt64Ty(C&: getContext()), V: G))}));
94}
95
96void GlobalValue::reassignGUID() {
97 if (!getGUIDMetadata())
98 return;
99 eraseMetadata(KindID: LLVMContext::MD_guid);
100 assignGUID();
101}
102
103GlobalValue::GUID GlobalValue::getGUID() const {
104 auto MaybeGUID = getGUIDIfAssigned();
105 assert(MaybeGUID.has_value() &&
106 "GUID was not assigned before calling GetGUID()");
107 return *MaybeGUID;
108}
109
110GlobalValue::GUID GlobalValue::getGUIDOrFallback() const {
111 if (auto MaybeGUID = getGUIDIfAssigned(); MaybeGUID)
112 return *MaybeGUID;
113 return getGUIDAssumingExternalLinkage(GlobalIdentifier: getGlobalIdentifier());
114}
115
116std::optional<GlobalValue::GUID> GlobalValue::getGUIDIfAssigned() const {
117 // First check the metadata.
118 auto *MD = getGUIDMetadata();
119 if (MD != nullptr)
120 return cast<ConstantInt>(Val: cast<ConstantAsMetadata>(Val: MD->getOperand(I: 0))
121 ->getValue()
122 ->stripPointerCasts())
123 ->getZExtValue();
124
125 // Handle a few special cases where we just want to compute it based on the
126 // current properties.
127 // TODO: Maybe we should use a more robust check for intrinsics than just
128 // matching on the name?
129 if (isDeclaration() || isa<GlobalAlias>(Val: this) ||
130 getName().starts_with(Prefix: "llvm.")) {
131 return GlobalValue::getGUIDAssumingExternalLinkage(GlobalIdentifier: getGlobalIdentifier());
132 }
133
134 // Otherwise we try to look it up in the module, for cases where we've read
135 // the GUID table but not the metadata. This happens when lazy-loading a
136 // module.
137 return getParent()->getGUID(V: this);
138}
139
140MDNode *GlobalValue::getGUIDMetadata() const {
141 if (auto *GO = dyn_cast<GlobalObject>(Val: this))
142 return GO->getMetadata(KindID: LLVMContext::MD_guid);
143 return nullptr;
144}
145
146void GlobalValue::removeFromParent() {
147 switch (getValueID()) {
148#define HANDLE_GLOBAL_VALUE(NAME) \
149 case Value::NAME##Val: \
150 return static_cast<NAME *>(this)->removeFromParent();
151#include "llvm/IR/Value.def"
152 default:
153 break;
154 }
155 llvm_unreachable("not a global");
156}
157
158void GlobalValue::eraseFromParent() {
159 switch (getValueID()) {
160#define HANDLE_GLOBAL_VALUE(NAME) \
161 case Value::NAME##Val: \
162 return static_cast<NAME *>(this)->eraseFromParent();
163#include "llvm/IR/Value.def"
164 default:
165 break;
166 }
167 llvm_unreachable("not a global");
168}
169
170GlobalObject::~GlobalObject() {
171 // Remove associated metadata from context.
172 if (hasMetadata())
173 clearMetadata();
174
175 setComdat(nullptr);
176}
177
178bool GlobalValue::isInterposable(bool CheckNoIPA) const {
179 if (CheckNoIPA && isNoipaFnDef())
180 return true;
181 if (isInterposableLinkage(Linkage: getLinkage()))
182 return true;
183 return !isDSOLocal() && getParent() &&
184 getParent()->getSemanticInterposition();
185}
186
187bool GlobalValue::canBenefitFromLocalAlias() const {
188 if (isTagged()) {
189 // Cannot create local aliases to MTE tagged globals. The address of a
190 // tagged global includes a tag that is assigned by the loader in the
191 // GOT.
192 return false;
193 }
194 // See AsmPrinter::getSymbolPreferLocal(). For a deduplicate comdat kind,
195 // references to a discarded local symbol from outside the group are not
196 // allowed, so avoid the local alias.
197 auto isDeduplicateComdat = [](const Comdat *C) {
198 return C && C->getSelectionKind() != Comdat::NoDeduplicate;
199 };
200 return hasDefaultVisibility() &&
201 GlobalObject::isExternalLinkage(Linkage: getLinkage()) && !isDeclaration() &&
202 !isa<GlobalIFunc>(Val: this) && !isDeduplicateComdat(getComdat());
203}
204
205const DataLayout &GlobalValue::getDataLayout() const {
206 return getParent()->getDataLayout();
207}
208
209void GlobalObject::setAlignment(MaybeAlign Align) {
210 assert((!Align || *Align <= MaximumAlignment) &&
211 "Alignment is greater than MaximumAlignment!");
212 unsigned AlignmentData = encode(A: Align);
213 unsigned OldData = getGlobalValueSubClassData();
214 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
215 assert(getAlign() == Align && "Alignment representation error!");
216}
217
218void GlobalObject::setAlignment(Align Align) {
219 assert(Align <= MaximumAlignment &&
220 "Alignment is greater than MaximumAlignment!");
221 unsigned AlignmentData = encode(A: Align);
222 unsigned OldData = getGlobalValueSubClassData();
223 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
224 assert(getAlign() && *getAlign() == Align &&
225 "Alignment representation error!");
226}
227
228void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
229 GlobalValue::copyAttributesFrom(Src);
230 setAlignment(Src->getAlign());
231 setSection(Src->getSection());
232}
233
234std::string GlobalValue::getGlobalIdentifier(StringRef Name,
235 GlobalValue::LinkageTypes Linkage,
236 StringRef FileName) {
237 // Value names may be prefixed with a binary '1' to indicate
238 // that the backend should not modify the symbols due to any platform
239 // naming convention. Do not include that '1' in the PGO profile name.
240 Name.consume_front(Prefix: "\1");
241
242 std::string GlobalName;
243 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
244 // For local symbols, prepend the main file name to distinguish them.
245 // Do not include the full path in the file name since there's no guarantee
246 // that it will stay the same, e.g., if the files are checked out from
247 // version control in different locations.
248 if (FileName.empty())
249 GlobalName += "<unknown>";
250 else
251 GlobalName += FileName;
252
253 GlobalName += GlobalIdentifierDelimiter;
254 }
255 GlobalName += Name;
256 return GlobalName;
257}
258
259std::string GlobalValue::getGlobalIdentifier() const {
260 return getGlobalIdentifier(Name: getName(), Linkage: getLinkage(),
261 FileName: getParent()->getSourceFileName());
262}
263
264StringRef GlobalValue::getSection() const {
265 if (auto *GA = dyn_cast<GlobalAlias>(Val: this)) {
266 // In general we cannot compute this at the IR level, but we try.
267 if (const GlobalObject *GO = GA->getAliaseeObject())
268 return GO->getSection();
269 return "";
270 }
271 return cast<GlobalObject>(Val: this)->getSection();
272}
273
274const Comdat *GlobalValue::getComdat() const {
275 if (auto *GA = dyn_cast<GlobalAlias>(Val: this)) {
276 // In general we cannot compute this at the IR level, but we try.
277 if (const GlobalObject *GO = GA->getAliaseeObject())
278 return const_cast<GlobalObject *>(GO)->getComdat();
279 return nullptr;
280 }
281 // ifunc and its resolver are separate things so don't use resolver comdat.
282 if (isa<GlobalIFunc>(Val: this))
283 return nullptr;
284 return cast<GlobalObject>(Val: this)->getComdat();
285}
286
287bool GlobalValue::isComdatLeader() const {
288 if (hasComdat())
289 return getParent()->getComdatSymbolTable().contains(Key: getName());
290 return false;
291}
292
293void GlobalObject::setComdat(Comdat *C) {
294 if (ObjComdat)
295 ObjComdat->removeUser(GO: this);
296 ObjComdat = C;
297 if (C)
298 C->addUser(GO: this);
299}
300
301StringRef GlobalValue::getPartition() const {
302 if (!hasPartition())
303 return "";
304 return getContext().pImpl->GlobalValuePartitions[this];
305}
306
307void GlobalValue::setPartition(StringRef S) {
308 // Do nothing if we're clearing the partition and it is already empty.
309 if (!hasPartition() && S.empty())
310 return;
311
312 // Get or create a stable partition name string and put it in the table in the
313 // context.
314 if (!S.empty())
315 S = getContext().pImpl->Saver.save(S);
316 getContext().pImpl->GlobalValuePartitions[this] = S;
317
318 // Update the HasPartition field. Setting the partition to the empty string
319 // means this global no longer has a partition.
320 HasPartition = !S.empty();
321}
322
323using SanitizerMetadata = GlobalValue::SanitizerMetadata;
324const SanitizerMetadata &GlobalValue::getSanitizerMetadata() const {
325 assert(hasSanitizerMetadata());
326 assert(getContext().pImpl->GlobalValueSanitizerMetadata.count(this));
327 return getContext().pImpl->GlobalValueSanitizerMetadata[this];
328}
329
330void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) {
331 getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
332 HasSanitizerMetadata = true;
333}
334
335void GlobalValue::removeSanitizerMetadata() {
336 DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
337 getContext().pImpl->GlobalValueSanitizerMetadata;
338 MetadataMap.erase(Val: this);
339 HasSanitizerMetadata = false;
340}
341
342void GlobalValue::setNoSanitizeMetadata() {
343 SanitizerMetadata Meta;
344 Meta.NoAddress = true;
345 Meta.NoHWAddress = true;
346 setSanitizerMetadata(Meta);
347}
348
349StringRef GlobalObject::getSectionImpl() const {
350 assert(hasSection());
351 return getContext().pImpl->GlobalObjectSections[this];
352}
353
354void GlobalObject::setSection(StringRef S) {
355 // Do nothing if we're clearing the section and it is already empty.
356 if (!hasSection() && S.empty())
357 return;
358
359 // Get or create a stable section name string and put it in the table in the
360 // context.
361 if (!S.empty())
362 S = getContext().pImpl->Saver.save(S);
363 getContext().pImpl->GlobalObjectSections[this] = S;
364
365 // Update the HasSectionHashEntryBit. Setting the section to the empty string
366 // means this global no longer has a section.
367 setGlobalObjectFlag(Bit: HasSectionHashEntryBit, Val: !S.empty());
368}
369
370bool GlobalObject::setSectionPrefix(StringRef Prefix) {
371 StringRef ExistingPrefix;
372 if (std::optional<StringRef> MaybePrefix = getSectionPrefix())
373 ExistingPrefix = *MaybePrefix;
374
375 if (ExistingPrefix == Prefix)
376 return false;
377
378 if (Prefix.empty()) {
379 setMetadata(KindID: LLVMContext::MD_section_prefix, Node: nullptr);
380 return true;
381 }
382 MDBuilder MDB(getContext());
383 setMetadata(KindID: LLVMContext::MD_section_prefix,
384 Node: MDB.createGlobalObjectSectionPrefix(Prefix));
385 return true;
386}
387
388std::optional<StringRef> GlobalObject::getSectionPrefix() const {
389 if (MDNode *MD = getMetadata(KindID: LLVMContext::MD_section_prefix)) {
390 [[maybe_unused]] StringRef MDName =
391 cast<MDString>(Val: MD->getOperand(I: 0))->getString();
392 assert((MDName == "section_prefix" ||
393 (isa<Function>(this) && MDName == "function_section_prefix")) &&
394 "Metadata not match");
395 return cast<MDString>(Val: MD->getOperand(I: 1))->getString();
396 }
397 return std::nullopt;
398}
399
400bool GlobalValue::isNobuiltinFnDef() const {
401 const Function *F = dyn_cast<Function>(Val: this);
402 if (!F || F->empty())
403 return false;
404 return F->hasFnAttribute(Kind: Attribute::NoBuiltin);
405}
406
407bool GlobalValue::isNoipaFnDef() const {
408 const Function *F = dyn_cast<Function>(Val: this);
409 if (!F || F->isDeclaration())
410 return false;
411 return F->hasFnAttribute(Kind: Attribute::NoIPA);
412}
413
414bool GlobalValue::isDeclaration() const {
415 // Globals are definitions if they have an initializer.
416 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: this))
417 return GV->getNumOperands() == 0;
418
419 // Functions are definitions if they have a body.
420 if (const Function *F = dyn_cast<Function>(Val: this))
421 return F->empty() && !F->isMaterializable();
422
423 // Aliases and ifuncs are always definitions.
424 assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
425 return false;
426}
427
428bool GlobalObject::canIncreaseAlignment() const {
429 // Firstly, can only increase the alignment of a global if it
430 // is a strong definition.
431 if (!isStrongDefinitionForLinker())
432 return false;
433
434 // It also has to either not have a section defined, or, not have
435 // alignment specified. (If it is assigned a section, the global
436 // could be densely packed with other objects in the section, and
437 // increasing the alignment could cause padding issues.)
438 if (hasSection() && getAlign())
439 return false;
440
441 // On ELF platforms, we're further restricted in that we can't
442 // increase the alignment of any variable which might be emitted
443 // into a shared library, and which is exported. If the main
444 // executable accesses a variable found in a shared-lib, the main
445 // exe actually allocates memory for and exports the symbol ITSELF,
446 // overriding the symbol found in the library. That is, at link
447 // time, the observed alignment of the variable is copied into the
448 // executable binary. (A COPY relocation is also generated, to copy
449 // the initial data from the shadowed variable in the shared-lib
450 // into the location in the main binary, before running code.)
451 //
452 // And thus, even though you might think you are defining the
453 // global, and allocating the memory for the global in your object
454 // file, and thus should be able to set the alignment arbitrarily,
455 // that's not actually true. Doing so can cause an ABI breakage; an
456 // executable might have already been built with the previous
457 // alignment of the variable, and then assuming an increased
458 // alignment will be incorrect.
459
460 // Conservatively assume ELF if there's no parent pointer.
461 bool isELF = (!Parent || Parent->getTargetTriple().isOSBinFormatELF());
462 if (isELF && !isDSOLocal())
463 return false;
464
465 // GV with toc-data attribute is defined in a TOC entry. To mitigate TOC
466 // overflow, the alignment of such symbol should not be increased. Otherwise,
467 // padding is needed thus more TOC entries are wasted.
468 bool isXCOFF = (!Parent || Parent->getTargetTriple().isOSBinFormatXCOFF());
469 if (isXCOFF)
470 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: this))
471 if (GV->hasAttribute(Kind: "toc-data"))
472 return false;
473
474 return true;
475}
476
477bool GlobalObject::hasMetadataOtherThanDebugLocAndGuid() const {
478 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
479 getAllMetadata(MDs);
480 for (const auto &V : MDs)
481 if (V.first != LLVMContext::MD_dbg && V.first != LLVMContext::MD_guid)
482 return true;
483 return false;
484}
485
486template <typename Operation>
487static const GlobalObject *
488findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases,
489 const Operation &Op) {
490 if (auto *GO = dyn_cast<GlobalObject>(Val: C)) {
491 Op(*GO);
492 return GO;
493 }
494 if (auto *GA = dyn_cast<GlobalAlias>(Val: C)) {
495 Op(*GA);
496 if (Aliases.insert(V: GA).second)
497 return findBaseObject(GA->getOperand(i_nocapture: 0), Aliases, Op);
498 }
499 if (auto *CE = dyn_cast<ConstantExpr>(Val: C)) {
500 switch (CE->getOpcode()) {
501 case Instruction::Add: {
502 auto *LHS = findBaseObject(CE->getOperand(i_nocapture: 0), Aliases, Op);
503 auto *RHS = findBaseObject(CE->getOperand(i_nocapture: 1), Aliases, Op);
504 if (LHS && RHS)
505 return nullptr;
506 return LHS ? LHS : RHS;
507 }
508 case Instruction::Sub: {
509 if (findBaseObject(CE->getOperand(i_nocapture: 1), Aliases, Op))
510 return nullptr;
511 return findBaseObject(CE->getOperand(i_nocapture: 0), Aliases, Op);
512 }
513 case Instruction::IntToPtr:
514 case Instruction::PtrToAddr:
515 case Instruction::PtrToInt:
516 case Instruction::BitCast:
517 case Instruction::AddrSpaceCast:
518 case Instruction::GetElementPtr:
519 return findBaseObject(CE->getOperand(i_nocapture: 0), Aliases, Op);
520 default:
521 break;
522 }
523 }
524 return nullptr;
525}
526
527const GlobalObject *GlobalValue::getAliaseeObject() const {
528 DenseSet<const GlobalAlias *> Aliases;
529 return findBaseObject(C: this, Aliases, Op: [](const GlobalValue &) {});
530}
531
532bool GlobalValue::isAbsoluteSymbolRef() const {
533 auto *GO = dyn_cast<GlobalObject>(Val: this);
534 if (!GO)
535 return false;
536
537 return GO->getMetadata(KindID: LLVMContext::MD_absolute_symbol);
538}
539
540std::optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
541 auto *GO = dyn_cast<GlobalObject>(Val: this);
542 if (!GO)
543 return std::nullopt;
544
545 MDNode *MD = GO->getMetadata(KindID: LLVMContext::MD_absolute_symbol);
546 if (!MD)
547 return std::nullopt;
548
549 return getConstantRangeFromMetadata(RangeMD: *MD);
550}
551
552bool GlobalValue::canBeOmittedFromSymbolTable() const {
553 if (!hasLinkOnceODRLinkage())
554 return false;
555
556 // We assume that anyone who sets global unnamed_addr on a non-constant
557 // knows what they're doing.
558 if (hasGlobalUnnamedAddr())
559 return true;
560
561 // If it is a non constant variable, it needs to be uniqued across shared
562 // objects.
563 if (auto *Var = dyn_cast<GlobalVariable>(Val: this))
564 if (!Var->isConstant())
565 return false;
566
567 return hasAtLeastLocalUnnamedAddr();
568}
569
570//===----------------------------------------------------------------------===//
571// GlobalVariable Implementation
572//===----------------------------------------------------------------------===//
573
574GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
575 Constant *InitVal, const Twine &Name,
576 ThreadLocalMode TLMode, unsigned AddressSpace,
577 bool isExternallyInitialized)
578 : GlobalObject(Ty, Value::GlobalVariableVal, AllocMarker, Link, Name,
579 AddressSpace),
580 isConstantGlobal(constant),
581 isExternallyInitializedConstant(isExternallyInitialized) {
582 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
583 "invalid type for global variable");
584 setThreadLocalMode(TLMode);
585 if (InitVal) {
586 assert(InitVal->getType() == Ty &&
587 "Initializer should be the same type as the GlobalVariable!");
588 Op<0>() = InitVal;
589 } else {
590 setGlobalVariableNumOperands(0);
591 }
592}
593
594GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
595 LinkageTypes Link, Constant *InitVal,
596 const Twine &Name, GlobalVariable *Before,
597 ThreadLocalMode TLMode,
598 std::optional<unsigned> AddressSpace,
599 bool isExternallyInitialized)
600 : GlobalVariable(Ty, constant, Link, InitVal, Name, TLMode,
601 AddressSpace
602 ? *AddressSpace
603 : M.getDataLayout().getDefaultGlobalsAddressSpace(),
604 isExternallyInitialized) {
605 if (Before)
606 Before->getParent()->insertGlobalVariable(Where: Before->getIterator(), GV: this);
607 else
608 M.insertGlobalVariable(GV: this);
609}
610
611void GlobalVariable::removeFromParent() {
612 getParent()->removeGlobalVariable(GV: this);
613}
614
615void GlobalVariable::eraseFromParent() {
616 getParent()->eraseGlobalVariable(GV: this);
617}
618
619void GlobalVariable::setInitializer(Constant *InitVal) {
620 if (!InitVal) {
621 if (hasInitializer()) {
622 // Note, the num operands is used to compute the offset of the operand, so
623 // the order here matters. Clearing the operand then clearing the num
624 // operands ensures we have the correct offset to the operand.
625 Op<0>().set(nullptr);
626 setGlobalVariableNumOperands(0);
627 }
628 } else {
629 assert(InitVal->getType() == getValueType() &&
630 "Initializer type must match GlobalVariable type");
631 // Note, the num operands is used to compute the offset of the operand, so
632 // the order here matters. We need to set num operands to 1 first so that
633 // we get the correct offset to the first operand when we set it.
634 if (!hasInitializer())
635 setGlobalVariableNumOperands(1);
636 Op<0>().set(InitVal);
637 }
638}
639
640void GlobalVariable::replaceInitializer(Constant *InitVal) {
641 assert(InitVal && "Can't compute type of null initializer");
642 ValueType = InitVal->getType();
643 setInitializer(InitVal);
644}
645
646uint64_t GlobalVariable::getGlobalSize(const DataLayout &DL) const {
647 // We don't support scalable global variables.
648 return DL.getTypeAllocSize(Ty: getValueType()).getFixedValue();
649}
650
651/// Copy all additional attributes (those not needed to create a GlobalVariable)
652/// from the GlobalVariable Src to this one.
653void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
654 GlobalObject::copyAttributesFrom(Src);
655 setExternallyInitialized(Src->isExternallyInitialized());
656 setAttributes(Src->getAttributes());
657 if (auto CM = Src->getCodeModel())
658 setCodeModel(*CM);
659}
660
661void GlobalVariable::dropAllReferences() {
662 User::dropAllReferences();
663 clearMetadata();
664}
665
666void GlobalVariable::setCodeModel(CodeModel::Model CM) {
667 unsigned CodeModelData = static_cast<unsigned>(CM) + 1;
668 unsigned OldData = getGlobalValueSubClassData();
669 unsigned NewData = (OldData & ~(CodeModelMask << CodeModelShift)) |
670 (CodeModelData << CodeModelShift);
671 setGlobalValueSubClassData(NewData);
672 assert(getCodeModel() == CM && "Code model representation error!");
673}
674
675void GlobalVariable::clearCodeModel() {
676 unsigned CodeModelData = 0;
677 unsigned OldData = getGlobalValueSubClassData();
678 unsigned NewData = (OldData & ~(CodeModelMask << CodeModelShift)) |
679 (CodeModelData << CodeModelShift);
680 setGlobalValueSubClassData(NewData);
681 assert(getCodeModel() == std::nullopt && "Code model representation error!");
682}
683
684//===----------------------------------------------------------------------===//
685// GlobalAlias Implementation
686//===----------------------------------------------------------------------===//
687
688GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
689 const Twine &Name, Constant *Aliasee,
690 Module *ParentModule)
691 : GlobalValue(Ty, Value::GlobalAliasVal, AllocMarker, Link, Name,
692 AddressSpace) {
693 setAliasee(Aliasee);
694 if (ParentModule)
695 ParentModule->insertAlias(Alias: this);
696}
697
698GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
699 LinkageTypes Link, const Twine &Name,
700 Constant *Aliasee, Module *ParentModule) {
701 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
702}
703
704GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
705 LinkageTypes Linkage, const Twine &Name,
706 Module *Parent) {
707 return create(Ty, AddressSpace, Link: Linkage, Name, Aliasee: nullptr, ParentModule: Parent);
708}
709
710GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
711 LinkageTypes Linkage, const Twine &Name,
712 GlobalValue *Aliasee) {
713 return create(Ty, AddressSpace, Link: Linkage, Name, Aliasee, ParentModule: Aliasee->getParent());
714}
715
716GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
717 GlobalValue *Aliasee) {
718 return create(Ty: Aliasee->getValueType(), AddressSpace: Aliasee->getAddressSpace(), Linkage: Link, Name,
719 Aliasee);
720}
721
722GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
723 return create(Link: Aliasee->getLinkage(), Name, Aliasee);
724}
725
726void GlobalAlias::removeFromParent() { getParent()->removeAlias(Alias: this); }
727
728void GlobalAlias::eraseFromParent() { getParent()->eraseAlias(Alias: this); }
729
730void GlobalAlias::setAliasee(Constant *Aliasee) {
731 assert((!Aliasee || Aliasee->getType() == getType()) &&
732 "Alias and aliasee types should match!");
733 Op<0>().set(Aliasee);
734}
735
736const GlobalObject *GlobalAlias::getAliaseeObject() const {
737 DenseSet<const GlobalAlias *> Aliases;
738 return findBaseObject(C: getOperand(i_nocapture: 0), Aliases, Op: [](const GlobalValue &) {});
739}
740
741//===----------------------------------------------------------------------===//
742// GlobalIFunc Implementation
743//===----------------------------------------------------------------------===//
744
745GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
746 const Twine &Name, Constant *Resolver,
747 Module *ParentModule)
748 : GlobalObject(Ty, Value::GlobalIFuncVal, AllocMarker, Link, Name,
749 AddressSpace) {
750 setResolver(Resolver);
751 if (ParentModule)
752 ParentModule->insertIFunc(IFunc: this);
753}
754
755GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
756 LinkageTypes Link, const Twine &Name,
757 Constant *Resolver, Module *ParentModule) {
758 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
759}
760
761void GlobalIFunc::removeFromParent() { getParent()->removeIFunc(IFunc: this); }
762
763void GlobalIFunc::eraseFromParent() { getParent()->eraseIFunc(IFunc: this); }
764
765const Function *GlobalIFunc::getResolverFunction() const {
766 return dyn_cast<Function>(Val: getResolver()->stripPointerCastsAndAliases());
767}
768
769void GlobalIFunc::applyAlongResolverPath(
770 function_ref<void(const GlobalValue &)> Op) const {
771 DenseSet<const GlobalAlias *> Aliases;
772 findBaseObject(C: getResolver(), Aliases, Op);
773}
774