xref: /llvm-project-15.0.7/llvm/lib/IR/Globals.cpp (revision d648aa1b)
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/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"
25 using namespace llvm;
26 
27 //===----------------------------------------------------------------------===//
28 //                            GlobalValue Class
29 //===----------------------------------------------------------------------===//
30 
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");
37 
38 // GlobalObject adds a comdat.
39 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
40               "unexpected GlobalObject size growth");
41 
42 bool GlobalValue::isMaterializable() const {
43   if (const Function *F = dyn_cast<Function>(this))
44     return F->isMaterializable();
45   return false;
46 }
47 Error GlobalValue::materialize() {
48   return getParent()->materialize(this);
49 }
50 
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()!");
55 }
56 
57 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
58   llvm_unreachable("Unsupported class for handleOperandChange()!");
59 }
60 
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());
72   else
73     removeSanitizerMetadata();
74 }
75 
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"
82   default:
83     break;
84   }
85   llvm_unreachable("not a global");
86 }
87 
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"
94   default:
95     break;
96   }
97   llvm_unreachable("not a global");
98 }
99 
100 GlobalObject::~GlobalObject() { setComdat(nullptr); }
101 
102 bool GlobalValue::isInterposable() const {
103   if (isInterposableLinkage(getLinkage()))
104     return true;
105   return getParent() && getParent()->getSemanticInterposition() &&
106          !isDSOLocal();
107 }
108 
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;
115   };
116   return hasDefaultVisibility() &&
117          GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
118          !isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat());
119 }
120 
121 unsigned GlobalValue::getAddressSpace() const {
122   PointerType *PtrTy = getType();
123   return PtrTy->getAddressSpace();
124 }
125 
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!");
134 }
135 
136 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
137   GlobalValue::copyAttributesFrom(Src);
138   setAlignment(Src->getAlign());
139   setSection(Src->getSection());
140 }
141 
142 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
143                                              GlobalValue::LinkageTypes Linkage,
144                                              StringRef FileName) {
145 
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.
149   if (Name[0] == '\1')
150     Name = Name.substr(1);
151 
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>:");
160     else
161       NewName = NewName.insert(0, FileName.str() + ":");
162   }
163   return NewName;
164 }
165 
166 std::string GlobalValue::getGlobalIdentifier() const {
167   return getGlobalIdentifier(getName(), getLinkage(),
168                              getParent()->getSourceFileName());
169 }
170 
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();
176     return "";
177   }
178   return cast<GlobalObject>(this)->getSection();
179 }
180 
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();
186     return nullptr;
187   }
188   // ifunc and its resolver are separate things so don't use resolver comdat.
189   if (isa<GlobalIFunc>(this))
190     return nullptr;
191   return cast<GlobalObject>(this)->getComdat();
192 }
193 
194 void GlobalObject::setComdat(Comdat *C) {
195   if (ObjComdat)
196     ObjComdat->removeUser(this);
197   ObjComdat = C;
198   if (C)
199     C->addUser(this);
200 }
201 
202 StringRef GlobalValue::getPartition() const {
203   if (!hasPartition())
204     return "";
205   return getContext().pImpl->GlobalValuePartitions[this];
206 }
207 
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())
211     return;
212 
213   // Get or create a stable partition name string and put it in the table in the
214   // context.
215   if (!S.empty())
216     S = getContext().pImpl->Saver.save(S);
217   getContext().pImpl->GlobalValuePartitions[this] = S;
218 
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();
222 }
223 
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];
229 }
230 
231 void GlobalValue::setSanitizerMetadata(const SanitizerMetadata &Meta) {
232   getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
233   HasSanitizerMetadata = true;
234 }
235 
236 void GlobalValue::removeSanitizerMetadata() {
237   DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
238       getContext().pImpl->GlobalValueSanitizerMetadata;
239   auto It = MetadataMap.find(this);
240   if (It != MetadataMap.end())
241     MetadataMap.erase(It);
242   HasSanitizerMetadata = false;
243 }
244 
245 StringRef GlobalObject::getSectionImpl() const {
246   assert(hasSection());
247   return getContext().pImpl->GlobalObjectSections[this];
248 }
249 
250 void GlobalObject::setSection(StringRef S) {
251   // Do nothing if we're clearing the section and it is already empty.
252   if (!hasSection() && S.empty())
253     return;
254 
255   // Get or create a stable section name string and put it in the table in the
256   // context.
257   if (!S.empty())
258     S = getContext().pImpl->Saver.save(S);
259   getContext().pImpl->GlobalObjectSections[this] = S;
260 
261   // Update the HasSectionHashEntryBit. Setting the section to the empty string
262   // means this global no longer has a section.
263   setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
264 }
265 
266 bool GlobalValue::isDeclaration() const {
267   // Globals are definitions if they have an initializer.
268   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
269     return GV->getNumOperands() == 0;
270 
271   // Functions are definitions if they have a body.
272   if (const Function *F = dyn_cast<Function>(this))
273     return F->empty() && !F->isMaterializable();
274 
275   // Aliases and ifuncs are always definitions.
276   assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
277   return false;
278 }
279 
280 bool GlobalObject::canIncreaseAlignment() const {
281   // Firstly, can only increase the alignment of a global if it
282   // is a strong definition.
283   if (!isStrongDefinitionForLinker())
284     return false;
285 
286   // It also has to either not have a section defined, or, not have
287   // alignment specified. (If it is assigned a section, the global
288   // could be densely packed with other objects in the section, and
289   // increasing the alignment could cause padding issues.)
290   if (hasSection() && getAlign().hasValue())
291     return false;
292 
293   // On ELF platforms, we're further restricted in that we can't
294   // increase the alignment of any variable which might be emitted
295   // into a shared library, and which is exported. If the main
296   // executable accesses a variable found in a shared-lib, the main
297   // exe actually allocates memory for and exports the symbol ITSELF,
298   // overriding the symbol found in the library. That is, at link
299   // time, the observed alignment of the variable is copied into the
300   // executable binary. (A COPY relocation is also generated, to copy
301   // the initial data from the shadowed variable in the shared-lib
302   // into the location in the main binary, before running code.)
303   //
304   // And thus, even though you might think you are defining the
305   // global, and allocating the memory for the global in your object
306   // file, and thus should be able to set the alignment arbitrarily,
307   // that's not actually true. Doing so can cause an ABI breakage; an
308   // executable might have already been built with the previous
309   // alignment of the variable, and then assuming an increased
310   // alignment will be incorrect.
311 
312   // Conservatively assume ELF if there's no parent pointer.
313   bool isELF =
314       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
315   if (isELF && !isDSOLocal())
316     return false;
317 
318   return true;
319 }
320 
321 static const GlobalObject *
322 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases) {
323   if (auto *GO = dyn_cast<GlobalObject>(C))
324     return GO;
325   if (auto *GA = dyn_cast<GlobalAlias>(C))
326     if (Aliases.insert(GA).second)
327       return findBaseObject(GA->getOperand(0), Aliases);
328   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
329     switch (CE->getOpcode()) {
330     case Instruction::Add: {
331       auto *LHS = findBaseObject(CE->getOperand(0), Aliases);
332       auto *RHS = findBaseObject(CE->getOperand(1), Aliases);
333       if (LHS && RHS)
334         return nullptr;
335       return LHS ? LHS : RHS;
336     }
337     case Instruction::Sub: {
338       if (findBaseObject(CE->getOperand(1), Aliases))
339         return nullptr;
340       return findBaseObject(CE->getOperand(0), Aliases);
341     }
342     case Instruction::IntToPtr:
343     case Instruction::PtrToInt:
344     case Instruction::BitCast:
345     case Instruction::GetElementPtr:
346       return findBaseObject(CE->getOperand(0), Aliases);
347     default:
348       break;
349     }
350   }
351   return nullptr;
352 }
353 
354 const GlobalObject *GlobalValue::getAliaseeObject() const {
355   DenseSet<const GlobalAlias *> Aliases;
356   return findBaseObject(this, Aliases);
357 }
358 
359 bool GlobalValue::isAbsoluteSymbolRef() const {
360   auto *GO = dyn_cast<GlobalObject>(this);
361   if (!GO)
362     return false;
363 
364   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
365 }
366 
367 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
368   auto *GO = dyn_cast<GlobalObject>(this);
369   if (!GO)
370     return None;
371 
372   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
373   if (!MD)
374     return None;
375 
376   return getConstantRangeFromMetadata(*MD);
377 }
378 
379 bool GlobalValue::canBeOmittedFromSymbolTable() const {
380   if (!hasLinkOnceODRLinkage())
381     return false;
382 
383   // We assume that anyone who sets global unnamed_addr on a non-constant
384   // knows what they're doing.
385   if (hasGlobalUnnamedAddr())
386     return true;
387 
388   // If it is a non constant variable, it needs to be uniqued across shared
389   // objects.
390   if (auto *Var = dyn_cast<GlobalVariable>(this))
391     if (!Var->isConstant())
392       return false;
393 
394   return hasAtLeastLocalUnnamedAddr();
395 }
396 
397 //===----------------------------------------------------------------------===//
398 // GlobalVariable Implementation
399 //===----------------------------------------------------------------------===//
400 
401 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
402                                Constant *InitVal, const Twine &Name,
403                                ThreadLocalMode TLMode, unsigned AddressSpace,
404                                bool isExternallyInitialized)
405     : GlobalObject(Ty, Value::GlobalVariableVal,
406                    OperandTraits<GlobalVariable>::op_begin(this),
407                    InitVal != nullptr, Link, Name, AddressSpace),
408       isConstantGlobal(constant),
409       isExternallyInitializedConstant(isExternallyInitialized) {
410   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
411          "invalid type for global variable");
412   setThreadLocalMode(TLMode);
413   if (InitVal) {
414     assert(InitVal->getType() == Ty &&
415            "Initializer should be the same type as the GlobalVariable!");
416     Op<0>() = InitVal;
417   }
418 }
419 
420 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
421                                LinkageTypes Link, Constant *InitVal,
422                                const Twine &Name, GlobalVariable *Before,
423                                ThreadLocalMode TLMode,
424                                Optional<unsigned> AddressSpace,
425                                bool isExternallyInitialized)
426     : GlobalObject(Ty, Value::GlobalVariableVal,
427                    OperandTraits<GlobalVariable>::op_begin(this),
428                    InitVal != nullptr, Link, Name,
429                    AddressSpace
430                        ? *AddressSpace
431                        : M.getDataLayout().getDefaultGlobalsAddressSpace()),
432       isConstantGlobal(constant),
433       isExternallyInitializedConstant(isExternallyInitialized) {
434   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
435          "invalid type for global variable");
436   setThreadLocalMode(TLMode);
437   if (InitVal) {
438     assert(InitVal->getType() == Ty &&
439            "Initializer should be the same type as the GlobalVariable!");
440     Op<0>() = InitVal;
441   }
442 
443   if (Before)
444     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
445   else
446     M.getGlobalList().push_back(this);
447 }
448 
449 void GlobalVariable::removeFromParent() {
450   getParent()->getGlobalList().remove(getIterator());
451 }
452 
453 void GlobalVariable::eraseFromParent() {
454   getParent()->getGlobalList().erase(getIterator());
455 }
456 
457 void GlobalVariable::setInitializer(Constant *InitVal) {
458   if (!InitVal) {
459     if (hasInitializer()) {
460       // Note, the num operands is used to compute the offset of the operand, so
461       // the order here matters.  Clearing the operand then clearing the num
462       // operands ensures we have the correct offset to the operand.
463       Op<0>().set(nullptr);
464       setGlobalVariableNumOperands(0);
465     }
466   } else {
467     assert(InitVal->getType() == getValueType() &&
468            "Initializer type must match GlobalVariable type");
469     // Note, the num operands is used to compute the offset of the operand, so
470     // the order here matters.  We need to set num operands to 1 first so that
471     // we get the correct offset to the first operand when we set it.
472     if (!hasInitializer())
473       setGlobalVariableNumOperands(1);
474     Op<0>().set(InitVal);
475   }
476 }
477 
478 /// Copy all additional attributes (those not needed to create a GlobalVariable)
479 /// from the GlobalVariable Src to this one.
480 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
481   GlobalObject::copyAttributesFrom(Src);
482   setExternallyInitialized(Src->isExternallyInitialized());
483   setAttributes(Src->getAttributes());
484 }
485 
486 void GlobalVariable::dropAllReferences() {
487   User::dropAllReferences();
488   clearMetadata();
489 }
490 
491 //===----------------------------------------------------------------------===//
492 // GlobalAlias Implementation
493 //===----------------------------------------------------------------------===//
494 
495 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
496                          const Twine &Name, Constant *Aliasee,
497                          Module *ParentModule)
498     : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
499                   AddressSpace) {
500   setAliasee(Aliasee);
501   if (ParentModule)
502     ParentModule->getAliasList().push_back(this);
503 }
504 
505 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
506                                  LinkageTypes Link, const Twine &Name,
507                                  Constant *Aliasee, Module *ParentModule) {
508   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
509 }
510 
511 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
512                                  LinkageTypes Linkage, const Twine &Name,
513                                  Module *Parent) {
514   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
515 }
516 
517 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
518                                  LinkageTypes Linkage, const Twine &Name,
519                                  GlobalValue *Aliasee) {
520   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
521 }
522 
523 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
524                                  GlobalValue *Aliasee) {
525   return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
526                 Aliasee);
527 }
528 
529 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
530   return create(Aliasee->getLinkage(), Name, Aliasee);
531 }
532 
533 void GlobalAlias::removeFromParent() {
534   getParent()->getAliasList().remove(getIterator());
535 }
536 
537 void GlobalAlias::eraseFromParent() {
538   getParent()->getAliasList().erase(getIterator());
539 }
540 
541 void GlobalAlias::setAliasee(Constant *Aliasee) {
542   assert((!Aliasee || Aliasee->getType() == getType()) &&
543          "Alias and aliasee types should match!");
544   Op<0>().set(Aliasee);
545 }
546 
547 const GlobalObject *GlobalAlias::getAliaseeObject() const {
548   DenseSet<const GlobalAlias *> Aliases;
549   return findBaseObject(getOperand(0), Aliases);
550 }
551 
552 //===----------------------------------------------------------------------===//
553 // GlobalIFunc Implementation
554 //===----------------------------------------------------------------------===//
555 
556 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
557                          const Twine &Name, Constant *Resolver,
558                          Module *ParentModule)
559     : GlobalObject(Ty, Value::GlobalIFuncVal, &Op<0>(), 1, Link, Name,
560                    AddressSpace) {
561   setResolver(Resolver);
562   if (ParentModule)
563     ParentModule->getIFuncList().push_back(this);
564 }
565 
566 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
567                                  LinkageTypes Link, const Twine &Name,
568                                  Constant *Resolver, Module *ParentModule) {
569   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
570 }
571 
572 void GlobalIFunc::removeFromParent() {
573   getParent()->getIFuncList().remove(getIterator());
574 }
575 
576 void GlobalIFunc::eraseFromParent() {
577   getParent()->getIFuncList().erase(getIterator());
578 }
579 
580 const Function *GlobalIFunc::getResolverFunction() const {
581   DenseSet<const GlobalAlias *> Aliases;
582   return dyn_cast<Function>(findBaseObject(getResolver(), Aliases));
583 }
584