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