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 "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/ConstantRange.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 #include "LLVMContextImpl.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 unsigned GlobalValue::getAlignment() const {
73 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
74 // In general we cannot compute this at the IR level, but we try.
75 if (const GlobalObject *GO = GA->getBaseObject())
76 return GO->getAlignment();
78 // FIXME: we should also be able to handle:
79 // Alias = Global + Offset
83 return cast<GlobalObject>(this)->getAlignment();
86 void GlobalObject::setAlignment(unsigned Align) {
87 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
88 assert(Align <= MaximumAlignment &&
89 "Alignment is greater than MaximumAlignment!");
90 unsigned AlignmentData = Log2_32(Align) + 1;
91 unsigned OldData = getGlobalValueSubClassData();
92 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
93 assert(getAlignment() == Align && "Alignment representation error!");
96 unsigned GlobalObject::getGlobalObjectSubClassData() const {
97 unsigned ValueData = getGlobalValueSubClassData();
98 return ValueData >> GlobalObjectBits;
101 void GlobalObject::setGlobalObjectSubClassData(unsigned Val) {
102 unsigned OldData = getGlobalValueSubClassData();
103 setGlobalValueSubClassData((OldData & GlobalObjectMask) |
104 (Val << GlobalObjectBits));
105 assert(getGlobalObjectSubClassData() == Val && "representation error");
108 void GlobalObject::copyAttributesFrom(const GlobalValue *Src) {
109 GlobalValue::copyAttributesFrom(Src);
110 if (const auto *GV = dyn_cast<GlobalObject>(Src)) {
111 setAlignment(GV->getAlignment());
112 setSection(GV->getSection());
116 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
117 GlobalValue::LinkageTypes Linkage,
118 StringRef FileName) {
120 // Value names may be prefixed with a binary '1' to indicate
121 // that the backend should not modify the symbols due to any platform
122 // naming convention. Do not include that '1' in the PGO profile name.
124 Name = Name.substr(1);
126 std::string NewName = Name;
127 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
128 // For local symbols, prepend the main file name to distinguish them.
129 // Do not include the full path in the file name since there's no guarantee
130 // that it will stay the same, e.g., if the files are checked out from
131 // version control in different locations.
132 if (FileName.empty())
133 NewName = NewName.insert(0, "<unknown>:");
135 NewName = NewName.insert(0, FileName.str() + ":");
140 std::string GlobalValue::getGlobalIdentifier() const {
141 return getGlobalIdentifier(getName(), getLinkage(),
142 getParent()->getSourceFileName());
145 StringRef GlobalValue::getSection() const {
146 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
147 // In general we cannot compute this at the IR level, but we try.
148 if (const GlobalObject *GO = GA->getBaseObject())
149 return GO->getSection();
152 return cast<GlobalObject>(this)->getSection();
155 Comdat *GlobalValue::getComdat() {
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 const_cast<GlobalObject *>(GO)->getComdat();
162 // ifunc and its resolver are separate things so don't use resolver comdat.
163 if (isa<GlobalIFunc>(this))
165 return cast<GlobalObject>(this)->getComdat();
168 StringRef GlobalObject::getSectionImpl() const {
169 assert(hasSection());
170 return getContext().pImpl->GlobalObjectSections[this];
173 void GlobalObject::setSection(StringRef S) {
174 // Do nothing if we're clearing the section and it is already empty.
175 if (!hasSection() && S.empty())
178 // Get or create a stable section name string and put it in the table in the
180 S = getContext().pImpl->SectionStrings.insert(S).first->first();
181 getContext().pImpl->GlobalObjectSections[this] = S;
183 // Update the HasSectionHashEntryBit. Setting the section to the empty string
184 // means this global no longer has a section.
185 setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
188 bool GlobalValue::isDeclaration() const {
189 // Globals are definitions if they have an initializer.
190 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
191 return GV->getNumOperands() == 0;
193 // Functions are definitions if they have a body.
194 if (const Function *F = dyn_cast<Function>(this))
195 return F->empty() && !F->isMaterializable();
197 // Aliases and ifuncs are always definitions.
198 assert(isa<GlobalIndirectSymbol>(this));
202 bool GlobalValue::canIncreaseAlignment() const {
203 // Firstly, can only increase the alignment of a global if it
204 // is a strong definition.
205 if (!isStrongDefinitionForLinker())
208 // It also has to either not have a section defined, or, not have
209 // alignment specified. (If it is assigned a section, the global
210 // could be densely packed with other objects in the section, and
211 // increasing the alignment could cause padding issues.)
212 if (hasSection() && getAlignment() > 0)
215 // On ELF platforms, we're further restricted in that we can't
216 // increase the alignment of any variable which might be emitted
217 // into a shared library, and which is exported. If the main
218 // executable accesses a variable found in a shared-lib, the main
219 // exe actually allocates memory for and exports the symbol ITSELF,
220 // overriding the symbol found in the library. That is, at link
221 // time, the observed alignment of the variable is copied into the
222 // executable binary. (A COPY relocation is also generated, to copy
223 // the initial data from the shadowed variable in the shared-lib
224 // into the location in the main binary, before running code.)
226 // And thus, even though you might think you are defining the
227 // global, and allocating the memory for the global in your object
228 // file, and thus should be able to set the alignment arbitrarily,
229 // that's not actually true. Doing so can cause an ABI breakage; an
230 // executable might have already been built with the previous
231 // alignment of the variable, and then assuming an increased
232 // alignment will be incorrect.
234 // Conservatively assume ELF if there's no parent pointer.
236 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
237 if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
243 GlobalObject *GlobalValue::getBaseObject() {
244 if (auto *GO = dyn_cast<GlobalObject>(this))
246 if (auto *GA = dyn_cast<GlobalAlias>(this))
247 return GA->getBaseObject();
251 bool GlobalValue::isAbsoluteSymbolRef() const {
252 auto *GO = dyn_cast<GlobalObject>(this);
256 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
259 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
260 auto *GO = dyn_cast<GlobalObject>(this);
264 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
268 return getConstantRangeFromMetadata(*MD);
271 //===----------------------------------------------------------------------===//
272 // GlobalVariable Implementation
273 //===----------------------------------------------------------------------===//
275 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
276 Constant *InitVal, const Twine &Name,
277 ThreadLocalMode TLMode, unsigned AddressSpace,
278 bool isExternallyInitialized)
279 : GlobalObject(Ty, Value::GlobalVariableVal,
280 OperandTraits<GlobalVariable>::op_begin(this),
281 InitVal != nullptr, Link, Name, AddressSpace),
282 isConstantGlobal(constant),
283 isExternallyInitializedConstant(isExternallyInitialized) {
284 setThreadLocalMode(TLMode);
286 assert(InitVal->getType() == Ty &&
287 "Initializer should be the same type as the GlobalVariable!");
292 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
293 LinkageTypes Link, Constant *InitVal,
294 const Twine &Name, GlobalVariable *Before,
295 ThreadLocalMode TLMode, unsigned AddressSpace,
296 bool isExternallyInitialized)
297 : GlobalObject(Ty, Value::GlobalVariableVal,
298 OperandTraits<GlobalVariable>::op_begin(this),
299 InitVal != nullptr, Link, Name, AddressSpace),
300 isConstantGlobal(constant),
301 isExternallyInitializedConstant(isExternallyInitialized) {
302 setThreadLocalMode(TLMode);
304 assert(InitVal->getType() == Ty &&
305 "Initializer should be the same type as the GlobalVariable!");
310 Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
312 M.getGlobalList().push_back(this);
315 void GlobalVariable::removeFromParent() {
316 getParent()->getGlobalList().remove(getIterator());
319 void GlobalVariable::eraseFromParent() {
320 getParent()->getGlobalList().erase(getIterator());
323 void GlobalVariable::setInitializer(Constant *InitVal) {
325 if (hasInitializer()) {
326 // Note, the num operands is used to compute the offset of the operand, so
327 // the order here matters. Clearing the operand then clearing the num
328 // operands ensures we have the correct offset to the operand.
329 Op<0>().set(nullptr);
330 setGlobalVariableNumOperands(0);
333 assert(InitVal->getType() == getValueType() &&
334 "Initializer type must match GlobalVariable type");
335 // Note, the num operands is used to compute the offset of the operand, so
336 // the order here matters. We need to set num operands to 1 first so that
337 // we get the correct offset to the first operand when we set it.
338 if (!hasInitializer())
339 setGlobalVariableNumOperands(1);
340 Op<0>().set(InitVal);
344 /// Copy all additional attributes (those not needed to create a GlobalVariable)
345 /// from the GlobalVariable Src to this one.
346 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
347 GlobalObject::copyAttributesFrom(Src);
348 if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(Src)) {
349 setThreadLocalMode(SrcVar->getThreadLocalMode());
350 setExternallyInitialized(SrcVar->isExternallyInitialized());
354 void GlobalVariable::dropAllReferences() {
355 User::dropAllReferences();
359 //===----------------------------------------------------------------------===//
360 // GlobalIndirectSymbol Implementation
361 //===----------------------------------------------------------------------===//
363 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
364 unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
366 : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
371 //===----------------------------------------------------------------------===//
372 // GlobalAlias Implementation
373 //===----------------------------------------------------------------------===//
375 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
376 const Twine &Name, Constant *Aliasee,
377 Module *ParentModule)
378 : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
381 ParentModule->getAliasList().push_back(this);
384 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
385 LinkageTypes Link, const Twine &Name,
386 Constant *Aliasee, Module *ParentModule) {
387 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
390 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
391 LinkageTypes Linkage, const Twine &Name,
393 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
396 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
397 LinkageTypes Linkage, const Twine &Name,
398 GlobalValue *Aliasee) {
399 return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
402 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
403 GlobalValue *Aliasee) {
404 PointerType *PTy = Aliasee->getType();
405 return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
409 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
410 return create(Aliasee->getLinkage(), Name, Aliasee);
413 void GlobalAlias::removeFromParent() {
414 getParent()->getAliasList().remove(getIterator());
417 void GlobalAlias::eraseFromParent() {
418 getParent()->getAliasList().erase(getIterator());
421 void GlobalAlias::setAliasee(Constant *Aliasee) {
422 assert((!Aliasee || Aliasee->getType() == getType()) &&
423 "Alias and aliasee types should match!");
424 setIndirectSymbol(Aliasee);
427 //===----------------------------------------------------------------------===//
428 // GlobalIFunc Implementation
429 //===----------------------------------------------------------------------===//
431 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
432 const Twine &Name, Constant *Resolver,
433 Module *ParentModule)
434 : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
437 ParentModule->getIFuncList().push_back(this);
440 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
441 LinkageTypes Link, const Twine &Name,
442 Constant *Resolver, Module *ParentModule) {
443 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
446 void GlobalIFunc::removeFromParent() {
447 getParent()->getIFuncList().remove(getIterator());
450 void GlobalIFunc::eraseFromParent() {
451 getParent()->getIFuncList().erase(getIterator());