]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/lib/IR/Globals.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / lib / IR / Globals.cpp
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 unsigned GlobalValue::getAlignment() const {
98   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
99     // In general we cannot compute this at the IR level, but we try.
100     if (const GlobalObject *GO = GA->getBaseObject())
101       return GO->getAlignment();
102
103     // FIXME: we should also be able to handle:
104     // Alias = Global + Offset
105     // Alias = Absolute
106     return 0;
107   }
108   return cast<GlobalObject>(this)->getAlignment();
109 }
110
111 unsigned GlobalValue::getAddressSpace() const {
112   PointerType *PtrTy = getType();
113   return PtrTy->getAddressSpace();
114 }
115
116 void GlobalObject::setAlignment(unsigned Align) {
117   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
118   assert(Align <= MaximumAlignment &&
119          "Alignment is greater than MaximumAlignment!");
120   unsigned AlignmentData = Log2_32(Align) + 1;
121   unsigned OldData = getGlobalValueSubClassData();
122   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
123   assert(getAlignment() == Align && "Alignment representation error!");
124 }
125
126 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
127   GlobalValue::copyAttributesFrom(Src);
128   setAlignment(Src->getAlignment());
129   setSection(Src->getSection());
130 }
131
132 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
133                                              GlobalValue::LinkageTypes Linkage,
134                                              StringRef FileName) {
135
136   // Value names may be prefixed with a binary '1' to indicate
137   // that the backend should not modify the symbols due to any platform
138   // naming convention. Do not include that '1' in the PGO profile name.
139   if (Name[0] == '\1')
140     Name = Name.substr(1);
141
142   std::string NewName = Name;
143   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
144     // For local symbols, prepend the main file name to distinguish them.
145     // Do not include the full path in the file name since there's no guarantee
146     // that it will stay the same, e.g., if the files are checked out from
147     // version control in different locations.
148     if (FileName.empty())
149       NewName = NewName.insert(0, "<unknown>:");
150     else
151       NewName = NewName.insert(0, FileName.str() + ":");
152   }
153   return NewName;
154 }
155
156 std::string GlobalValue::getGlobalIdentifier() const {
157   return getGlobalIdentifier(getName(), getLinkage(),
158                              getParent()->getSourceFileName());
159 }
160
161 StringRef GlobalValue::getSection() const {
162   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
163     // In general we cannot compute this at the IR level, but we try.
164     if (const GlobalObject *GO = GA->getBaseObject())
165       return GO->getSection();
166     return "";
167   }
168   return cast<GlobalObject>(this)->getSection();
169 }
170
171 const Comdat *GlobalValue::getComdat() 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->getBaseObject())
175       return const_cast<GlobalObject *>(GO)->getComdat();
176     return nullptr;
177   }
178   // ifunc and its resolver are separate things so don't use resolver comdat.
179   if (isa<GlobalIFunc>(this))
180     return nullptr;
181   return cast<GlobalObject>(this)->getComdat();
182 }
183
184 StringRef GlobalValue::getPartition() const {
185   if (!hasPartition())
186     return "";
187   return getContext().pImpl->GlobalValuePartitions[this];
188 }
189
190 void GlobalValue::setPartition(StringRef S) {
191   // Do nothing if we're clearing the partition and it is already empty.
192   if (!hasPartition() && S.empty())
193     return;
194
195   // Get or create a stable partition name string and put it in the table in the
196   // context.
197   if (!S.empty())
198     S = getContext().pImpl->Saver.save(S);
199   getContext().pImpl->GlobalValuePartitions[this] = S;
200
201   // Update the HasPartition field. Setting the partition to the empty string
202   // means this global no longer has a partition.
203   HasPartition = !S.empty();
204 }
205
206 StringRef GlobalObject::getSectionImpl() const {
207   assert(hasSection());
208   return getContext().pImpl->GlobalObjectSections[this];
209 }
210
211 void GlobalObject::setSection(StringRef S) {
212   // Do nothing if we're clearing the section and it is already empty.
213   if (!hasSection() && S.empty())
214     return;
215
216   // Get or create a stable section name string and put it in the table in the
217   // context.
218   if (!S.empty())
219     S = getContext().pImpl->Saver.save(S);
220   getContext().pImpl->GlobalObjectSections[this] = S;
221
222   // Update the HasSectionHashEntryBit. Setting the section to the empty string
223   // means this global no longer has a section.
224   setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
225 }
226
227 bool GlobalValue::isDeclaration() const {
228   // Globals are definitions if they have an initializer.
229   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
230     return GV->getNumOperands() == 0;
231
232   // Functions are definitions if they have a body.
233   if (const Function *F = dyn_cast<Function>(this))
234     return F->empty() && !F->isMaterializable();
235
236   // Aliases and ifuncs are always definitions.
237   assert(isa<GlobalIndirectSymbol>(this));
238   return false;
239 }
240
241 bool GlobalValue::canIncreaseAlignment() const {
242   // Firstly, can only increase the alignment of a global if it
243   // is a strong definition.
244   if (!isStrongDefinitionForLinker())
245     return false;
246
247   // It also has to either not have a section defined, or, not have
248   // alignment specified. (If it is assigned a section, the global
249   // could be densely packed with other objects in the section, and
250   // increasing the alignment could cause padding issues.)
251   if (hasSection() && getAlignment() > 0)
252     return false;
253
254   // On ELF platforms, we're further restricted in that we can't
255   // increase the alignment of any variable which might be emitted
256   // into a shared library, and which is exported. If the main
257   // executable accesses a variable found in a shared-lib, the main
258   // exe actually allocates memory for and exports the symbol ITSELF,
259   // overriding the symbol found in the library. That is, at link
260   // time, the observed alignment of the variable is copied into the
261   // executable binary. (A COPY relocation is also generated, to copy
262   // the initial data from the shadowed variable in the shared-lib
263   // into the location in the main binary, before running code.)
264   //
265   // And thus, even though you might think you are defining the
266   // global, and allocating the memory for the global in your object
267   // file, and thus should be able to set the alignment arbitrarily,
268   // that's not actually true. Doing so can cause an ABI breakage; an
269   // executable might have already been built with the previous
270   // alignment of the variable, and then assuming an increased
271   // alignment will be incorrect.
272
273   // Conservatively assume ELF if there's no parent pointer.
274   bool isELF =
275       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
276   if (isELF && !isDSOLocal())
277     return false;
278
279   return true;
280 }
281
282 const GlobalObject *GlobalValue::getBaseObject() const {
283   if (auto *GO = dyn_cast<GlobalObject>(this))
284     return GO;
285   if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
286     return GA->getBaseObject();
287   return nullptr;
288 }
289
290 bool GlobalValue::isAbsoluteSymbolRef() const {
291   auto *GO = dyn_cast<GlobalObject>(this);
292   if (!GO)
293     return false;
294
295   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
296 }
297
298 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
299   auto *GO = dyn_cast<GlobalObject>(this);
300   if (!GO)
301     return None;
302
303   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
304   if (!MD)
305     return None;
306
307   return getConstantRangeFromMetadata(*MD);
308 }
309
310 bool GlobalValue::canBeOmittedFromSymbolTable() const {
311   if (!hasLinkOnceODRLinkage())
312     return false;
313
314   // We assume that anyone who sets global unnamed_addr on a non-constant
315   // knows what they're doing.
316   if (hasGlobalUnnamedAddr())
317     return true;
318
319   // If it is a non constant variable, it needs to be uniqued across shared
320   // objects.
321   if (auto *Var = dyn_cast<GlobalVariable>(this))
322     if (!Var->isConstant())
323       return false;
324
325   return hasAtLeastLocalUnnamedAddr();
326 }
327
328 //===----------------------------------------------------------------------===//
329 // GlobalVariable Implementation
330 //===----------------------------------------------------------------------===//
331
332 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
333                                Constant *InitVal, const Twine &Name,
334                                ThreadLocalMode TLMode, unsigned AddressSpace,
335                                bool isExternallyInitialized)
336     : GlobalObject(Ty, Value::GlobalVariableVal,
337                    OperandTraits<GlobalVariable>::op_begin(this),
338                    InitVal != nullptr, Link, Name, AddressSpace),
339       isConstantGlobal(constant),
340       isExternallyInitializedConstant(isExternallyInitialized) {
341   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
342          "invalid type for global variable");
343   setThreadLocalMode(TLMode);
344   if (InitVal) {
345     assert(InitVal->getType() == Ty &&
346            "Initializer should be the same type as the GlobalVariable!");
347     Op<0>() = InitVal;
348   }
349 }
350
351 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
352                                LinkageTypes Link, Constant *InitVal,
353                                const Twine &Name, GlobalVariable *Before,
354                                ThreadLocalMode TLMode, unsigned AddressSpace,
355                                bool isExternallyInitialized)
356     : GlobalObject(Ty, Value::GlobalVariableVal,
357                    OperandTraits<GlobalVariable>::op_begin(this),
358                    InitVal != nullptr, Link, Name, AddressSpace),
359       isConstantGlobal(constant),
360       isExternallyInitializedConstant(isExternallyInitialized) {
361   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
362          "invalid type for global variable");
363   setThreadLocalMode(TLMode);
364   if (InitVal) {
365     assert(InitVal->getType() == Ty &&
366            "Initializer should be the same type as the GlobalVariable!");
367     Op<0>() = InitVal;
368   }
369
370   if (Before)
371     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
372   else
373     M.getGlobalList().push_back(this);
374 }
375
376 void GlobalVariable::removeFromParent() {
377   getParent()->getGlobalList().remove(getIterator());
378 }
379
380 void GlobalVariable::eraseFromParent() {
381   getParent()->getGlobalList().erase(getIterator());
382 }
383
384 void GlobalVariable::setInitializer(Constant *InitVal) {
385   if (!InitVal) {
386     if (hasInitializer()) {
387       // Note, the num operands is used to compute the offset of the operand, so
388       // the order here matters.  Clearing the operand then clearing the num
389       // operands ensures we have the correct offset to the operand.
390       Op<0>().set(nullptr);
391       setGlobalVariableNumOperands(0);
392     }
393   } else {
394     assert(InitVal->getType() == getValueType() &&
395            "Initializer type must match GlobalVariable type");
396     // Note, the num operands is used to compute the offset of the operand, so
397     // the order here matters.  We need to set num operands to 1 first so that
398     // we get the correct offset to the first operand when we set it.
399     if (!hasInitializer())
400       setGlobalVariableNumOperands(1);
401     Op<0>().set(InitVal);
402   }
403 }
404
405 /// Copy all additional attributes (those not needed to create a GlobalVariable)
406 /// from the GlobalVariable Src to this one.
407 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
408   GlobalObject::copyAttributesFrom(Src);
409   setThreadLocalMode(Src->getThreadLocalMode());
410   setExternallyInitialized(Src->isExternallyInitialized());
411   setAttributes(Src->getAttributes());
412 }
413
414 void GlobalVariable::dropAllReferences() {
415   User::dropAllReferences();
416   clearMetadata();
417 }
418
419 //===----------------------------------------------------------------------===//
420 // GlobalIndirectSymbol Implementation
421 //===----------------------------------------------------------------------===//
422
423 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
424     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
425     Constant *Symbol)
426     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
427     Op<0>() = Symbol;
428 }
429
430
431 //===----------------------------------------------------------------------===//
432 // GlobalAlias Implementation
433 //===----------------------------------------------------------------------===//
434
435 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
436                          const Twine &Name, Constant *Aliasee,
437                          Module *ParentModule)
438     : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
439                            Aliasee) {
440   if (ParentModule)
441     ParentModule->getAliasList().push_back(this);
442 }
443
444 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
445                                  LinkageTypes Link, const Twine &Name,
446                                  Constant *Aliasee, Module *ParentModule) {
447   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
448 }
449
450 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
451                                  LinkageTypes Linkage, const Twine &Name,
452                                  Module *Parent) {
453   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
454 }
455
456 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
457                                  LinkageTypes Linkage, const Twine &Name,
458                                  GlobalValue *Aliasee) {
459   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
460 }
461
462 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
463                                  GlobalValue *Aliasee) {
464   PointerType *PTy = Aliasee->getType();
465   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
466                 Aliasee);
467 }
468
469 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
470   return create(Aliasee->getLinkage(), Name, Aliasee);
471 }
472
473 void GlobalAlias::removeFromParent() {
474   getParent()->getAliasList().remove(getIterator());
475 }
476
477 void GlobalAlias::eraseFromParent() {
478   getParent()->getAliasList().erase(getIterator());
479 }
480
481 void GlobalAlias::setAliasee(Constant *Aliasee) {
482   assert((!Aliasee || Aliasee->getType() == getType()) &&
483          "Alias and aliasee types should match!");
484   setIndirectSymbol(Aliasee);
485 }
486
487 //===----------------------------------------------------------------------===//
488 // GlobalIFunc Implementation
489 //===----------------------------------------------------------------------===//
490
491 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
492                          const Twine &Name, Constant *Resolver,
493                          Module *ParentModule)
494     : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
495                            Resolver) {
496   if (ParentModule)
497     ParentModule->getIFuncList().push_back(this);
498 }
499
500 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
501                                  LinkageTypes Link, const Twine &Name,
502                                  Constant *Resolver, Module *ParentModule) {
503   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
504 }
505
506 void GlobalIFunc::removeFromParent() {
507   getParent()->getIFuncList().remove(getIterator());
508 }
509
510 void GlobalIFunc::eraseFromParent() {
511   getParent()->getIFuncList().erase(getIterator());
512 }