xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Globals.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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/DerivedTypes.h"
18 #include "llvm/IR/GlobalAlias.h"
19 #include "llvm/IR/GlobalValue.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/TargetParser/Triple.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() { return getParent()->materialize(this); }
48 
49 /// Override destroyConstantImpl to make sure it doesn't get called on
50 /// GlobalValue's because they shouldn't be treated like other constants.
51 void GlobalValue::destroyConstantImpl() {
52   llvm_unreachable("You can't GV->destroyConstantImpl()!");
53 }
54 
55 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
56   llvm_unreachable("Unsupported class for handleOperandChange()!");
57 }
58 
59 /// copyAttributesFrom - copy all additional attributes (those not needed to
60 /// create a GlobalValue) from the GlobalValue Src to this one.
61 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
62   setVisibility(Src->getVisibility());
63   setUnnamedAddr(Src->getUnnamedAddr());
64   setThreadLocalMode(Src->getThreadLocalMode());
65   setDLLStorageClass(Src->getDLLStorageClass());
66   setDSOLocal(Src->isDSOLocal());
67   setPartition(Src->getPartition());
68   if (Src->hasSanitizerMetadata())
69     setSanitizerMetadata(Src->getSanitizerMetadata());
70   else
71     removeSanitizerMetadata();
72 }
73 
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"
80   default:
81     break;
82   }
83   llvm_unreachable("not a global");
84 }
85 
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"
92   default:
93     break;
94   }
95   llvm_unreachable("not a global");
96 }
97 
98 GlobalObject::~GlobalObject() { setComdat(nullptr); }
99 
100 bool GlobalValue::isInterposable() const {
101   if (isInterposableLinkage(getLinkage()))
102     return true;
103   return getParent() && getParent()->getSemanticInterposition() &&
104          !isDSOLocal();
105 }
106 
107 bool GlobalValue::canBenefitFromLocalAlias() const {
108   // See AsmPrinter::getSymbolPreferLocal(). For a deduplicate comdat kind,
109   // references to a discarded local symbol from outside the group are not
110   // allowed, so avoid the local alias.
111   auto isDeduplicateComdat = [](const Comdat *C) {
112     return C && C->getSelectionKind() != Comdat::NoDeduplicate;
113   };
114   return hasDefaultVisibility() &&
115          GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
116          !isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat());
117 }
118 
119 void GlobalObject::setAlignment(MaybeAlign Align) {
120   assert((!Align || *Align <= MaximumAlignment) &&
121          "Alignment is greater than MaximumAlignment!");
122   unsigned AlignmentData = encode(Align);
123   unsigned OldData = getGlobalValueSubClassData();
124   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
125   assert(getAlign() == Align && "Alignment representation error!");
126 }
127 
128 void GlobalObject::setAlignment(Align Align) {
129   assert(Align <= MaximumAlignment &&
130          "Alignment is greater than MaximumAlignment!");
131   unsigned AlignmentData = encode(Align);
132   unsigned OldData = getGlobalValueSubClassData();
133   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
134   assert(getAlign() && *getAlign() == Align &&
135          "Alignment representation error!");
136 }
137 
138 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
139   GlobalValue::copyAttributesFrom(Src);
140   setAlignment(Src->getAlign());
141   setSection(Src->getSection());
142 }
143 
144 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
145                                              GlobalValue::LinkageTypes Linkage,
146                                              StringRef FileName) {
147   // Value names may be prefixed with a binary '1' to indicate
148   // that the backend should not modify the symbols due to any platform
149   // naming convention. Do not include that '1' in the PGO profile name.
150   if (Name[0] == '\1')
151     Name = Name.substr(1);
152 
153   std::string GlobalName;
154   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
155     // For local symbols, prepend the main file name to distinguish them.
156     // Do not include the full path in the file name since there's no guarantee
157     // that it will stay the same, e.g., if the files are checked out from
158     // version control in different locations.
159     if (FileName.empty())
160       GlobalName += "<unknown>";
161     else
162       GlobalName += FileName;
163 
164     GlobalName += kGlobalIdentifierDelimiter;
165   }
166   GlobalName += Name;
167   return GlobalName;
168 }
169 
170 std::string GlobalValue::getGlobalIdentifier() const {
171   return getGlobalIdentifier(getName(), getLinkage(),
172                              getParent()->getSourceFileName());
173 }
174 
175 StringRef GlobalValue::getSection() const {
176   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
177     // In general we cannot compute this at the IR level, but we try.
178     if (const GlobalObject *GO = GA->getAliaseeObject())
179       return GO->getSection();
180     return "";
181   }
182   return cast<GlobalObject>(this)->getSection();
183 }
184 
185 const Comdat *GlobalValue::getComdat() const {
186   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
187     // In general we cannot compute this at the IR level, but we try.
188     if (const GlobalObject *GO = GA->getAliaseeObject())
189       return const_cast<GlobalObject *>(GO)->getComdat();
190     return nullptr;
191   }
192   // ifunc and its resolver are separate things so don't use resolver comdat.
193   if (isa<GlobalIFunc>(this))
194     return nullptr;
195   return cast<GlobalObject>(this)->getComdat();
196 }
197 
198 void GlobalObject::setComdat(Comdat *C) {
199   if (ObjComdat)
200     ObjComdat->removeUser(this);
201   ObjComdat = C;
202   if (C)
203     C->addUser(this);
204 }
205 
206 StringRef GlobalValue::getPartition() const {
207   if (!hasPartition())
208     return "";
209   return getContext().pImpl->GlobalValuePartitions[this];
210 }
211 
212 void GlobalValue::setPartition(StringRef S) {
213   // Do nothing if we're clearing the partition and it is already empty.
214   if (!hasPartition() && S.empty())
215     return;
216 
217   // Get or create a stable partition name string and put it in the table in the
218   // context.
219   if (!S.empty())
220     S = getContext().pImpl->Saver.save(S);
221   getContext().pImpl->GlobalValuePartitions[this] = S;
222 
223   // Update the HasPartition field. Setting the partition to the empty string
224   // means this global no longer has a partition.
225   HasPartition = !S.empty();
226 }
227 
228 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
229 const SanitizerMetadata &GlobalValue::getSanitizerMetadata() const {
230   assert(hasSanitizerMetadata());
231   assert(getContext().pImpl->GlobalValueSanitizerMetadata.count(this));
232   return getContext().pImpl->GlobalValueSanitizerMetadata[this];
233 }
234 
235 void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) {
236   getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
237   HasSanitizerMetadata = true;
238 }
239 
240 void GlobalValue::removeSanitizerMetadata() {
241   DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
242       getContext().pImpl->GlobalValueSanitizerMetadata;
243   MetadataMap.erase(this);
244   HasSanitizerMetadata = false;
245 }
246 
247 StringRef GlobalObject::getSectionImpl() const {
248   assert(hasSection());
249   return getContext().pImpl->GlobalObjectSections[this];
250 }
251 
252 void GlobalObject::setSection(StringRef S) {
253   // Do nothing if we're clearing the section and it is already empty.
254   if (!hasSection() && S.empty())
255     return;
256 
257   // Get or create a stable section name string and put it in the table in the
258   // context.
259   if (!S.empty())
260     S = getContext().pImpl->Saver.save(S);
261   getContext().pImpl->GlobalObjectSections[this] = S;
262 
263   // Update the HasSectionHashEntryBit. Setting the section to the empty string
264   // means this global no longer has a section.
265   setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
266 }
267 
268 bool GlobalValue::isNobuiltinFnDef() const {
269   const Function *F = dyn_cast<Function>(this);
270   if (!F || F->empty())
271     return false;
272   return F->hasFnAttribute(Attribute::NoBuiltin);
273 }
274 
275 bool GlobalValue::isDeclaration() const {
276   // Globals are definitions if they have an initializer.
277   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
278     return GV->getNumOperands() == 0;
279 
280   // Functions are definitions if they have a body.
281   if (const Function *F = dyn_cast<Function>(this))
282     return F->empty() && !F->isMaterializable();
283 
284   // Aliases and ifuncs are always definitions.
285   assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
286   return false;
287 }
288 
289 bool GlobalObject::canIncreaseAlignment() const {
290   // Firstly, can only increase the alignment of a global if it
291   // is a strong definition.
292   if (!isStrongDefinitionForLinker())
293     return false;
294 
295   // It also has to either not have a section defined, or, not have
296   // alignment specified. (If it is assigned a section, the global
297   // could be densely packed with other objects in the section, and
298   // increasing the alignment could cause padding issues.)
299   if (hasSection() && getAlign())
300     return false;
301 
302   // On ELF platforms, we're further restricted in that we can't
303   // increase the alignment of any variable which might be emitted
304   // into a shared library, and which is exported. If the main
305   // executable accesses a variable found in a shared-lib, the main
306   // exe actually allocates memory for and exports the symbol ITSELF,
307   // overriding the symbol found in the library. That is, at link
308   // time, the observed alignment of the variable is copied into the
309   // executable binary. (A COPY relocation is also generated, to copy
310   // the initial data from the shadowed variable in the shared-lib
311   // into the location in the main binary, before running code.)
312   //
313   // And thus, even though you might think you are defining the
314   // global, and allocating the memory for the global in your object
315   // file, and thus should be able to set the alignment arbitrarily,
316   // that's not actually true. Doing so can cause an ABI breakage; an
317   // executable might have already been built with the previous
318   // alignment of the variable, and then assuming an increased
319   // alignment will be incorrect.
320 
321   // Conservatively assume ELF if there's no parent pointer.
322   bool isELF =
323       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
324   if (isELF && !isDSOLocal())
325     return false;
326 
327   return true;
328 }
329 
330 template <typename Operation>
331 static const GlobalObject *
332 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases,
333                const Operation &Op) {
334   if (auto *GO = dyn_cast<GlobalObject>(C)) {
335     Op(*GO);
336     return GO;
337   }
338   if (auto *GA = dyn_cast<GlobalAlias>(C)) {
339     Op(*GA);
340     if (Aliases.insert(GA).second)
341       return findBaseObject(GA->getOperand(0), Aliases, Op);
342   }
343   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
344     switch (CE->getOpcode()) {
345     case Instruction::Add: {
346       auto *LHS = findBaseObject(CE->getOperand(0), Aliases, Op);
347       auto *RHS = findBaseObject(CE->getOperand(1), Aliases, Op);
348       if (LHS && RHS)
349         return nullptr;
350       return LHS ? LHS : RHS;
351     }
352     case Instruction::Sub: {
353       if (findBaseObject(CE->getOperand(1), Aliases, Op))
354         return nullptr;
355       return findBaseObject(CE->getOperand(0), Aliases, Op);
356     }
357     case Instruction::IntToPtr:
358     case Instruction::PtrToInt:
359     case Instruction::BitCast:
360     case Instruction::GetElementPtr:
361       return findBaseObject(CE->getOperand(0), Aliases, Op);
362     default:
363       break;
364     }
365   }
366   return nullptr;
367 }
368 
369 const GlobalObject *GlobalValue::getAliaseeObject() const {
370   DenseSet<const GlobalAlias *> Aliases;
371   return findBaseObject(this, Aliases, [](const GlobalValue &) {});
372 }
373 
374 bool GlobalValue::isAbsoluteSymbolRef() const {
375   auto *GO = dyn_cast<GlobalObject>(this);
376   if (!GO)
377     return false;
378 
379   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
380 }
381 
382 std::optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
383   auto *GO = dyn_cast<GlobalObject>(this);
384   if (!GO)
385     return std::nullopt;
386 
387   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
388   if (!MD)
389     return std::nullopt;
390 
391   return getConstantRangeFromMetadata(*MD);
392 }
393 
394 bool GlobalValue::canBeOmittedFromSymbolTable() const {
395   if (!hasLinkOnceODRLinkage())
396     return false;
397 
398   // We assume that anyone who sets global unnamed_addr on a non-constant
399   // knows what they're doing.
400   if (hasGlobalUnnamedAddr())
401     return true;
402 
403   // If it is a non constant variable, it needs to be uniqued across shared
404   // objects.
405   if (auto *Var = dyn_cast<GlobalVariable>(this))
406     if (!Var->isConstant())
407       return false;
408 
409   return hasAtLeastLocalUnnamedAddr();
410 }
411 
412 //===----------------------------------------------------------------------===//
413 // GlobalVariable Implementation
414 //===----------------------------------------------------------------------===//
415 
416 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
417                                Constant *InitVal, const Twine &Name,
418                                ThreadLocalMode TLMode, unsigned AddressSpace,
419                                bool isExternallyInitialized)
420     : GlobalObject(Ty, Value::GlobalVariableVal,
421                    OperandTraits<GlobalVariable>::op_begin(this),
422                    InitVal != nullptr, Link, Name, AddressSpace),
423       isConstantGlobal(constant),
424       isExternallyInitializedConstant(isExternallyInitialized) {
425   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
426          "invalid type for global variable");
427   setThreadLocalMode(TLMode);
428   if (InitVal) {
429     assert(InitVal->getType() == Ty &&
430            "Initializer should be the same type as the GlobalVariable!");
431     Op<0>() = InitVal;
432   }
433 }
434 
435 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
436                                LinkageTypes Link, Constant *InitVal,
437                                const Twine &Name, GlobalVariable *Before,
438                                ThreadLocalMode TLMode,
439                                std::optional<unsigned> AddressSpace,
440                                bool isExternallyInitialized)
441     : GlobalVariable(Ty, constant, Link, InitVal, Name, TLMode,
442                      AddressSpace
443                          ? *AddressSpace
444                          : M.getDataLayout().getDefaultGlobalsAddressSpace(),
445                      isExternallyInitialized) {
446   if (Before)
447     Before->getParent()->insertGlobalVariable(Before->getIterator(), this);
448   else
449     M.insertGlobalVariable(this);
450 }
451 
452 void GlobalVariable::removeFromParent() {
453   getParent()->removeGlobalVariable(this);
454 }
455 
456 void GlobalVariable::eraseFromParent() {
457   getParent()->eraseGlobalVariable(this);
458 }
459 
460 void GlobalVariable::setInitializer(Constant *InitVal) {
461   if (!InitVal) {
462     if (hasInitializer()) {
463       // Note, the num operands is used to compute the offset of the operand, so
464       // the order here matters.  Clearing the operand then clearing the num
465       // operands ensures we have the correct offset to the operand.
466       Op<0>().set(nullptr);
467       setGlobalVariableNumOperands(0);
468     }
469   } else {
470     assert(InitVal->getType() == getValueType() &&
471            "Initializer type must match GlobalVariable type");
472     // Note, the num operands is used to compute the offset of the operand, so
473     // the order here matters.  We need to set num operands to 1 first so that
474     // we get the correct offset to the first operand when we set it.
475     if (!hasInitializer())
476       setGlobalVariableNumOperands(1);
477     Op<0>().set(InitVal);
478   }
479 }
480 
481 /// Copy all additional attributes (those not needed to create a GlobalVariable)
482 /// from the GlobalVariable Src to this one.
483 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
484   GlobalObject::copyAttributesFrom(Src);
485   setExternallyInitialized(Src->isExternallyInitialized());
486   setAttributes(Src->getAttributes());
487   if (auto CM = Src->getCodeModel())
488     setCodeModel(*CM);
489 }
490 
491 void GlobalVariable::dropAllReferences() {
492   User::dropAllReferences();
493   clearMetadata();
494 }
495 
496 void GlobalVariable::setCodeModel(CodeModel::Model CM) {
497   unsigned CodeModelData = static_cast<unsigned>(CM) + 1;
498   unsigned OldData = getGlobalValueSubClassData();
499   unsigned NewData = (OldData & ~(CodeModelMask << CodeModelShift)) |
500                      (CodeModelData << CodeModelShift);
501   setGlobalValueSubClassData(NewData);
502   assert(getCodeModel() == CM && "Code model representation error!");
503 }
504 
505 //===----------------------------------------------------------------------===//
506 // GlobalAlias Implementation
507 //===----------------------------------------------------------------------===//
508 
509 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
510                          const Twine &Name, Constant *Aliasee,
511                          Module *ParentModule)
512     : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
513                   AddressSpace) {
514   setAliasee(Aliasee);
515   if (ParentModule)
516     ParentModule->insertAlias(this);
517 }
518 
519 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
520                                  LinkageTypes Link, const Twine &Name,
521                                  Constant *Aliasee, Module *ParentModule) {
522   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
523 }
524 
525 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
526                                  LinkageTypes Linkage, const Twine &Name,
527                                  Module *Parent) {
528   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
529 }
530 
531 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
532                                  LinkageTypes Linkage, const Twine &Name,
533                                  GlobalValue *Aliasee) {
534   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
535 }
536 
537 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
538                                  GlobalValue *Aliasee) {
539   return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
540                 Aliasee);
541 }
542 
543 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
544   return create(Aliasee->getLinkage(), Name, Aliasee);
545 }
546 
547 void GlobalAlias::removeFromParent() { getParent()->removeAlias(this); }
548 
549 void GlobalAlias::eraseFromParent() { getParent()->eraseAlias(this); }
550 
551 void GlobalAlias::setAliasee(Constant *Aliasee) {
552   assert((!Aliasee || Aliasee->getType() == getType()) &&
553          "Alias and aliasee types should match!");
554   Op<0>().set(Aliasee);
555 }
556 
557 const GlobalObject *GlobalAlias::getAliaseeObject() const {
558   DenseSet<const GlobalAlias *> Aliases;
559   return findBaseObject(getOperand(0), Aliases, [](const GlobalValue &) {});
560 }
561 
562 //===----------------------------------------------------------------------===//
563 // GlobalIFunc Implementation
564 //===----------------------------------------------------------------------===//
565 
566 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
567                          const Twine &Name, Constant *Resolver,
568                          Module *ParentModule)
569     : GlobalObject(Ty, Value::GlobalIFuncVal, &Op<0>(), 1, Link, Name,
570                    AddressSpace) {
571   setResolver(Resolver);
572   if (ParentModule)
573     ParentModule->insertIFunc(this);
574 }
575 
576 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
577                                  LinkageTypes Link, const Twine &Name,
578                                  Constant *Resolver, Module *ParentModule) {
579   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
580 }
581 
582 void GlobalIFunc::removeFromParent() { getParent()->removeIFunc(this); }
583 
584 void GlobalIFunc::eraseFromParent() { getParent()->eraseIFunc(this); }
585 
586 const Function *GlobalIFunc::getResolverFunction() const {
587   return dyn_cast<Function>(getResolver()->stripPointerCastsAndAliases());
588 }
589 
590 void GlobalIFunc::applyAlongResolverPath(
591     function_ref<void(const GlobalValue &)> Op) const {
592   DenseSet<const GlobalAlias *> Aliases;
593   findBaseObject(getResolver(), Aliases, Op);
594 }
595