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());
70 setDSOLocal(Src->isDSOLocal());
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"
82 llvm_unreachable("not a global");
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"
94 llvm_unreachable("not a global");
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();
103 // FIXME: we should also be able to handle:
104 // Alias = Global + Offset
108 return cast<GlobalObject>(this)->getAlignment();
111 void GlobalObject::setAlignment(unsigned Align) {
112 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
113 assert(Align <= MaximumAlignment &&
114 "Alignment is greater than MaximumAlignment!");
115 unsigned AlignmentData = Log2_32(Align) + 1;
116 unsigned OldData = getGlobalValueSubClassData();
117 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
118 assert(getAlignment() == Align && "Alignment representation error!");
121 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
122 GlobalValue::copyAttributesFrom(Src);
123 setAlignment(Src->getAlignment());
124 setSection(Src->getSection());
127 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
128 GlobalValue::LinkageTypes Linkage,
129 StringRef FileName) {
131 // Value names may be prefixed with a binary '1' to indicate
132 // that the backend should not modify the symbols due to any platform
133 // naming convention. Do not include that '1' in the PGO profile name.
135 Name = Name.substr(1);
137 std::string NewName = Name;
138 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
139 // For local symbols, prepend the main file name to distinguish them.
140 // Do not include the full path in the file name since there's no guarantee
141 // that it will stay the same, e.g., if the files are checked out from
142 // version control in different locations.
143 if (FileName.empty())
144 NewName = NewName.insert(0, "<unknown>:");
146 NewName = NewName.insert(0, FileName.str() + ":");
151 std::string GlobalValue::getGlobalIdentifier() const {
152 return getGlobalIdentifier(getName(), getLinkage(),
153 getParent()->getSourceFileName());
156 StringRef GlobalValue::getSection() const {
157 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
158 // In general we cannot compute this at the IR level, but we try.
159 if (const GlobalObject *GO = GA->getBaseObject())
160 return GO->getSection();
163 return cast<GlobalObject>(this)->getSection();
166 const Comdat *GlobalValue::getComdat() const {
167 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
168 // In general we cannot compute this at the IR level, but we try.
169 if (const GlobalObject *GO = GA->getBaseObject())
170 return const_cast<GlobalObject *>(GO)->getComdat();
173 // ifunc and its resolver are separate things so don't use resolver comdat.
174 if (isa<GlobalIFunc>(this))
176 return cast<GlobalObject>(this)->getComdat();
179 StringRef GlobalObject::getSectionImpl() const {
180 assert(hasSection());
181 return getContext().pImpl->GlobalObjectSections[this];
184 void GlobalObject::setSection(StringRef S) {
185 // Do nothing if we're clearing the section and it is already empty.
186 if (!hasSection() && S.empty())
189 // Get or create a stable section name string and put it in the table in the
192 S = getContext().pImpl->SectionStrings.insert(S).first->first();
194 getContext().pImpl->GlobalObjectSections[this] = S;
196 // Update the HasSectionHashEntryBit. Setting the section to the empty string
197 // means this global no longer has a section.
198 setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
201 bool GlobalValue::isDeclaration() const {
202 // Globals are definitions if they have an initializer.
203 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
204 return GV->getNumOperands() == 0;
206 // Functions are definitions if they have a body.
207 if (const Function *F = dyn_cast<Function>(this))
208 return F->empty() && !F->isMaterializable();
210 // Aliases and ifuncs are always definitions.
211 assert(isa<GlobalIndirectSymbol>(this));
215 bool GlobalValue::canIncreaseAlignment() const {
216 // Firstly, can only increase the alignment of a global if it
217 // is a strong definition.
218 if (!isStrongDefinitionForLinker())
221 // It also has to either not have a section defined, or, not have
222 // alignment specified. (If it is assigned a section, the global
223 // could be densely packed with other objects in the section, and
224 // increasing the alignment could cause padding issues.)
225 if (hasSection() && getAlignment() > 0)
228 // On ELF platforms, we're further restricted in that we can't
229 // increase the alignment of any variable which might be emitted
230 // into a shared library, and which is exported. If the main
231 // executable accesses a variable found in a shared-lib, the main
232 // exe actually allocates memory for and exports the symbol ITSELF,
233 // overriding the symbol found in the library. That is, at link
234 // time, the observed alignment of the variable is copied into the
235 // executable binary. (A COPY relocation is also generated, to copy
236 // the initial data from the shadowed variable in the shared-lib
237 // into the location in the main binary, before running code.)
239 // And thus, even though you might think you are defining the
240 // global, and allocating the memory for the global in your object
241 // file, and thus should be able to set the alignment arbitrarily,
242 // that's not actually true. Doing so can cause an ABI breakage; an
243 // executable might have already been built with the previous
244 // alignment of the variable, and then assuming an increased
245 // alignment will be incorrect.
247 // Conservatively assume ELF if there's no parent pointer.
249 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
250 if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
256 const GlobalObject *GlobalValue::getBaseObject() const {
257 if (auto *GO = dyn_cast<GlobalObject>(this))
259 if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
260 return GA->getBaseObject();
264 bool GlobalValue::isAbsoluteSymbolRef() const {
265 auto *GO = dyn_cast<GlobalObject>(this);
269 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
272 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
273 auto *GO = dyn_cast<GlobalObject>(this);
277 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
281 return getConstantRangeFromMetadata(*MD);
284 //===----------------------------------------------------------------------===//
285 // GlobalVariable Implementation
286 //===----------------------------------------------------------------------===//
288 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
289 Constant *InitVal, const Twine &Name,
290 ThreadLocalMode TLMode, unsigned AddressSpace,
291 bool isExternallyInitialized)
292 : GlobalObject(Ty, Value::GlobalVariableVal,
293 OperandTraits<GlobalVariable>::op_begin(this),
294 InitVal != nullptr, Link, Name, AddressSpace),
295 isConstantGlobal(constant),
296 isExternallyInitializedConstant(isExternallyInitialized) {
297 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
298 "invalid type for global variable");
299 setThreadLocalMode(TLMode);
301 assert(InitVal->getType() == Ty &&
302 "Initializer should be the same type as the GlobalVariable!");
307 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
308 LinkageTypes Link, Constant *InitVal,
309 const Twine &Name, GlobalVariable *Before,
310 ThreadLocalMode TLMode, unsigned AddressSpace,
311 bool isExternallyInitialized)
312 : GlobalObject(Ty, Value::GlobalVariableVal,
313 OperandTraits<GlobalVariable>::op_begin(this),
314 InitVal != nullptr, Link, Name, AddressSpace),
315 isConstantGlobal(constant),
316 isExternallyInitializedConstant(isExternallyInitialized) {
317 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
318 "invalid type for global variable");
319 setThreadLocalMode(TLMode);
321 assert(InitVal->getType() == Ty &&
322 "Initializer should be the same type as the GlobalVariable!");
327 Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
329 M.getGlobalList().push_back(this);
332 void GlobalVariable::removeFromParent() {
333 getParent()->getGlobalList().remove(getIterator());
336 void GlobalVariable::eraseFromParent() {
337 getParent()->getGlobalList().erase(getIterator());
340 void GlobalVariable::setInitializer(Constant *InitVal) {
342 if (hasInitializer()) {
343 // Note, the num operands is used to compute the offset of the operand, so
344 // the order here matters. Clearing the operand then clearing the num
345 // operands ensures we have the correct offset to the operand.
346 Op<0>().set(nullptr);
347 setGlobalVariableNumOperands(0);
350 assert(InitVal->getType() == getValueType() &&
351 "Initializer type must match GlobalVariable type");
352 // Note, the num operands is used to compute the offset of the operand, so
353 // the order here matters. We need to set num operands to 1 first so that
354 // we get the correct offset to the first operand when we set it.
355 if (!hasInitializer())
356 setGlobalVariableNumOperands(1);
357 Op<0>().set(InitVal);
361 /// Copy all additional attributes (those not needed to create a GlobalVariable)
362 /// from the GlobalVariable Src to this one.
363 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
364 GlobalObject::copyAttributesFrom(Src);
365 setThreadLocalMode(Src->getThreadLocalMode());
366 setExternallyInitialized(Src->isExternallyInitialized());
367 setAttributes(Src->getAttributes());
370 void GlobalVariable::dropAllReferences() {
371 User::dropAllReferences();
375 //===----------------------------------------------------------------------===//
376 // GlobalIndirectSymbol Implementation
377 //===----------------------------------------------------------------------===//
379 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
380 unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
382 : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
387 //===----------------------------------------------------------------------===//
388 // GlobalAlias Implementation
389 //===----------------------------------------------------------------------===//
391 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
392 const Twine &Name, Constant *Aliasee,
393 Module *ParentModule)
394 : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
397 ParentModule->getAliasList().push_back(this);
400 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
401 LinkageTypes Link, const Twine &Name,
402 Constant *Aliasee, Module *ParentModule) {
403 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
406 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
407 LinkageTypes Linkage, const Twine &Name,
409 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
412 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
413 LinkageTypes Linkage, const Twine &Name,
414 GlobalValue *Aliasee) {
415 return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
418 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
419 GlobalValue *Aliasee) {
420 PointerType *PTy = Aliasee->getType();
421 return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
425 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
426 return create(Aliasee->getLinkage(), Name, Aliasee);
429 void GlobalAlias::removeFromParent() {
430 getParent()->getAliasList().remove(getIterator());
433 void GlobalAlias::eraseFromParent() {
434 getParent()->getAliasList().erase(getIterator());
437 void GlobalAlias::setAliasee(Constant *Aliasee) {
438 assert((!Aliasee || Aliasee->getType() == getType()) &&
439 "Alias and aliasee types should match!");
440 setIndirectSymbol(Aliasee);
443 //===----------------------------------------------------------------------===//
444 // GlobalIFunc Implementation
445 //===----------------------------------------------------------------------===//
447 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
448 const Twine &Name, Constant *Resolver,
449 Module *ParentModule)
450 : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
453 ParentModule->getIFuncList().push_back(this);
456 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
457 LinkageTypes Link, const Twine &Name,
458 Constant *Resolver, Module *ParentModule) {
459 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
462 void GlobalIFunc::removeFromParent() {
463 getParent()->getIFuncList().remove(getIterator());
466 void GlobalIFunc::eraseFromParent() {
467 getParent()->getIFuncList().erase(getIterator());