[AArch64] Crypto requires FP.
[llvm-core.git] / lib / IR / Globals.cpp
blob5f338f58d9403677532cb22196e39a517937ab6f
1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the GlobalValue & GlobalVariable classes for the IR
11 // library.
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"
28 using namespace llvm;
30 //===----------------------------------------------------------------------===//
31 // GlobalValue Class
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();
48 return false;
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
80 // Alias = Absolute
81 return 0;
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 void GlobalObject::copyAttributesFrom(const GlobalValue *Src) {
97 GlobalValue::copyAttributesFrom(Src);
98 if (const auto *GV = dyn_cast<GlobalObject>(Src)) {
99 setAlignment(GV->getAlignment());
100 setSection(GV->getSection());
104 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
105 GlobalValue::LinkageTypes Linkage,
106 StringRef FileName) {
108 // Value names may be prefixed with a binary '1' to indicate
109 // that the backend should not modify the symbols due to any platform
110 // naming convention. Do not include that '1' in the PGO profile name.
111 if (Name[0] == '\1')
112 Name = Name.substr(1);
114 std::string NewName = Name;
115 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
116 // For local symbols, prepend the main file name to distinguish them.
117 // Do not include the full path in the file name since there's no guarantee
118 // that it will stay the same, e.g., if the files are checked out from
119 // version control in different locations.
120 if (FileName.empty())
121 NewName = NewName.insert(0, "<unknown>:");
122 else
123 NewName = NewName.insert(0, FileName.str() + ":");
125 return NewName;
128 std::string GlobalValue::getGlobalIdentifier() const {
129 return getGlobalIdentifier(getName(), getLinkage(),
130 getParent()->getSourceFileName());
133 StringRef GlobalValue::getSection() const {
134 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
135 // In general we cannot compute this at the IR level, but we try.
136 if (const GlobalObject *GO = GA->getBaseObject())
137 return GO->getSection();
138 return "";
140 return cast<GlobalObject>(this)->getSection();
143 const Comdat *GlobalValue::getComdat() const {
144 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
145 // In general we cannot compute this at the IR level, but we try.
146 if (const GlobalObject *GO = GA->getBaseObject())
147 return const_cast<GlobalObject *>(GO)->getComdat();
148 return nullptr;
150 // ifunc and its resolver are separate things so don't use resolver comdat.
151 if (isa<GlobalIFunc>(this))
152 return nullptr;
153 return cast<GlobalObject>(this)->getComdat();
156 StringRef GlobalObject::getSectionImpl() const {
157 assert(hasSection());
158 return getContext().pImpl->GlobalObjectSections[this];
161 void GlobalObject::setSection(StringRef S) {
162 // Do nothing if we're clearing the section and it is already empty.
163 if (!hasSection() && S.empty())
164 return;
166 // Get or create a stable section name string and put it in the table in the
167 // context.
168 if (!S.empty()) {
169 S = getContext().pImpl->SectionStrings.insert(S).first->first();
171 getContext().pImpl->GlobalObjectSections[this] = S;
173 // Update the HasSectionHashEntryBit. Setting the section to the empty string
174 // means this global no longer has a section.
175 setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
178 bool GlobalValue::isDeclaration() const {
179 // Globals are definitions if they have an initializer.
180 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
181 return GV->getNumOperands() == 0;
183 // Functions are definitions if they have a body.
184 if (const Function *F = dyn_cast<Function>(this))
185 return F->empty() && !F->isMaterializable();
187 // Aliases and ifuncs are always definitions.
188 assert(isa<GlobalIndirectSymbol>(this));
189 return false;
192 bool GlobalValue::canIncreaseAlignment() const {
193 // Firstly, can only increase the alignment of a global if it
194 // is a strong definition.
195 if (!isStrongDefinitionForLinker())
196 return false;
198 // It also has to either not have a section defined, or, not have
199 // alignment specified. (If it is assigned a section, the global
200 // could be densely packed with other objects in the section, and
201 // increasing the alignment could cause padding issues.)
202 if (hasSection() && getAlignment() > 0)
203 return false;
205 // On ELF platforms, we're further restricted in that we can't
206 // increase the alignment of any variable which might be emitted
207 // into a shared library, and which is exported. If the main
208 // executable accesses a variable found in a shared-lib, the main
209 // exe actually allocates memory for and exports the symbol ITSELF,
210 // overriding the symbol found in the library. That is, at link
211 // time, the observed alignment of the variable is copied into the
212 // executable binary. (A COPY relocation is also generated, to copy
213 // the initial data from the shadowed variable in the shared-lib
214 // into the location in the main binary, before running code.)
216 // And thus, even though you might think you are defining the
217 // global, and allocating the memory for the global in your object
218 // file, and thus should be able to set the alignment arbitrarily,
219 // that's not actually true. Doing so can cause an ABI breakage; an
220 // executable might have already been built with the previous
221 // alignment of the variable, and then assuming an increased
222 // alignment will be incorrect.
224 // Conservatively assume ELF if there's no parent pointer.
225 bool isELF =
226 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
227 if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
228 return false;
230 return true;
233 const GlobalObject *GlobalValue::getBaseObject() const {
234 if (auto *GO = dyn_cast<GlobalObject>(this))
235 return GO;
236 if (auto *GA = dyn_cast<GlobalAlias>(this))
237 return GA->getBaseObject();
238 return nullptr;
241 bool GlobalValue::isAbsoluteSymbolRef() const {
242 auto *GO = dyn_cast<GlobalObject>(this);
243 if (!GO)
244 return false;
246 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
249 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
250 auto *GO = dyn_cast<GlobalObject>(this);
251 if (!GO)
252 return None;
254 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
255 if (!MD)
256 return None;
258 return getConstantRangeFromMetadata(*MD);
261 //===----------------------------------------------------------------------===//
262 // GlobalVariable Implementation
263 //===----------------------------------------------------------------------===//
265 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
266 Constant *InitVal, const Twine &Name,
267 ThreadLocalMode TLMode, unsigned AddressSpace,
268 bool isExternallyInitialized)
269 : GlobalObject(Ty, Value::GlobalVariableVal,
270 OperandTraits<GlobalVariable>::op_begin(this),
271 InitVal != nullptr, Link, Name, AddressSpace),
272 isConstantGlobal(constant),
273 isExternallyInitializedConstant(isExternallyInitialized) {
274 setThreadLocalMode(TLMode);
275 if (InitVal) {
276 assert(InitVal->getType() == Ty &&
277 "Initializer should be the same type as the GlobalVariable!");
278 Op<0>() = InitVal;
282 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
283 LinkageTypes Link, Constant *InitVal,
284 const Twine &Name, GlobalVariable *Before,
285 ThreadLocalMode TLMode, unsigned AddressSpace,
286 bool isExternallyInitialized)
287 : GlobalObject(Ty, Value::GlobalVariableVal,
288 OperandTraits<GlobalVariable>::op_begin(this),
289 InitVal != nullptr, Link, Name, AddressSpace),
290 isConstantGlobal(constant),
291 isExternallyInitializedConstant(isExternallyInitialized) {
292 setThreadLocalMode(TLMode);
293 if (InitVal) {
294 assert(InitVal->getType() == Ty &&
295 "Initializer should be the same type as the GlobalVariable!");
296 Op<0>() = InitVal;
299 if (Before)
300 Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
301 else
302 M.getGlobalList().push_back(this);
305 void GlobalVariable::removeFromParent() {
306 getParent()->getGlobalList().remove(getIterator());
309 void GlobalVariable::eraseFromParent() {
310 getParent()->getGlobalList().erase(getIterator());
313 void GlobalVariable::setInitializer(Constant *InitVal) {
314 if (!InitVal) {
315 if (hasInitializer()) {
316 // Note, the num operands is used to compute the offset of the operand, so
317 // the order here matters. Clearing the operand then clearing the num
318 // operands ensures we have the correct offset to the operand.
319 Op<0>().set(nullptr);
320 setGlobalVariableNumOperands(0);
322 } else {
323 assert(InitVal->getType() == getValueType() &&
324 "Initializer type must match GlobalVariable type");
325 // Note, the num operands is used to compute the offset of the operand, so
326 // the order here matters. We need to set num operands to 1 first so that
327 // we get the correct offset to the first operand when we set it.
328 if (!hasInitializer())
329 setGlobalVariableNumOperands(1);
330 Op<0>().set(InitVal);
334 /// Copy all additional attributes (those not needed to create a GlobalVariable)
335 /// from the GlobalVariable Src to this one.
336 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
337 GlobalObject::copyAttributesFrom(Src);
338 if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(Src)) {
339 setThreadLocalMode(SrcVar->getThreadLocalMode());
340 setExternallyInitialized(SrcVar->isExternallyInitialized());
344 void GlobalVariable::dropAllReferences() {
345 User::dropAllReferences();
346 clearMetadata();
349 //===----------------------------------------------------------------------===//
350 // GlobalIndirectSymbol Implementation
351 //===----------------------------------------------------------------------===//
353 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
354 unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
355 Constant *Symbol)
356 : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
357 Op<0>() = Symbol;
361 //===----------------------------------------------------------------------===//
362 // GlobalAlias Implementation
363 //===----------------------------------------------------------------------===//
365 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
366 const Twine &Name, Constant *Aliasee,
367 Module *ParentModule)
368 : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
369 Aliasee) {
370 if (ParentModule)
371 ParentModule->getAliasList().push_back(this);
374 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
375 LinkageTypes Link, const Twine &Name,
376 Constant *Aliasee, Module *ParentModule) {
377 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
380 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
381 LinkageTypes Linkage, const Twine &Name,
382 Module *Parent) {
383 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
386 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
387 LinkageTypes Linkage, const Twine &Name,
388 GlobalValue *Aliasee) {
389 return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
392 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
393 GlobalValue *Aliasee) {
394 PointerType *PTy = Aliasee->getType();
395 return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
396 Aliasee);
399 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
400 return create(Aliasee->getLinkage(), Name, Aliasee);
403 void GlobalAlias::removeFromParent() {
404 getParent()->getAliasList().remove(getIterator());
407 void GlobalAlias::eraseFromParent() {
408 getParent()->getAliasList().erase(getIterator());
411 void GlobalAlias::setAliasee(Constant *Aliasee) {
412 assert((!Aliasee || Aliasee->getType() == getType()) &&
413 "Alias and aliasee types should match!");
414 setIndirectSymbol(Aliasee);
417 //===----------------------------------------------------------------------===//
418 // GlobalIFunc Implementation
419 //===----------------------------------------------------------------------===//
421 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
422 const Twine &Name, Constant *Resolver,
423 Module *ParentModule)
424 : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
425 Resolver) {
426 if (ParentModule)
427 ParentModule->getIFuncList().push_back(this);
430 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
431 LinkageTypes Link, const Twine &Name,
432 Constant *Resolver, Module *ParentModule) {
433 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
436 void GlobalIFunc::removeFromParent() {
437 getParent()->getIFuncList().remove(getIterator());
440 void GlobalIFunc::eraseFromParent() {
441 getParent()->getIFuncList().erase(getIterator());