]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/IR/Globals.cpp
Merge ^/head r320573 through r320970.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / IR / Globals.cpp
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.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
28 using namespace llvm;
29
30 //===----------------------------------------------------------------------===//
31 //                            GlobalValue Class
32 //===----------------------------------------------------------------------===//
33
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");
40
41 // GlobalObject adds a comdat.
42 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
43               "unexpected GlobalObject size growth");
44
45 bool GlobalValue::isMaterializable() const {
46   if (const Function *F = dyn_cast<Function>(this))
47     return F->isMaterializable();
48   return false;
49 }
50 Error GlobalValue::materialize() {
51   return getParent()->materialize(this);
52 }
53
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()!");
58 }
59
60 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
61   llvm_unreachable("Unsupported class for handleOperandChange()!");
62 }
63
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 }
71
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"
78   default:
79     break;
80   }
81   llvm_unreachable("not a global");
82 }
83
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"
90   default:
91     break;
92   }
93   llvm_unreachable("not a global");
94 }
95
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();
101
102     // FIXME: we should also be able to handle:
103     // Alias = Global + Offset
104     // Alias = Absolute
105     return 0;
106   }
107   return cast<GlobalObject>(this)->getAlignment();
108 }
109
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!");
118 }
119
120 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
121   GlobalValue::copyAttributesFrom(Src);
122   setAlignment(Src->getAlignment());
123   setSection(Src->getSection());
124 }
125
126 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
127                                              GlobalValue::LinkageTypes Linkage,
128                                              StringRef FileName) {
129
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.
133   if (Name[0] == '\1')
134     Name = Name.substr(1);
135
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>:");
144     else
145       NewName = NewName.insert(0, FileName.str() + ":");
146   }
147   return NewName;
148 }
149
150 std::string GlobalValue::getGlobalIdentifier() const {
151   return getGlobalIdentifier(getName(), getLinkage(),
152                              getParent()->getSourceFileName());
153 }
154
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();
160     return "";
161   }
162   return cast<GlobalObject>(this)->getSection();
163 }
164
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();
170     return nullptr;
171   }
172   // ifunc and its resolver are separate things so don't use resolver comdat.
173   if (isa<GlobalIFunc>(this))
174     return nullptr;
175   return cast<GlobalObject>(this)->getComdat();
176 }
177
178 StringRef GlobalObject::getSectionImpl() const {
179   assert(hasSection());
180   return getContext().pImpl->GlobalObjectSections[this];
181 }
182
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())
186     return;
187
188   // Get or create a stable section name string and put it in the table in the
189   // context.
190   if (!S.empty()) {
191     S = getContext().pImpl->SectionStrings.insert(S).first->first();
192   }
193   getContext().pImpl->GlobalObjectSections[this] = S;
194
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());
198 }
199
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;
204
205   // Functions are definitions if they have a body.
206   if (const Function *F = dyn_cast<Function>(this))
207     return F->empty() && !F->isMaterializable();
208
209   // Aliases and ifuncs are always definitions.
210   assert(isa<GlobalIndirectSymbol>(this));
211   return false;
212 }
213
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())
218     return false;
219
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)
225     return false;
226
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.)
237   //
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.
245
246   // Conservatively assume ELF if there's no parent pointer.
247   bool isELF =
248       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
249   if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
250     return false;
251
252   return true;
253 }
254
255 const GlobalObject *GlobalValue::getBaseObject() const {
256   if (auto *GO = dyn_cast<GlobalObject>(this))
257     return GO;
258   if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
259     return GA->getBaseObject();
260   return nullptr;
261 }
262
263 bool GlobalValue::isAbsoluteSymbolRef() const {
264   auto *GO = dyn_cast<GlobalObject>(this);
265   if (!GO)
266     return false;
267
268   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
269 }
270
271 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
272   auto *GO = dyn_cast<GlobalObject>(this);
273   if (!GO)
274     return None;
275
276   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
277   if (!MD)
278     return None;
279
280   return getConstantRangeFromMetadata(*MD);
281 }
282
283 //===----------------------------------------------------------------------===//
284 // GlobalVariable Implementation
285 //===----------------------------------------------------------------------===//
286
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);
299   if (InitVal) {
300     assert(InitVal->getType() == Ty &&
301            "Initializer should be the same type as the GlobalVariable!");
302     Op<0>() = InitVal;
303   }
304 }
305
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);
319   if (InitVal) {
320     assert(InitVal->getType() == Ty &&
321            "Initializer should be the same type as the GlobalVariable!");
322     Op<0>() = InitVal;
323   }
324
325   if (Before)
326     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
327   else
328     M.getGlobalList().push_back(this);
329 }
330
331 void GlobalVariable::removeFromParent() {
332   getParent()->getGlobalList().remove(getIterator());
333 }
334
335 void GlobalVariable::eraseFromParent() {
336   getParent()->getGlobalList().erase(getIterator());
337 }
338
339 void GlobalVariable::setInitializer(Constant *InitVal) {
340   if (!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);
347     }
348   } else {
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);
357   }
358 }
359
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());
367 }
368
369 void GlobalVariable::dropAllReferences() {
370   User::dropAllReferences();
371   clearMetadata();
372 }
373
374 //===----------------------------------------------------------------------===//
375 // GlobalIndirectSymbol Implementation
376 //===----------------------------------------------------------------------===//
377
378 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
379     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
380     Constant *Symbol)
381     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
382     Op<0>() = Symbol;
383 }
384
385
386 //===----------------------------------------------------------------------===//
387 // GlobalAlias Implementation
388 //===----------------------------------------------------------------------===//
389
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,
394                            Aliasee) {
395   if (ParentModule)
396     ParentModule->getAliasList().push_back(this);
397 }
398
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);
403 }
404
405 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
406                                  LinkageTypes Linkage, const Twine &Name,
407                                  Module *Parent) {
408   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
409 }
410
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());
415 }
416
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,
421                 Aliasee);
422 }
423
424 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
425   return create(Aliasee->getLinkage(), Name, Aliasee);
426 }
427
428 void GlobalAlias::removeFromParent() {
429   getParent()->getAliasList().remove(getIterator());
430 }
431
432 void GlobalAlias::eraseFromParent() {
433   getParent()->getAliasList().erase(getIterator());
434 }
435
436 void GlobalAlias::setAliasee(Constant *Aliasee) {
437   assert((!Aliasee || Aliasee->getType() == getType()) &&
438          "Alias and aliasee types should match!");
439   setIndirectSymbol(Aliasee);
440 }
441
442 //===----------------------------------------------------------------------===//
443 // GlobalIFunc Implementation
444 //===----------------------------------------------------------------------===//
445
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,
450                            Resolver) {
451   if (ParentModule)
452     ParentModule->getIFuncList().push_back(this);
453 }
454
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);
459 }
460
461 void GlobalIFunc::removeFromParent() {
462   getParent()->getIFuncList().remove(getIterator());
463 }
464
465 void GlobalIFunc::eraseFromParent() {
466   getParent()->getIFuncList().erase(getIterator());
467 }