1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the GlobalValue & GlobalVariable classes for the IR
13 //===----------------------------------------------------------------------===//
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/ConstantRange.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
30 //===----------------------------------------------------------------------===//
32 //===----------------------------------------------------------------------===//
34 // GlobalValue should be a Constant, plus a type, a module, some flags, and an
35 // intrinsic ID. Add an assert to prevent people from accidentally growing
36 // GlobalValue while adding flags.
37 static_assert(sizeof(GlobalValue) ==
38 sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
39 "unexpected GlobalValue size growth");
41 // GlobalObject adds a comdat.
42 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
43 "unexpected GlobalObject size growth");
45 bool GlobalValue::isMaterializable() const {
46 if (const Function *F = dyn_cast<Function>(this))
47 return F->isMaterializable();
50 Error GlobalValue::materialize() {
51 return getParent()->materialize(this);
54 /// Override destroyConstantImpl to make sure it doesn't get called on
55 /// GlobalValue's because they shouldn't be treated like other constants.
56 void GlobalValue::destroyConstantImpl() {
57 llvm_unreachable("You can't GV->destroyConstantImpl()!");
60 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
61 llvm_unreachable("Unsupported class for handleOperandChange()!");
64 /// copyAttributesFrom - copy all additional attributes (those not needed to
65 /// create a GlobalValue) from the GlobalValue Src to this one.
66 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
67 setVisibility(Src->getVisibility());
68 setUnnamedAddr(Src->getUnnamedAddr());
69 setDLLStorageClass(Src->getDLLStorageClass());
72 void GlobalValue::removeFromParent() {
73 switch (getValueID()) {
74 #define HANDLE_GLOBAL_VALUE(NAME) \
75 case Value::NAME##Val: \
76 return static_cast<NAME *>(this)->removeFromParent();
77 #include "llvm/IR/Value.def"
81 llvm_unreachable("not a global");
84 void GlobalValue::eraseFromParent() {
85 switch (getValueID()) {
86 #define HANDLE_GLOBAL_VALUE(NAME) \
87 case Value::NAME##Val: \
88 return static_cast<NAME *>(this)->eraseFromParent();
89 #include "llvm/IR/Value.def"
93 llvm_unreachable("not a global");
96 unsigned GlobalValue::getAlignment() const {
97 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
98 // In general we cannot compute this at the IR level, but we try.
99 if (const GlobalObject *GO = GA->getBaseObject())
100 return GO->getAlignment();
102 // FIXME: we should also be able to handle:
103 // Alias = Global + Offset
107 return cast<GlobalObject>(this)->getAlignment();
110 void GlobalObject::setAlignment(unsigned Align) {
111 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
112 assert(Align <= MaximumAlignment &&
113 "Alignment is greater than MaximumAlignment!");
114 unsigned AlignmentData = Log2_32(Align) + 1;
115 unsigned OldData = getGlobalValueSubClassData();
116 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
117 assert(getAlignment() == Align && "Alignment representation error!");
120 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
121 GlobalValue::copyAttributesFrom(Src);
122 setAlignment(Src->getAlignment());
123 setSection(Src->getSection());
126 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
127 GlobalValue::LinkageTypes Linkage,
128 StringRef FileName) {
130 // Value names may be prefixed with a binary '1' to indicate
131 // that the backend should not modify the symbols due to any platform
132 // naming convention. Do not include that '1' in the PGO profile name.
134 Name = Name.substr(1);
136 std::string NewName = Name;
137 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
138 // For local symbols, prepend the main file name to distinguish them.
139 // Do not include the full path in the file name since there's no guarantee
140 // that it will stay the same, e.g., if the files are checked out from
141 // version control in different locations.
142 if (FileName.empty())
143 NewName = NewName.insert(0, "<unknown>:");
145 NewName = NewName.insert(0, FileName.str() + ":");
150 std::string GlobalValue::getGlobalIdentifier() const {
151 return getGlobalIdentifier(getName(), getLinkage(),
152 getParent()->getSourceFileName());
155 StringRef GlobalValue::getSection() const {
156 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
157 // In general we cannot compute this at the IR level, but we try.
158 if (const GlobalObject *GO = GA->getBaseObject())
159 return GO->getSection();
162 return cast<GlobalObject>(this)->getSection();
165 const Comdat *GlobalValue::getComdat() 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->getBaseObject())
169 return const_cast<GlobalObject *>(GO)->getComdat();
172 // ifunc and its resolver are separate things so don't use resolver comdat.
173 if (isa<GlobalIFunc>(this))
175 return cast<GlobalObject>(this)->getComdat();
178 StringRef GlobalObject::getSectionImpl() const {
179 assert(hasSection());
180 return getContext().pImpl->GlobalObjectSections[this];
183 void GlobalObject::setSection(StringRef S) {
184 // Do nothing if we're clearing the section and it is already empty.
185 if (!hasSection() && S.empty())
188 // Get or create a stable section name string and put it in the table in the
191 S = getContext().pImpl->SectionStrings.insert(S).first->first();
193 getContext().pImpl->GlobalObjectSections[this] = S;
195 // Update the HasSectionHashEntryBit. Setting the section to the empty string
196 // means this global no longer has a section.
197 setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
200 bool GlobalValue::isDeclaration() const {
201 // Globals are definitions if they have an initializer.
202 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
203 return GV->getNumOperands() == 0;
205 // Functions are definitions if they have a body.
206 if (const Function *F = dyn_cast<Function>(this))
207 return F->empty() && !F->isMaterializable();
209 // Aliases and ifuncs are always definitions.
210 assert(isa<GlobalIndirectSymbol>(this));
214 bool GlobalValue::canIncreaseAlignment() const {
215 // Firstly, can only increase the alignment of a global if it
216 // is a strong definition.
217 if (!isStrongDefinitionForLinker())
220 // It also has to either not have a section defined, or, not have
221 // alignment specified. (If it is assigned a section, the global
222 // could be densely packed with other objects in the section, and
223 // increasing the alignment could cause padding issues.)
224 if (hasSection() && getAlignment() > 0)
227 // On ELF platforms, we're further restricted in that we can't
228 // increase the alignment of any variable which might be emitted
229 // into a shared library, and which is exported. If the main
230 // executable accesses a variable found in a shared-lib, the main
231 // exe actually allocates memory for and exports the symbol ITSELF,
232 // overriding the symbol found in the library. That is, at link
233 // time, the observed alignment of the variable is copied into the
234 // executable binary. (A COPY relocation is also generated, to copy
235 // the initial data from the shadowed variable in the shared-lib
236 // into the location in the main binary, before running code.)
238 // And thus, even though you might think you are defining the
239 // global, and allocating the memory for the global in your object
240 // file, and thus should be able to set the alignment arbitrarily,
241 // that's not actually true. Doing so can cause an ABI breakage; an
242 // executable might have already been built with the previous
243 // alignment of the variable, and then assuming an increased
244 // alignment will be incorrect.
246 // Conservatively assume ELF if there's no parent pointer.
248 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
249 if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
255 const GlobalObject *GlobalValue::getBaseObject() const {
256 if (auto *GO = dyn_cast<GlobalObject>(this))
258 if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
259 return GA->getBaseObject();
263 bool GlobalValue::isAbsoluteSymbolRef() const {
264 auto *GO = dyn_cast<GlobalObject>(this);
268 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
271 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
272 auto *GO = dyn_cast<GlobalObject>(this);
276 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
280 return getConstantRangeFromMetadata(*MD);
283 //===----------------------------------------------------------------------===//
284 // GlobalVariable Implementation
285 //===----------------------------------------------------------------------===//
287 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
288 Constant *InitVal, const Twine &Name,
289 ThreadLocalMode TLMode, unsigned AddressSpace,
290 bool isExternallyInitialized)
291 : GlobalObject(Ty, Value::GlobalVariableVal,
292 OperandTraits<GlobalVariable>::op_begin(this),
293 InitVal != nullptr, Link, Name, AddressSpace),
294 isConstantGlobal(constant),
295 isExternallyInitializedConstant(isExternallyInitialized) {
296 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
297 "invalid type for global variable");
298 setThreadLocalMode(TLMode);
300 assert(InitVal->getType() == Ty &&
301 "Initializer should be the same type as the GlobalVariable!");
306 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
307 LinkageTypes Link, Constant *InitVal,
308 const Twine &Name, GlobalVariable *Before,
309 ThreadLocalMode TLMode, unsigned AddressSpace,
310 bool isExternallyInitialized)
311 : GlobalObject(Ty, Value::GlobalVariableVal,
312 OperandTraits<GlobalVariable>::op_begin(this),
313 InitVal != nullptr, Link, Name, AddressSpace),
314 isConstantGlobal(constant),
315 isExternallyInitializedConstant(isExternallyInitialized) {
316 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
317 "invalid type for global variable");
318 setThreadLocalMode(TLMode);
320 assert(InitVal->getType() == Ty &&
321 "Initializer should be the same type as the GlobalVariable!");
326 Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
328 M.getGlobalList().push_back(this);
331 void GlobalVariable::removeFromParent() {
332 getParent()->getGlobalList().remove(getIterator());
335 void GlobalVariable::eraseFromParent() {
336 getParent()->getGlobalList().erase(getIterator());
339 void GlobalVariable::setInitializer(Constant *InitVal) {
341 if (hasInitializer()) {
342 // Note, the num operands is used to compute the offset of the operand, so
343 // the order here matters. Clearing the operand then clearing the num
344 // operands ensures we have the correct offset to the operand.
345 Op<0>().set(nullptr);
346 setGlobalVariableNumOperands(0);
349 assert(InitVal->getType() == getValueType() &&
350 "Initializer type must match GlobalVariable type");
351 // Note, the num operands is used to compute the offset of the operand, so
352 // the order here matters. We need to set num operands to 1 first so that
353 // we get the correct offset to the first operand when we set it.
354 if (!hasInitializer())
355 setGlobalVariableNumOperands(1);
356 Op<0>().set(InitVal);
360 /// Copy all additional attributes (those not needed to create a GlobalVariable)
361 /// from the GlobalVariable Src to this one.
362 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
363 GlobalObject::copyAttributesFrom(Src);
364 setThreadLocalMode(Src->getThreadLocalMode());
365 setExternallyInitialized(Src->isExternallyInitialized());
366 setAttributes(Src->getAttributes());
369 void GlobalVariable::dropAllReferences() {
370 User::dropAllReferences();
374 //===----------------------------------------------------------------------===//
375 // GlobalIndirectSymbol Implementation
376 //===----------------------------------------------------------------------===//
378 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
379 unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
381 : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
386 //===----------------------------------------------------------------------===//
387 // GlobalAlias Implementation
388 //===----------------------------------------------------------------------===//
390 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
391 const Twine &Name, Constant *Aliasee,
392 Module *ParentModule)
393 : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
396 ParentModule->getAliasList().push_back(this);
399 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
400 LinkageTypes Link, const Twine &Name,
401 Constant *Aliasee, Module *ParentModule) {
402 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
405 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
406 LinkageTypes Linkage, const Twine &Name,
408 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
411 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
412 LinkageTypes Linkage, const Twine &Name,
413 GlobalValue *Aliasee) {
414 return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
417 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
418 GlobalValue *Aliasee) {
419 PointerType *PTy = Aliasee->getType();
420 return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
424 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
425 return create(Aliasee->getLinkage(), Name, Aliasee);
428 void GlobalAlias::removeFromParent() {
429 getParent()->getAliasList().remove(getIterator());
432 void GlobalAlias::eraseFromParent() {
433 getParent()->getAliasList().erase(getIterator());
436 void GlobalAlias::setAliasee(Constant *Aliasee) {
437 assert((!Aliasee || Aliasee->getType() == getType()) &&
438 "Alias and aliasee types should match!");
439 setIndirectSymbol(Aliasee);
442 //===----------------------------------------------------------------------===//
443 // GlobalIFunc Implementation
444 //===----------------------------------------------------------------------===//
446 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
447 const Twine &Name, Constant *Resolver,
448 Module *ParentModule)
449 : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
452 ParentModule->getIFuncList().push_back(this);
455 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
456 LinkageTypes Link, const Twine &Name,
457 Constant *Resolver, Module *ParentModule) {
458 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
461 void GlobalIFunc::removeFromParent() {
462 getParent()->getIFuncList().remove(getIterator());
465 void GlobalIFunc::eraseFromParent() {
466 getParent()->getIFuncList().erase(getIterator());