LCOV - code coverage report
Current view: top level - lib/IR - Globals.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 136 149 91.3 %
Date: 2018-07-13 00:08:38 Functions: 39 43 90.7 %
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       84477 : bool GlobalValue::isMaterializable() const {
      46             :   if (const Function *F = dyn_cast<Function>(this))
      47           0 :     return F->isMaterializable();
      48             :   return false;
      49             : }
      50      172462 : Error GlobalValue::materialize() {
      51      172462 :   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        4117 : void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
      67             :   setVisibility(Src->getVisibility());
      68             :   setUnnamedAddr(Src->getUnnamedAddr());
      69             :   setDLLStorageClass(Src->getDLLStorageClass());
      70             :   setDSOLocal(Src->isDSOLocal());
      71        4117 : }
      72             : 
      73           0 : void GlobalValue::removeFromParent() {
      74           0 :   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"
      79             :   default:
      80             :     break;
      81             :   }
      82           0 :   llvm_unreachable("not a global");
      83             : }
      84             : 
      85        6088 : void GlobalValue::eraseFromParent() {
      86       12176 :   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"
      91             :   default:
      92             :     break;
      93             :   }
      94           0 :   llvm_unreachable("not a global");
      95             : }
      96             : 
      97     1720896 : 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        3016 :     if (const GlobalObject *GO = GA->getBaseObject())
     101        2923 :       return GO->getAlignment();
     102             : 
     103             :     // FIXME: we should also be able to handle:
     104             :     // Alias = Global + Offset
     105             :     // Alias = Absolute
     106             :     return 0;
     107             :   }
     108     1717880 :   return cast<GlobalObject>(this)->getAlignment();
     109             : }
     110             : 
     111      524061 : 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      524061 :   unsigned AlignmentData = Log2_32(Align) + 1;
     116             :   unsigned OldData = getGlobalValueSubClassData();
     117      524061 :   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
     118             :   assert(getAlignment() == Align && "Alignment representation error!");
     119      524061 : }
     120             : 
     121        4008 : void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
     122        4008 :   GlobalValue::copyAttributesFrom(Src);
     123        4008 :   setAlignment(Src->getAlignment());
     124        4008 :   setSection(Src->getSection());
     125        4008 : }
     126             : 
     127       11007 : std::string GlobalValue::getGlobalIdentifier(StringRef Name,
     128             :                                              GlobalValue::LinkageTypes Linkage,
     129             :                                              StringRef FileName) {
     130             : 
     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.
     134       22014 :   if (Name[0] == '\1')
     135          54 :     Name = Name.substr(1);
     136             : 
     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         805 :     if (FileName.empty())
     144           1 :       NewName = NewName.insert(0, "<unknown>:");
     145             :     else
     146        2412 :       NewName = NewName.insert(0, FileName.str() + ":");
     147             :   }
     148       11007 :   return NewName;
     149             : }
     150             : 
     151        7055 : std::string GlobalValue::getGlobalIdentifier() const {
     152             :   return getGlobalIdentifier(getName(), getLinkage(),
     153       14110 :                              getParent()->getSourceFileName());
     154             : }
     155             : 
     156      127173 : 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         132 :     if (const GlobalObject *GO = GA->getBaseObject())
     160             :       return GO->getSection();
     161           0 :     return "";
     162             :   }
     163             :   return cast<GlobalObject>(this)->getSection();
     164             : }
     165             : 
     166     1325454 : 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        1637 :     if (const GlobalObject *GO = GA->getBaseObject())
     170        1621 :       return const_cast<GlobalObject *>(GO)->getComdat();
     171             :     return nullptr;
     172             :   }
     173             :   // ifunc and its resolver are separate things so don't use resolver comdat.
     174     1323817 :   if (isa<GlobalIFunc>(this))
     175             :     return nullptr;
     176     1323809 :   return cast<GlobalObject>(this)->getComdat();
     177             : }
     178             : 
     179       25152 : StringRef GlobalObject::getSectionImpl() const {
     180             :   assert(hasSection());
     181       50304 :   return getContext().pImpl->GlobalObjectSections[this];
     182             : }
     183             : 
     184      330240 : void GlobalObject::setSection(StringRef S) {
     185             :   // Do nothing if we're clearing the section and it is already empty.
     186      330240 :   if (!hasSection() && S.empty())
     187             :     return;
     188             : 
     189             :   // Get or create a stable section name string and put it in the table in the
     190             :   // context.
     191       20431 :   if (!S.empty()) {
     192       20430 :     S = getContext().pImpl->SectionStrings.insert(S).first->first();
     193             :   }
     194       40862 :   getContext().pImpl->GlobalObjectSections[this] = S;
     195             : 
     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());
     199             : }
     200             : 
     201    38336485 : bool GlobalValue::isDeclaration() const {
     202             :   // Globals are definitions if they have an initializer.
     203             :   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
     204    25414278 :     return GV->getNumOperands() == 0;
     205             : 
     206             :   // Functions are definitions if they have a body.
     207             :   if (const Function *F = dyn_cast<Function>(this))
     208    17608086 :     return F->empty() && !F->isMaterializable();
     209             : 
     210             :   // Aliases and ifuncs are always definitions.
     211             :   assert(isa<GlobalIndirectSymbol>(this));
     212             :   return false;
     213             : }
     214             : 
     215       13632 : bool GlobalValue::canIncreaseAlignment() const {
     216             :   // Firstly, can only increase the alignment of a global if it
     217             :   // is a strong definition.
     218       13632 :   if (!isStrongDefinitionForLinker())
     219             :     return false;
     220             : 
     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       13514 :   if (hasSection() && getAlignment() > 0)
     226             :     return false;
     227             : 
     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.)
     238             :   //
     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.
     246             : 
     247             :   // Conservatively assume ELF if there's no parent pointer.
     248             :   bool isELF =
     249       53984 :       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
     250       26969 :   if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
     251             :     return false;
     252             : 
     253             :   return true;
     254             : }
     255             : 
     256       43440 : const GlobalObject *GlobalValue::getBaseObject() const {
     257             :   if (auto *GO = dyn_cast<GlobalObject>(this))
     258             :     return GO;
     259             :   if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
     260         634 :     return GA->getBaseObject();
     261             :   return nullptr;
     262             : }
     263             : 
     264      468452 : bool GlobalValue::isAbsoluteSymbolRef() const {
     265             :   auto *GO = dyn_cast<GlobalObject>(this);
     266             :   if (!GO)
     267             :     return false;
     268             : 
     269      468344 :   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
     270             : }
     271             : 
     272     1554585 : Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
     273             :   auto *GO = dyn_cast<GlobalObject>(this);
     274             :   if (!GO)
     275             :     return None;
     276             : 
     277     1554448 :   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
     278     1554448 :   if (!MD)
     279             :     return None;
     280             : 
     281          84 :   return getConstantRangeFromMetadata(*MD);
     282             : }
     283             : 
     284       18169 : bool GlobalValue::canBeOmittedFromSymbolTable() const {
     285       18169 :   if (!hasLinkOnceODRLinkage())
     286             :     return false;
     287             : 
     288             :   // We assume that anyone who sets global unnamed_addr on a non-constant
     289             :   // knows what they're doing.
     290        1917 :   if (hasGlobalUnnamedAddr())
     291             :     return true;
     292             : 
     293             :   // If it is a non constant variable, it needs to be uniqued across shared
     294             :   // objects.
     295             :   if (auto *Var = dyn_cast<GlobalVariable>(this))
     296          32 :     if (!Var->isConstant())
     297             :       return false;
     298             : 
     299         549 :   return hasAtLeastLocalUnnamedAddr();
     300             : }
     301             : 
     302             : //===----------------------------------------------------------------------===//
     303             : // GlobalVariable Implementation
     304             : //===----------------------------------------------------------------------===//
     305             : 
     306         139 : GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
     307             :                                Constant *InitVal, const Twine &Name,
     308             :                                ThreadLocalMode TLMode, unsigned AddressSpace,
     309         139 :                                bool isExternallyInitialized)
     310             :     : GlobalObject(Ty, Value::GlobalVariableVal,
     311             :                    OperandTraits<GlobalVariable>::op_begin(this),
     312             :                    InitVal != nullptr, Link, Name, AddressSpace),
     313             :       isConstantGlobal(constant),
     314         278 :       isExternallyInitializedConstant(isExternallyInitialized) {
     315             :   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
     316             :          "invalid type for global variable");
     317             :   setThreadLocalMode(TLMode);
     318         139 :   if (InitVal) {
     319             :     assert(InitVal->getType() == Ty &&
     320             :            "Initializer should be the same type as the GlobalVariable!");
     321             :     Op<0>() = InitVal;
     322             :   }
     323         139 : }
     324             : 
     325      203078 : GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
     326             :                                LinkageTypes Link, Constant *InitVal,
     327             :                                const Twine &Name, GlobalVariable *Before,
     328             :                                ThreadLocalMode TLMode, unsigned AddressSpace,
     329      203078 :                                bool isExternallyInitialized)
     330             :     : GlobalObject(Ty, Value::GlobalVariableVal,
     331             :                    OperandTraits<GlobalVariable>::op_begin(this),
     332             :                    InitVal != nullptr, Link, Name, AddressSpace),
     333             :       isConstantGlobal(constant),
     334      406156 :       isExternallyInitializedConstant(isExternallyInitialized) {
     335             :   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
     336             :          "invalid type for global variable");
     337             :   setThreadLocalMode(TLMode);
     338      203078 :   if (InitVal) {
     339             :     assert(InitVal->getType() == Ty &&
     340             :            "Initializer should be the same type as the GlobalVariable!");
     341             :     Op<0>() = InitVal;
     342             :   }
     343             : 
     344      203078 :   if (Before)
     345         351 :     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
     346             :   else
     347      202727 :     M.getGlobalList().push_back(this);
     348      203078 : }
     349             : 
     350         130 : void GlobalVariable::removeFromParent() {
     351         130 :   getParent()->getGlobalList().remove(getIterator());
     352         130 : }
     353             : 
     354        4205 : void GlobalVariable::eraseFromParent() {
     355        4205 :   getParent()->getGlobalList().erase(getIterator());
     356        4205 : }
     357             : 
     358       56905 : void GlobalVariable::setInitializer(Constant *InitVal) {
     359       56905 :   if (!InitVal) {
     360         106 :     if (hasInitializer()) {
     361             :       // Note, the num operands is used to compute the offset of the operand, so
     362             :       // the order here matters.  Clearing the operand then clearing the num
     363             :       // operands ensures we have the correct offset to the operand.
     364             :       Op<0>().set(nullptr);
     365             :       setGlobalVariableNumOperands(0);
     366             :     }
     367             :   } else {
     368             :     assert(InitVal->getType() == getValueType() &&
     369             :            "Initializer type must match GlobalVariable type");
     370             :     // Note, the num operands is used to compute the offset of the operand, so
     371             :     // the order here matters.  We need to set num operands to 1 first so that
     372             :     // we get the correct offset to the first operand when we set it.
     373       56799 :     if (!hasInitializer())
     374             :       setGlobalVariableNumOperands(1);
     375       56799 :     Op<0>().set(InitVal);
     376             :   }
     377       56905 : }
     378             : 
     379             : /// Copy all additional attributes (those not needed to create a GlobalVariable)
     380             : /// from the GlobalVariable Src to this one.
     381        1024 : void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
     382        1024 :   GlobalObject::copyAttributesFrom(Src);
     383             :   setThreadLocalMode(Src->getThreadLocalMode());
     384             :   setExternallyInitialized(Src->isExternallyInitialized());
     385             :   setAttributes(Src->getAttributes());
     386        1024 : }
     387             : 
     388      251961 : void GlobalVariable::dropAllReferences() {
     389      251961 :   User::dropAllReferences();
     390      251961 :   clearMetadata();
     391      251961 : }
     392             : 
     393             : //===----------------------------------------------------------------------===//
     394             : // GlobalIndirectSymbol Implementation
     395             : //===----------------------------------------------------------------------===//
     396             : 
     397        2810 : GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
     398             :     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
     399        2810 :     Constant *Symbol)
     400        5620 :     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
     401             :     Op<0>() = Symbol;
     402        2810 : }
     403             : 
     404             : 
     405             : //===----------------------------------------------------------------------===//
     406             : // GlobalAlias Implementation
     407             : //===----------------------------------------------------------------------===//
     408             : 
     409        2683 : GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
     410             :                          const Twine &Name, Constant *Aliasee,
     411        2683 :                          Module *ParentModule)
     412             :     : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
     413        2683 :                            Aliasee) {
     414        2683 :   if (ParentModule)
     415        1718 :     ParentModule->getAliasList().push_back(this);
     416        2683 : }
     417             : 
     418        2683 : GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
     419             :                                  LinkageTypes Link, const Twine &Name,
     420             :                                  Constant *Aliasee, Module *ParentModule) {
     421        2683 :   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
     422             : }
     423             : 
     424         967 : GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
     425             :                                  LinkageTypes Linkage, const Twine &Name,
     426             :                                  Module *Parent) {
     427         967 :   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
     428             : }
     429             : 
     430         228 : GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
     431             :                                  LinkageTypes Linkage, const Twine &Name,
     432             :                                  GlobalValue *Aliasee) {
     433         228 :   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
     434             : }
     435             : 
     436         228 : GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
     437             :                                  GlobalValue *Aliasee) {
     438             :   PointerType *PTy = Aliasee->getType();
     439         228 :   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
     440         228 :                 Aliasee);
     441             : }
     442             : 
     443           4 : GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
     444           4 :   return create(Aliasee->getLinkage(), Name, Aliasee);
     445             : }
     446             : 
     447           9 : void GlobalAlias::removeFromParent() {
     448           9 :   getParent()->getAliasList().remove(getIterator());
     449           9 : }
     450             : 
     451         110 : void GlobalAlias::eraseFromParent() {
     452         110 :   getParent()->getAliasList().erase(getIterator());
     453         110 : }
     454             : 
     455         117 : void GlobalAlias::setAliasee(Constant *Aliasee) {
     456             :   assert((!Aliasee || Aliasee->getType() == getType()) &&
     457             :          "Alias and aliasee types should match!");
     458             :   setIndirectSymbol(Aliasee);
     459         117 : }
     460             : 
     461             : //===----------------------------------------------------------------------===//
     462             : // GlobalIFunc Implementation
     463             : //===----------------------------------------------------------------------===//
     464             : 
     465         127 : GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
     466             :                          const Twine &Name, Constant *Resolver,
     467         127 :                          Module *ParentModule)
     468             :     : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
     469         127 :                            Resolver) {
     470         127 :   if (ParentModule)
     471          90 :     ParentModule->getIFuncList().push_back(this);
     472         127 : }
     473             : 
     474         127 : GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
     475             :                                  LinkageTypes Link, const Twine &Name,
     476             :                                  Constant *Resolver, Module *ParentModule) {
     477         127 :   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
     478             : }
     479             : 
     480           0 : void GlobalIFunc::removeFromParent() {
     481           0 :   getParent()->getIFuncList().remove(getIterator());
     482           0 : }
     483             : 
     484           7 : void GlobalIFunc::eraseFromParent() {
     485           7 :   getParent()->getIFuncList().erase(getIterator());
     486           7 : }

Generated by: LCOV version 1.13