xref: /llvm-project-15.0.7/llvm/lib/IR/Globals.cpp (revision 90e4ebdc)
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/SmallPtrSet.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/IR/ConstantRange.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
27 using namespace llvm;
28 
29 //===----------------------------------------------------------------------===//
30 //                            GlobalValue Class
31 //===----------------------------------------------------------------------===//
32 
33 // GlobalValue should be a Constant, plus a type, a module, some flags, and an
34 // intrinsic ID. Add an assert to prevent people from accidentally growing
35 // GlobalValue while adding flags.
36 static_assert(sizeof(GlobalValue) ==
37                   sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
38               "unexpected GlobalValue size growth");
39 
40 // GlobalObject adds a comdat.
41 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
42               "unexpected GlobalObject size growth");
43 
44 bool GlobalValue::isMaterializable() const {
45   if (const Function *F = dyn_cast<Function>(this))
46     return F->isMaterializable();
47   return false;
48 }
49 Error GlobalValue::materialize() {
50   return getParent()->materialize(this);
51 }
52 
53 /// Override destroyConstantImpl to make sure it doesn't get called on
54 /// GlobalValue's because they shouldn't be treated like other constants.
55 void GlobalValue::destroyConstantImpl() {
56   llvm_unreachable("You can't GV->destroyConstantImpl()!");
57 }
58 
59 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
60   llvm_unreachable("Unsupported class for handleOperandChange()!");
61 }
62 
63 /// copyAttributesFrom - copy all additional attributes (those not needed to
64 /// create a GlobalValue) from the GlobalValue Src to this one.
65 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
66   setVisibility(Src->getVisibility());
67   setUnnamedAddr(Src->getUnnamedAddr());
68   setDLLStorageClass(Src->getDLLStorageClass());
69   setDSOLocal(Src->isDSOLocal());
70   setPartition(Src->getPartition());
71 }
72 
73 void GlobalValue::removeFromParent() {
74   switch (getValueID()) {
75 #define HANDLE_GLOBAL_VALUE(NAME)                                              \
76   case Value::NAME##Val:                                                       \
77     return static_cast<NAME *>(this)->removeFromParent();
78 #include "llvm/IR/Value.def"
79   default:
80     break;
81   }
82   llvm_unreachable("not a global");
83 }
84 
85 void GlobalValue::eraseFromParent() {
86   switch (getValueID()) {
87 #define HANDLE_GLOBAL_VALUE(NAME)                                              \
88   case Value::NAME##Val:                                                       \
89     return static_cast<NAME *>(this)->eraseFromParent();
90 #include "llvm/IR/Value.def"
91   default:
92     break;
93   }
94   llvm_unreachable("not a global");
95 }
96 
97 bool GlobalValue::isInterposable() const {
98   if (isInterposableLinkage(getLinkage()))
99     return true;
100   return getParent() && getParent()->getSemanticInterposition() &&
101          !isDSOLocal();
102 }
103 
104 unsigned GlobalValue::getAlignment() const {
105   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
106     // In general we cannot compute this at the IR level, but we try.
107     if (const GlobalObject *GO = GA->getBaseObject())
108       return GO->getAlignment();
109 
110     // FIXME: we should also be able to handle:
111     // Alias = Global + Offset
112     // Alias = Absolute
113     return 0;
114   }
115   return cast<GlobalObject>(this)->getAlignment();
116 }
117 
118 unsigned GlobalValue::getAddressSpace() const {
119   PointerType *PtrTy = getType();
120   return PtrTy->getAddressSpace();
121 }
122 
123 void GlobalObject::setAlignment(unsigned Align) {
124   setAlignment(MaybeAlign(Align));
125 }
126 
127 void GlobalObject::setAlignment(MaybeAlign Align) {
128   assert((!Align || Align <= MaximumAlignment) &&
129          "Alignment is greater than MaximumAlignment!");
130   unsigned AlignmentData = encode(Align);
131   unsigned OldData = getGlobalValueSubClassData();
132   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
133   assert(MaybeAlign(getAlignment()) == Align &&
134          "Alignment representation error!");
135 }
136 
137 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
138   GlobalValue::copyAttributesFrom(Src);
139   setAlignment(MaybeAlign(Src->getAlignment()));
140   setSection(Src->getSection());
141 }
142 
143 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
144                                              GlobalValue::LinkageTypes Linkage,
145                                              StringRef FileName) {
146 
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 NewName = std::string(Name);
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       NewName = NewName.insert(0, "<unknown>:");
161     else
162       NewName = NewName.insert(0, FileName.str() + ":");
163   }
164   return NewName;
165 }
166 
167 std::string GlobalValue::getGlobalIdentifier() const {
168   return getGlobalIdentifier(getName(), getLinkage(),
169                              getParent()->getSourceFileName());
170 }
171 
172 StringRef GlobalValue::getSection() const {
173   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
174     // In general we cannot compute this at the IR level, but we try.
175     if (const GlobalObject *GO = GA->getBaseObject())
176       return GO->getSection();
177     return "";
178   }
179   return cast<GlobalObject>(this)->getSection();
180 }
181 
182 const Comdat *GlobalValue::getComdat() const {
183   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
184     // In general we cannot compute this at the IR level, but we try.
185     if (const GlobalObject *GO = GA->getBaseObject())
186       return const_cast<GlobalObject *>(GO)->getComdat();
187     return nullptr;
188   }
189   // ifunc and its resolver are separate things so don't use resolver comdat.
190   if (isa<GlobalIFunc>(this))
191     return nullptr;
192   return cast<GlobalObject>(this)->getComdat();
193 }
194 
195 StringRef GlobalValue::getPartition() const {
196   if (!hasPartition())
197     return "";
198   return getContext().pImpl->GlobalValuePartitions[this];
199 }
200 
201 void GlobalValue::setPartition(StringRef S) {
202   // Do nothing if we're clearing the partition and it is already empty.
203   if (!hasPartition() && S.empty())
204     return;
205 
206   // Get or create a stable partition name string and put it in the table in the
207   // context.
208   if (!S.empty())
209     S = getContext().pImpl->Saver.save(S);
210   getContext().pImpl->GlobalValuePartitions[this] = S;
211 
212   // Update the HasPartition field. Setting the partition to the empty string
213   // means this global no longer has a partition.
214   HasPartition = !S.empty();
215 }
216 
217 StringRef GlobalObject::getSectionImpl() const {
218   assert(hasSection());
219   return getContext().pImpl->GlobalObjectSections[this];
220 }
221 
222 void GlobalObject::setSection(StringRef S) {
223   // Do nothing if we're clearing the section and it is already empty.
224   if (!hasSection() && S.empty())
225     return;
226 
227   // Get or create a stable section name string and put it in the table in the
228   // context.
229   if (!S.empty())
230     S = getContext().pImpl->Saver.save(S);
231   getContext().pImpl->GlobalObjectSections[this] = S;
232 
233   // Update the HasSectionHashEntryBit. Setting the section to the empty string
234   // means this global no longer has a section.
235   setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
236 }
237 
238 bool GlobalValue::isDeclaration() const {
239   // Globals are definitions if they have an initializer.
240   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
241     return GV->getNumOperands() == 0;
242 
243   // Functions are definitions if they have a body.
244   if (const Function *F = dyn_cast<Function>(this))
245     return F->empty() && !F->isMaterializable();
246 
247   // Aliases and ifuncs are always definitions.
248   assert(isa<GlobalIndirectSymbol>(this));
249   return false;
250 }
251 
252 bool GlobalValue::canIncreaseAlignment() const {
253   // Firstly, can only increase the alignment of a global if it
254   // is a strong definition.
255   if (!isStrongDefinitionForLinker())
256     return false;
257 
258   // It also has to either not have a section defined, or, not have
259   // alignment specified. (If it is assigned a section, the global
260   // could be densely packed with other objects in the section, and
261   // increasing the alignment could cause padding issues.)
262   if (hasSection() && getAlignment() > 0)
263     return false;
264 
265   // On ELF platforms, we're further restricted in that we can't
266   // increase the alignment of any variable which might be emitted
267   // into a shared library, and which is exported. If the main
268   // executable accesses a variable found in a shared-lib, the main
269   // exe actually allocates memory for and exports the symbol ITSELF,
270   // overriding the symbol found in the library. That is, at link
271   // time, the observed alignment of the variable is copied into the
272   // executable binary. (A COPY relocation is also generated, to copy
273   // the initial data from the shadowed variable in the shared-lib
274   // into the location in the main binary, before running code.)
275   //
276   // And thus, even though you might think you are defining the
277   // global, and allocating the memory for the global in your object
278   // file, and thus should be able to set the alignment arbitrarily,
279   // that's not actually true. Doing so can cause an ABI breakage; an
280   // executable might have already been built with the previous
281   // alignment of the variable, and then assuming an increased
282   // alignment will be incorrect.
283 
284   // Conservatively assume ELF if there's no parent pointer.
285   bool isELF =
286       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
287   if (isELF && !isDSOLocal())
288     return false;
289 
290   return true;
291 }
292 
293 const GlobalObject *GlobalValue::getBaseObject() const {
294   if (auto *GO = dyn_cast<GlobalObject>(this))
295     return GO;
296   if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
297     return GA->getBaseObject();
298   return nullptr;
299 }
300 
301 bool GlobalValue::isAbsoluteSymbolRef() const {
302   auto *GO = dyn_cast<GlobalObject>(this);
303   if (!GO)
304     return false;
305 
306   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
307 }
308 
309 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
310   auto *GO = dyn_cast<GlobalObject>(this);
311   if (!GO)
312     return None;
313 
314   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
315   if (!MD)
316     return None;
317 
318   return getConstantRangeFromMetadata(*MD);
319 }
320 
321 bool GlobalValue::canBeOmittedFromSymbolTable() const {
322   if (!hasLinkOnceODRLinkage())
323     return false;
324 
325   // We assume that anyone who sets global unnamed_addr on a non-constant
326   // knows what they're doing.
327   if (hasGlobalUnnamedAddr())
328     return true;
329 
330   // If it is a non constant variable, it needs to be uniqued across shared
331   // objects.
332   if (auto *Var = dyn_cast<GlobalVariable>(this))
333     if (!Var->isConstant())
334       return false;
335 
336   return hasAtLeastLocalUnnamedAddr();
337 }
338 
339 //===----------------------------------------------------------------------===//
340 // GlobalVariable Implementation
341 //===----------------------------------------------------------------------===//
342 
343 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
344                                Constant *InitVal, const Twine &Name,
345                                ThreadLocalMode TLMode, unsigned AddressSpace,
346                                bool isExternallyInitialized)
347     : GlobalObject(Ty, Value::GlobalVariableVal,
348                    OperandTraits<GlobalVariable>::op_begin(this),
349                    InitVal != nullptr, Link, Name, AddressSpace),
350       isConstantGlobal(constant),
351       isExternallyInitializedConstant(isExternallyInitialized) {
352   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
353          "invalid type for global variable");
354   setThreadLocalMode(TLMode);
355   if (InitVal) {
356     assert(InitVal->getType() == Ty &&
357            "Initializer should be the same type as the GlobalVariable!");
358     Op<0>() = InitVal;
359   }
360 }
361 
362 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
363                                LinkageTypes Link, Constant *InitVal,
364                                const Twine &Name, GlobalVariable *Before,
365                                ThreadLocalMode TLMode, unsigned AddressSpace,
366                                bool isExternallyInitialized)
367     : GlobalObject(Ty, Value::GlobalVariableVal,
368                    OperandTraits<GlobalVariable>::op_begin(this),
369                    InitVal != nullptr, Link, Name, AddressSpace),
370       isConstantGlobal(constant),
371       isExternallyInitializedConstant(isExternallyInitialized) {
372   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
373          "invalid type for global variable");
374   setThreadLocalMode(TLMode);
375   if (InitVal) {
376     assert(InitVal->getType() == Ty &&
377            "Initializer should be the same type as the GlobalVariable!");
378     Op<0>() = InitVal;
379   }
380 
381   if (Before)
382     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
383   else
384     M.getGlobalList().push_back(this);
385 }
386 
387 void GlobalVariable::removeFromParent() {
388   getParent()->getGlobalList().remove(getIterator());
389 }
390 
391 void GlobalVariable::eraseFromParent() {
392   getParent()->getGlobalList().erase(getIterator());
393 }
394 
395 void GlobalVariable::setInitializer(Constant *InitVal) {
396   if (!InitVal) {
397     if (hasInitializer()) {
398       // Note, the num operands is used to compute the offset of the operand, so
399       // the order here matters.  Clearing the operand then clearing the num
400       // operands ensures we have the correct offset to the operand.
401       Op<0>().set(nullptr);
402       setGlobalVariableNumOperands(0);
403     }
404   } else {
405     assert(InitVal->getType() == getValueType() &&
406            "Initializer type must match GlobalVariable type");
407     // Note, the num operands is used to compute the offset of the operand, so
408     // the order here matters.  We need to set num operands to 1 first so that
409     // we get the correct offset to the first operand when we set it.
410     if (!hasInitializer())
411       setGlobalVariableNumOperands(1);
412     Op<0>().set(InitVal);
413   }
414 }
415 
416 /// Copy all additional attributes (those not needed to create a GlobalVariable)
417 /// from the GlobalVariable Src to this one.
418 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
419   GlobalObject::copyAttributesFrom(Src);
420   setThreadLocalMode(Src->getThreadLocalMode());
421   setExternallyInitialized(Src->isExternallyInitialized());
422   setAttributes(Src->getAttributes());
423 }
424 
425 void GlobalVariable::dropAllReferences() {
426   User::dropAllReferences();
427   clearMetadata();
428 }
429 
430 //===----------------------------------------------------------------------===//
431 // GlobalIndirectSymbol Implementation
432 //===----------------------------------------------------------------------===//
433 
434 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
435     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
436     Constant *Symbol)
437     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
438     Op<0>() = Symbol;
439 }
440 
441 static const GlobalObject *
442 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases) {
443   if (auto *GO = dyn_cast<GlobalObject>(C))
444     return GO;
445   if (auto *GA = dyn_cast<GlobalAlias>(C))
446     if (Aliases.insert(GA).second)
447       return findBaseObject(GA->getOperand(0), Aliases);
448   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
449     switch (CE->getOpcode()) {
450     case Instruction::Add: {
451       auto *LHS = findBaseObject(CE->getOperand(0), Aliases);
452       auto *RHS = findBaseObject(CE->getOperand(1), Aliases);
453       if (LHS && RHS)
454         return nullptr;
455       return LHS ? LHS : RHS;
456     }
457     case Instruction::Sub: {
458       if (findBaseObject(CE->getOperand(1), Aliases))
459         return nullptr;
460       return findBaseObject(CE->getOperand(0), Aliases);
461     }
462     case Instruction::IntToPtr:
463     case Instruction::PtrToInt:
464     case Instruction::BitCast:
465     case Instruction::GetElementPtr:
466       return findBaseObject(CE->getOperand(0), Aliases);
467     default:
468       break;
469     }
470   }
471   return nullptr;
472 }
473 
474 const GlobalObject *GlobalIndirectSymbol::getBaseObject() const {
475   DenseSet<const GlobalAlias *> Aliases;
476   return findBaseObject(getOperand(0), Aliases);
477 }
478 
479 //===----------------------------------------------------------------------===//
480 // GlobalAlias Implementation
481 //===----------------------------------------------------------------------===//
482 
483 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
484                          const Twine &Name, Constant *Aliasee,
485                          Module *ParentModule)
486     : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
487                            Aliasee) {
488   if (ParentModule)
489     ParentModule->getAliasList().push_back(this);
490 }
491 
492 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
493                                  LinkageTypes Link, const Twine &Name,
494                                  Constant *Aliasee, Module *ParentModule) {
495   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
496 }
497 
498 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
499                                  LinkageTypes Linkage, const Twine &Name,
500                                  Module *Parent) {
501   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
502 }
503 
504 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
505                                  LinkageTypes Linkage, const Twine &Name,
506                                  GlobalValue *Aliasee) {
507   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
508 }
509 
510 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
511                                  GlobalValue *Aliasee) {
512   PointerType *PTy = Aliasee->getType();
513   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
514                 Aliasee);
515 }
516 
517 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
518   return create(Aliasee->getLinkage(), Name, Aliasee);
519 }
520 
521 void GlobalAlias::removeFromParent() {
522   getParent()->getAliasList().remove(getIterator());
523 }
524 
525 void GlobalAlias::eraseFromParent() {
526   getParent()->getAliasList().erase(getIterator());
527 }
528 
529 void GlobalAlias::setAliasee(Constant *Aliasee) {
530   assert((!Aliasee || Aliasee->getType() == getType()) &&
531          "Alias and aliasee types should match!");
532   setIndirectSymbol(Aliasee);
533 }
534 
535 //===----------------------------------------------------------------------===//
536 // GlobalIFunc Implementation
537 //===----------------------------------------------------------------------===//
538 
539 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
540                          const Twine &Name, Constant *Resolver,
541                          Module *ParentModule)
542     : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
543                            Resolver) {
544   if (ParentModule)
545     ParentModule->getIFuncList().push_back(this);
546 }
547 
548 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
549                                  LinkageTypes Link, const Twine &Name,
550                                  Constant *Resolver, Module *ParentModule) {
551   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
552 }
553 
554 void GlobalIFunc::removeFromParent() {
555   getParent()->getIFuncList().remove(getIterator());
556 }
557 
558 void GlobalIFunc::eraseFromParent() {
559   getParent()->getIFuncList().erase(getIterator());
560 }
561