LCOV - code coverage report
Current view: top level - lib/IR - Globals.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 160 174 92.0 %
Date: 2017-09-14 15:23:50 Functions: 38 42 90.5 %
Legend: Lines: hit not hit

          Line data    Source code
       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       54993 : bool GlobalValue::isMaterializable() const {
      46           0 :   if (const Function *F = dyn_cast<Function>(this))
      47           0 :     return F->isMaterializable();
      48             :   return false;
      49             : }
      50      105893 : Error GlobalValue::materialize() {
      51      105893 :   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           0 : void GlobalValue::destroyConstantImpl() {
      57           0 :   llvm_unreachable("You can't GV->destroyConstantImpl()!");
      58             : }
      59             : 
      60           0 : Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
      61           0 :   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        3741 : void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
      67        7482 :   setVisibility(Src->getVisibility());
      68        7482 :   setUnnamedAddr(Src->getUnnamedAddr());
      69        7482 :   setDLLStorageClass(Src->getDLLStorageClass());
      70        3741 : }
      71             : 
      72           0 : void GlobalValue::removeFromParent() {
      73           0 :   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           0 :   llvm_unreachable("not a global");
      82             : }
      83             : 
      84        4521 : void GlobalValue::eraseFromParent() {
      85        9042 :   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           0 :   llvm_unreachable("not a global");
      94             : }
      95             : 
      96     1240109 : unsigned GlobalValue::getAlignment() const {
      97     1240109 :   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
      98             :     // In general we cannot compute this at the IR level, but we try.
      99        2427 :     if (const GlobalObject *GO = GA->getBaseObject())
     100        2346 :       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     2475364 :   return cast<GlobalObject>(this)->getAlignment();
     108             : }
     109             : 
     110      359948 : 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      359948 :   unsigned AlignmentData = Log2_32(Align) + 1;
     115      719896 :   unsigned OldData = getGlobalValueSubClassData();
     116      719896 :   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
     117             :   assert(getAlignment() == Align && "Alignment representation error!");
     118      359948 : }
     119             : 
     120        3630 : void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
     121        3630 :   GlobalValue::copyAttributesFrom(Src);
     122        3630 :   setAlignment(Src->getAlignment());
     123        3630 :   setSection(Src->getSection());
     124        3630 : }
     125             : 
     126        4965 : 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        9930 :   if (Name[0] == '\1')
     134          43 :     Name = Name.substr(1);
     135             : 
     136        4965 :   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         414 :     if (FileName.empty())
     143           1 :       NewName = NewName.insert(0, "<unknown>:");
     144             :     else
     145        2065 :       NewName = NewName.insert(0, FileName.str() + ":");
     146             :   }
     147        4965 :   return NewName;
     148             : }
     149             : 
     150        2071 : std::string GlobalValue::getGlobalIdentifier() const {
     151             :   return getGlobalIdentifier(getName(), getLinkage(),
     152        8284 :                              getParent()->getSourceFileName());
     153             : }
     154             : 
     155       76095 : StringRef GlobalValue::getSection() const {
     156       76095 :   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
     157             :     // In general we cannot compute this at the IR level, but we try.
     158         115 :     if (const GlobalObject *GO = GA->getBaseObject())
     159             :       return GO->getSection();
     160           0 :     return "";
     161             :   }
     162       75980 :   return cast<GlobalObject>(this)->getSection();
     163             : }
     164             : 
     165      733939 : const Comdat *GlobalValue::getComdat() const {
     166      733939 :   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
     167             :     // In general we cannot compute this at the IR level, but we try.
     168        1138 :     if (const GlobalObject *GO = GA->getBaseObject())
     169        1130 :       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     1465602 :   if (isa<GlobalIFunc>(this))
     174             :     return nullptr;
     175      732796 :   return cast<GlobalObject>(this)->getComdat();
     176             : }
     177             : 
     178       18037 : StringRef GlobalObject::getSectionImpl() const {
     179             :   assert(hasSection());
     180       36074 :   return getContext().pImpl->GlobalObjectSections[this];
     181             : }
     182             : 
     183      251752 : void GlobalObject::setSection(StringRef S) {
     184             :   // Do nothing if we're clearing the section and it is already empty.
     185      251752 :   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       15219 :   if (!S.empty()) {
     191       60872 :     S = getContext().pImpl->SectionStrings.insert(S).first->first();
     192             :   }
     193       30438 :   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       15219 :   setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
     198             : }
     199             : 
     200    39102247 : bool GlobalValue::isDeclaration() const {
     201             :   // Globals are definitions if they have an initializer.
     202    39102247 :   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
     203    22332824 :     return GV->getNumOperands() == 0;
     204             : 
     205             :   // Functions are definitions if they have a body.
     206    16763613 :   if (const Function *F = dyn_cast<Function>(this))
     207    22259410 :     return F->empty() && !F->isMaterializable();
     208             : 
     209             :   // Aliases and ifuncs are always definitions.
     210             :   assert(isa<GlobalIndirectSymbol>(this));
     211             :   return false;
     212             : }
     213             : 
     214       12596 : bool GlobalValue::canIncreaseAlignment() const {
     215             :   // Firstly, can only increase the alignment of a global if it
     216             :   // is a strong definition.
     217       12596 :   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       12502 :   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       62420 :       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
     249       24946 :   if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
     250             :     return false;
     251             : 
     252             :   return true;
     253             : }
     254             : 
     255       22389 : const GlobalObject *GlobalValue::getBaseObject() const {
     256         567 :   if (auto *GO = dyn_cast<GlobalObject>(this))
     257             :     return GO;
     258         567 :   if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
     259         567 :     return GA->getBaseObject();
     260             :   return nullptr;
     261             : }
     262             : 
     263      472105 : bool GlobalValue::isAbsoluteSymbolRef() const {
     264      472093 :   auto *GO = dyn_cast<GlobalObject>(this);
     265             :   if (!GO)
     266             :     return false;
     267             : 
     268      472093 :   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
     269             : }
     270             : 
     271     1458644 : Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
     272     1458625 :   auto *GO = dyn_cast<GlobalObject>(this);
     273             :   if (!GO)
     274             :     return None;
     275             : 
     276     1458625 :   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
     277     1458625 :   if (!MD)
     278             :     return None;
     279             : 
     280          76 :   return getConstantRangeFromMetadata(*MD);
     281             : }
     282             : 
     283             : //===----------------------------------------------------------------------===//
     284             : // GlobalVariable Implementation
     285             : //===----------------------------------------------------------------------===//
     286             : 
     287         114 : GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
     288             :                                Constant *InitVal, const Twine &Name,
     289             :                                ThreadLocalMode TLMode, unsigned AddressSpace,
     290         114 :                                bool isExternallyInitialized)
     291             :     : GlobalObject(Ty, Value::GlobalVariableVal,
     292             :                    OperandTraits<GlobalVariable>::op_begin(this),
     293             :                    InitVal != nullptr, Link, Name, AddressSpace),
     294             :       isConstantGlobal(constant),
     295         570 :       isExternallyInitializedConstant(isExternallyInitialized) {
     296             :   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
     297             :          "invalid type for global variable");
     298         228 :   setThreadLocalMode(TLMode);
     299         114 :   if (InitVal) {
     300             :     assert(InitVal->getType() == Ty &&
     301             :            "Initializer should be the same type as the GlobalVariable!");
     302         103 :     Op<0>() = InitVal;
     303             :   }
     304         114 : }
     305             : 
     306      141008 : 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      141008 :                                bool isExternallyInitialized)
     311             :     : GlobalObject(Ty, Value::GlobalVariableVal,
     312             :                    OperandTraits<GlobalVariable>::op_begin(this),
     313             :                    InitVal != nullptr, Link, Name, AddressSpace),
     314             :       isConstantGlobal(constant),
     315      705040 :       isExternallyInitializedConstant(isExternallyInitialized) {
     316             :   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
     317             :          "invalid type for global variable");
     318      282016 :   setThreadLocalMode(TLMode);
     319      141008 :   if (InitVal) {
     320             :     assert(InitVal->getType() == Ty &&
     321             :            "Initializer should be the same type as the GlobalVariable!");
     322       87004 :     Op<0>() = InitVal;
     323             :   }
     324             : 
     325      141008 :   if (Before)
     326         556 :     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
     327             :   else
     328      140730 :     M.getGlobalList().push_back(this);
     329      141008 : }
     330             : 
     331          94 : void GlobalVariable::removeFromParent() {
     332         282 :   getParent()->getGlobalList().remove(getIterator());
     333          94 : }
     334             : 
     335        3702 : void GlobalVariable::eraseFromParent() {
     336        7404 :   getParent()->getGlobalList().erase(getIterator());
     337        3702 : }
     338             : 
     339       42075 : void GlobalVariable::setInitializer(Constant *InitVal) {
     340       42075 :   if (!InitVal) {
     341        1844 :     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        3688 :       Op<0>().set(nullptr);
     346        1844 :       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       40231 :     if (!hasInitializer())
     355       39414 :       setGlobalVariableNumOperands(1);
     356       40231 :     Op<0>().set(InitVal);
     357             :   }
     358       42075 : }
     359             : 
     360             : /// Copy all additional attributes (those not needed to create a GlobalVariable)
     361             : /// from the GlobalVariable Src to this one.
     362         912 : void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
     363         912 :   GlobalObject::copyAttributesFrom(Src);
     364        2736 :   setThreadLocalMode(Src->getThreadLocalMode());
     365        1824 :   setExternallyInitialized(Src->isExternallyInitialized());
     366         912 :   setAttributes(Src->getAttributes());
     367         912 : }
     368             : 
     369      166789 : void GlobalVariable::dropAllReferences() {
     370      166789 :   User::dropAllReferences();
     371      166789 :   clearMetadata();
     372      166789 : }
     373             : 
     374             : //===----------------------------------------------------------------------===//
     375             : // GlobalIndirectSymbol Implementation
     376             : //===----------------------------------------------------------------------===//
     377             : 
     378        2372 : GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
     379             :     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
     380        2372 :     Constant *Symbol)
     381        4744 :     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
     382        4744 :     Op<0>() = Symbol;
     383        2372 : }
     384             : 
     385             : 
     386             : //===----------------------------------------------------------------------===//
     387             : // GlobalAlias Implementation
     388             : //===----------------------------------------------------------------------===//
     389             : 
     390        2288 : GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
     391             :                          const Twine &Name, Constant *Aliasee,
     392        2288 :                          Module *ParentModule)
     393             :     : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
     394        4576 :                            Aliasee) {
     395        2288 :   if (ParentModule)
     396        1469 :     ParentModule->getAliasList().push_back(this);
     397        2288 : }
     398             : 
     399        2288 : GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
     400             :                                  LinkageTypes Link, const Twine &Name,
     401             :                                  Constant *Aliasee, Module *ParentModule) {
     402        2288 :   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
     403             : }
     404             : 
     405         829 : GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
     406             :                                  LinkageTypes Linkage, const Twine &Name,
     407             :                                  Module *Parent) {
     408         829 :   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
     409             : }
     410             : 
     411         182 : GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
     412             :                                  LinkageTypes Linkage, const Twine &Name,
     413             :                                  GlobalValue *Aliasee) {
     414         182 :   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
     415             : }
     416             : 
     417         182 : GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
     418             :                                  GlobalValue *Aliasee) {
     419         182 :   PointerType *PTy = Aliasee->getType();
     420         182 :   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
     421         182 :                 Aliasee);
     422             : }
     423             : 
     424           2 : GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
     425           2 :   return create(Aliasee->getLinkage(), Name, Aliasee);
     426             : }
     427             : 
     428           9 : void GlobalAlias::removeFromParent() {
     429          27 :   getParent()->getAliasList().remove(getIterator());
     430           9 : }
     431             : 
     432          79 : void GlobalAlias::eraseFromParent() {
     433         237 :   getParent()->getAliasList().erase(getIterator());
     434          79 : }
     435             : 
     436         114 : void GlobalAlias::setAliasee(Constant *Aliasee) {
     437             :   assert((!Aliasee || Aliasee->getType() == getType()) &&
     438             :          "Alias and aliasee types should match!");
     439         228 :   setIndirectSymbol(Aliasee);
     440         114 : }
     441             : 
     442             : //===----------------------------------------------------------------------===//
     443             : // GlobalIFunc Implementation
     444             : //===----------------------------------------------------------------------===//
     445             : 
     446          84 : GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
     447             :                          const Twine &Name, Constant *Resolver,
     448          84 :                          Module *ParentModule)
     449             :     : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
     450         168 :                            Resolver) {
     451          84 :   if (ParentModule)
     452          50 :     ParentModule->getIFuncList().push_back(this);
     453          84 : }
     454             : 
     455          84 : GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
     456             :                                  LinkageTypes Link, const Twine &Name,
     457             :                                  Constant *Resolver, Module *ParentModule) {
     458          84 :   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
     459             : }
     460             : 
     461           0 : void GlobalIFunc::removeFromParent() {
     462           0 :   getParent()->getIFuncList().remove(getIterator());
     463           0 : }
     464             : 
     465           7 : void GlobalIFunc::eraseFromParent() {
     466          21 :   getParent()->getIFuncList().erase(getIterator());
     467           7 : }

Generated by: LCOV version 1.13