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(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   MetadataMap.erase(this);
240   HasSanitizerMetadata = false;
241 }
242 
243 StringRef GlobalObject::getSectionImpl() const {
244   assert(hasSection());
245   return getContext().pImpl->GlobalObjectSections[this];
246 }
247 
248 void GlobalObject::setSection(StringRef S) {
249   // Do nothing if we're clearing the section and it is already empty.
250   if (!hasSection() && S.empty())
251     return;
252 
253   // Get or create a stable section name string and put it in the table in the
254   // context.
255   if (!S.empty())
256     S = getContext().pImpl->Saver.save(S);
257   getContext().pImpl->GlobalObjectSections[this] = S;
258 
259   // Update the HasSectionHashEntryBit. Setting the section to the empty string
260   // means this global no longer has a section.
261   setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
262 }
263 
264 bool GlobalValue::isDeclaration() const {
265   // Globals are definitions if they have an initializer.
266   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
267     return GV->getNumOperands() == 0;
268 
269   // Functions are definitions if they have a body.
270   if (const Function *F = dyn_cast<Function>(this))
271     return F->empty() && !F->isMaterializable();
272 
273   // Aliases and ifuncs are always definitions.
274   assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
275   return false;
276 }
277 
278 bool GlobalObject::canIncreaseAlignment() const {
279   // Firstly, can only increase the alignment of a global if it
280   // is a strong definition.
281   if (!isStrongDefinitionForLinker())
282     return false;
283 
284   // It also has to either not have a section defined, or, not have
285   // alignment specified. (If it is assigned a section, the global
286   // could be densely packed with other objects in the section, and
287   // increasing the alignment could cause padding issues.)
288   if (hasSection() && getAlign())
289     return false;
290 
291   // On ELF platforms, we're further restricted in that we can't
292   // increase the alignment of any variable which might be emitted
293   // into a shared library, and which is exported. If the main
294   // executable accesses a variable found in a shared-lib, the main
295   // exe actually allocates memory for and exports the symbol ITSELF,
296   // overriding the symbol found in the library. That is, at link
297   // time, the observed alignment of the variable is copied into the
298   // executable binary. (A COPY relocation is also generated, to copy
299   // the initial data from the shadowed variable in the shared-lib
300   // into the location in the main binary, before running code.)
301   //
302   // And thus, even though you might think you are defining the
303   // global, and allocating the memory for the global in your object
304   // file, and thus should be able to set the alignment arbitrarily,
305   // that's not actually true. Doing so can cause an ABI breakage; an
306   // executable might have already been built with the previous
307   // alignment of the variable, and then assuming an increased
308   // alignment will be incorrect.
309 
310   // Conservatively assume ELF if there's no parent pointer.
311   bool isELF =
312       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
313   if (isELF && !isDSOLocal())
314     return false;
315 
316   return true;
317 }
318 
319 template <typename Operation>
320 static const GlobalObject *
321 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases,
322                const Operation &Op) {
323   if (auto *GO = dyn_cast<GlobalObject>(C)) {
324     Op(*GO);
325     return GO;
326   }
327   if (auto *GA = dyn_cast<GlobalAlias>(C)) {
328     Op(*GA);
329     if (Aliases.insert(GA).second)
330       return findBaseObject(GA->getOperand(0), Aliases, Op);
331   }
332   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
333     switch (CE->getOpcode()) {
334     case Instruction::Add: {
335       auto *LHS = findBaseObject(CE->getOperand(0), Aliases, Op);
336       auto *RHS = findBaseObject(CE->getOperand(1), Aliases, Op);
337       if (LHS && RHS)
338         return nullptr;
339       return LHS ? LHS : RHS;
340     }
341     case Instruction::Sub: {
342       if (findBaseObject(CE->getOperand(1), Aliases, Op))
343         return nullptr;
344       return findBaseObject(CE->getOperand(0), Aliases, Op);
345     }
346     case Instruction::IntToPtr:
347     case Instruction::PtrToInt:
348     case Instruction::BitCast:
349     case Instruction::GetElementPtr:
350       return findBaseObject(CE->getOperand(0), Aliases, Op);
351     default:
352       break;
353     }
354   }
355   return nullptr;
356 }
357 
358 const GlobalObject *GlobalValue::getAliaseeObject() const {
359   DenseSet<const GlobalAlias *> Aliases;
360   return findBaseObject(this, Aliases, [](const GlobalValue &) {});
361 }
362 
363 bool GlobalValue::isAbsoluteSymbolRef() const {
364   auto *GO = dyn_cast<GlobalObject>(this);
365   if (!GO)
366     return false;
367 
368   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
369 }
370 
371 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
372   auto *GO = dyn_cast<GlobalObject>(this);
373   if (!GO)
374     return None;
375 
376   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
377   if (!MD)
378     return None;
379 
380   return getConstantRangeFromMetadata(*MD);
381 }
382 
383 bool GlobalValue::canBeOmittedFromSymbolTable() const {
384   if (!hasLinkOnceODRLinkage())
385     return false;
386 
387   // We assume that anyone who sets global unnamed_addr on a non-constant
388   // knows what they're doing.
389   if (hasGlobalUnnamedAddr())
390     return true;
391 
392   // If it is a non constant variable, it needs to be uniqued across shared
393   // objects.
394   if (auto *Var = dyn_cast<GlobalVariable>(this))
395     if (!Var->isConstant())
396       return false;
397 
398   return hasAtLeastLocalUnnamedAddr();
399 }
400 
401 //===----------------------------------------------------------------------===//
402 // GlobalVariable Implementation
403 //===----------------------------------------------------------------------===//
404 
405 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
406                                Constant *InitVal, const Twine &Name,
407                                ThreadLocalMode TLMode, unsigned AddressSpace,
408                                bool isExternallyInitialized)
409     : GlobalObject(Ty, Value::GlobalVariableVal,
410                    OperandTraits<GlobalVariable>::op_begin(this),
411                    InitVal != nullptr, Link, Name, AddressSpace),
412       isConstantGlobal(constant),
413       isExternallyInitializedConstant(isExternallyInitialized) {
414   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
415          "invalid type for global variable");
416   setThreadLocalMode(TLMode);
417   if (InitVal) {
418     assert(InitVal->getType() == Ty &&
419            "Initializer should be the same type as the GlobalVariable!");
420     Op<0>() = InitVal;
421   }
422 }
423 
424 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
425                                LinkageTypes Link, Constant *InitVal,
426                                const Twine &Name, GlobalVariable *Before,
427                                ThreadLocalMode TLMode,
428                                Optional<unsigned> AddressSpace,
429                                bool isExternallyInitialized)
430     : GlobalObject(Ty, Value::GlobalVariableVal,
431                    OperandTraits<GlobalVariable>::op_begin(this),
432                    InitVal != nullptr, Link, Name,
433                    AddressSpace
434                        ? *AddressSpace
435                        : M.getDataLayout().getDefaultGlobalsAddressSpace()),
436       isConstantGlobal(constant),
437       isExternallyInitializedConstant(isExternallyInitialized) {
438   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
439          "invalid type for global variable");
440   setThreadLocalMode(TLMode);
441   if (InitVal) {
442     assert(InitVal->getType() == Ty &&
443            "Initializer should be the same type as the GlobalVariable!");
444     Op<0>() = InitVal;
445   }
446 
447   if (Before)
448     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
449   else
450     M.getGlobalList().push_back(this);
451 }
452 
453 void GlobalVariable::removeFromParent() {
454   getParent()->getGlobalList().remove(getIterator());
455 }
456 
457 void GlobalVariable::eraseFromParent() {
458   getParent()->getGlobalList().erase(getIterator());
459 }
460 
461 void GlobalVariable::setInitializer(Constant *InitVal) {
462   if (!InitVal) {
463     if (hasInitializer()) {
464       // Note, the num operands is used to compute the offset of the operand, so
465       // the order here matters.  Clearing the operand then clearing the num
466       // operands ensures we have the correct offset to the operand.
467       Op<0>().set(nullptr);
468       setGlobalVariableNumOperands(0);
469     }
470   } else {
471     assert(InitVal->getType() == getValueType() &&
472            "Initializer type must match GlobalVariable type");
473     // Note, the num operands is used to compute the offset of the operand, so
474     // the order here matters.  We need to set num operands to 1 first so that
475     // we get the correct offset to the first operand when we set it.
476     if (!hasInitializer())
477       setGlobalVariableNumOperands(1);
478     Op<0>().set(InitVal);
479   }
480 }
481 
482 /// Copy all additional attributes (those not needed to create a GlobalVariable)
483 /// from the GlobalVariable Src to this one.
484 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
485   GlobalObject::copyAttributesFrom(Src);
486   setExternallyInitialized(Src->isExternallyInitialized());
487   setAttributes(Src->getAttributes());
488 }
489 
490 void GlobalVariable::dropAllReferences() {
491   User::dropAllReferences();
492   clearMetadata();
493 }
494 
495 //===----------------------------------------------------------------------===//
496 // GlobalAlias Implementation
497 //===----------------------------------------------------------------------===//
498 
499 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
500                          const Twine &Name, Constant *Aliasee,
501                          Module *ParentModule)
502     : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
503                   AddressSpace) {
504   setAliasee(Aliasee);
505   if (ParentModule)
506     ParentModule->getAliasList().push_back(this);
507 }
508 
509 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
510                                  LinkageTypes Link, const Twine &Name,
511                                  Constant *Aliasee, Module *ParentModule) {
512   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
513 }
514 
515 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
516                                  LinkageTypes Linkage, const Twine &Name,
517                                  Module *Parent) {
518   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
519 }
520 
521 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
522                                  LinkageTypes Linkage, const Twine &Name,
523                                  GlobalValue *Aliasee) {
524   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
525 }
526 
527 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
528                                  GlobalValue *Aliasee) {
529   return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
530                 Aliasee);
531 }
532 
533 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
534   return create(Aliasee->getLinkage(), Name, Aliasee);
535 }
536 
537 void GlobalAlias::removeFromParent() {
538   getParent()->getAliasList().remove(getIterator());
539 }
540 
541 void GlobalAlias::eraseFromParent() {
542   getParent()->getAliasList().erase(getIterator());
543 }
544 
545 void GlobalAlias::setAliasee(Constant *Aliasee) {
546   assert((!Aliasee || Aliasee->getType() == getType()) &&
547          "Alias and aliasee types should match!");
548   Op<0>().set(Aliasee);
549 }
550 
551 const GlobalObject *GlobalAlias::getAliaseeObject() const {
552   DenseSet<const GlobalAlias *> Aliases;
553   return findBaseObject(getOperand(0), Aliases, [](const GlobalValue &) {});
554 }
555 
556 //===----------------------------------------------------------------------===//
557 // GlobalIFunc Implementation
558 //===----------------------------------------------------------------------===//
559 
560 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
561                          const Twine &Name, Constant *Resolver,
562                          Module *ParentModule)
563     : GlobalObject(Ty, Value::GlobalIFuncVal, &Op<0>(), 1, Link, Name,
564                    AddressSpace) {
565   setResolver(Resolver);
566   if (ParentModule)
567     ParentModule->getIFuncList().push_back(this);
568 }
569 
570 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
571                                  LinkageTypes Link, const Twine &Name,
572                                  Constant *Resolver, Module *ParentModule) {
573   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
574 }
575 
576 void GlobalIFunc::removeFromParent() {
577   getParent()->getIFuncList().remove(getIterator());
578 }
579 
580 void GlobalIFunc::eraseFromParent() {
581   getParent()->getIFuncList().erase(getIterator());
582 }
583 
584 const Function *GlobalIFunc::getResolverFunction() const {
585   DenseSet<const GlobalAlias *> Aliases;
586   return dyn_cast<Function>(
587       findBaseObject(getResolver(), Aliases, [](const GlobalValue &) {}));
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