LCOV - code coverage report
Current view: top level - lib/Target - TargetLoweringObjectFile.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 96 99 97.0 %
Date: 2017-09-14 15:23:50 Functions: 16 17 94.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
       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 classes used to handle lowerings specific to common
      11             : // object file formats.
      12             : //
      13             : //===----------------------------------------------------------------------===//
      14             : 
      15             : #include "llvm/Target/TargetLoweringObjectFile.h"
      16             : #include "llvm/BinaryFormat/Dwarf.h"
      17             : #include "llvm/IR/Constants.h"
      18             : #include "llvm/IR/DataLayout.h"
      19             : #include "llvm/IR/DerivedTypes.h"
      20             : #include "llvm/IR/Function.h"
      21             : #include "llvm/IR/GlobalVariable.h"
      22             : #include "llvm/IR/Mangler.h"
      23             : #include "llvm/MC/MCAsmInfo.h"
      24             : #include "llvm/MC/MCContext.h"
      25             : #include "llvm/MC/MCExpr.h"
      26             : #include "llvm/MC/MCStreamer.h"
      27             : #include "llvm/MC/MCSymbol.h"
      28             : #include "llvm/Support/ErrorHandling.h"
      29             : #include "llvm/Support/raw_ostream.h"
      30             : #include "llvm/Target/TargetLowering.h"
      31             : #include "llvm/Target/TargetMachine.h"
      32             : #include "llvm/Target/TargetOptions.h"
      33             : #include "llvm/Target/TargetSubtargetInfo.h"
      34             : using namespace llvm;
      35             : 
      36             : //===----------------------------------------------------------------------===//
      37             : //                              Generic Code
      38             : //===----------------------------------------------------------------------===//
      39             : 
      40             : /// Initialize - this method must be called before any actual lowering is
      41             : /// done.  This specifies the current context for codegen, and gives the
      42             : /// lowering implementations a chance to set up their default sections.
      43       16856 : void TargetLoweringObjectFile::Initialize(MCContext &ctx,
      44             :                                           const TargetMachine &TM) {
      45       16856 :   Ctx = &ctx;
      46             :   // `Initialize` can be called more than once.
      47       16914 :   delete Mang;
      48       33712 :   Mang = new Mangler();
      49       50568 :   InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), *Ctx,
      50       16856 :                        TM.getCodeModel() == CodeModel::Large);
      51       16856 : }
      52             : 
      53       75246 : TargetLoweringObjectFile::~TargetLoweringObjectFile() {
      54       41488 :   delete Mang;
      55       25082 : }
      56             : 
      57       66968 : static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
      58       66968 :   const Constant *C = GV->getInitializer();
      59             : 
      60             :   // Must have zero initializer.
      61       66968 :   if (!C->isNullValue())
      62             :     return false;
      63             : 
      64             :   // Leave constant zeros in readonly constant sections, so they can be shared.
      65       26490 :   if (GV->isConstant())
      66             :     return false;
      67             : 
      68             :   // If the global has an explicit section specified, don't put it in BSS.
      69       52562 :   if (GV->hasSection())
      70             :     return false;
      71             : 
      72             :   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
      73       26222 :   if (NoZerosInBSS)
      74             :     return false;
      75             : 
      76             :   // Otherwise, put it in BSS!
      77       26222 :   return true;
      78             : }
      79             : 
      80             : /// IsNullTerminatedString - Return true if the specified constant (which is
      81             : /// known to have a type that is an array of 1/2/4 byte elements) ends with a
      82             : /// nul value and contains no other nuls in it.  Note that this is more general
      83             : /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
      84       27616 : static bool IsNullTerminatedString(const Constant *C) {
      85             :   // First check: is we have constant array terminated with zero
      86       55116 :   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
      87       27500 :     unsigned NumElts = CDS->getNumElements();
      88             :     assert(NumElts != 0 && "Can't have an empty CDS");
      89             :     
      90       27500 :     if (CDS->getElementAsInteger(NumElts-1) != 0)
      91             :       return false; // Not null terminated.
      92             :     
      93             :     // Verify that the null doesn't occur anywhere else in the string.
      94     3075318 :     for (unsigned i = 0; i != NumElts-1; ++i)
      95     1523977 :       if (CDS->getElementAsInteger(i) == 0)
      96             :         return false;
      97             :     return true;
      98             :   }
      99             : 
     100             :   // Another possibility: [1 x i8] zeroinitializer
     101         232 :   if (isa<ConstantAggregateZero>(C))
     102         224 :     return cast<ArrayType>(C->getType())->getNumElements() == 1;
     103             : 
     104             :   return false;
     105             : }
     106             : 
     107         895 : MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
     108             :     const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
     109             :   assert(!Suffix.empty());
     110             : 
     111        1790 :   SmallString<60> NameStr;
     112        1790 :   NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
     113         895 :   TM.getNameWithPrefix(NameStr, GV, *Mang);
     114        1790 :   NameStr.append(Suffix.begin(), Suffix.end());
     115        2685 :   return Ctx->getOrCreateSymbol(NameStr);
     116             : }
     117             : 
     118         153 : MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
     119             :     const GlobalValue *GV, const TargetMachine &TM,
     120             :     MachineModuleInfo *MMI) const {
     121         153 :   return TM.getSymbol(GV);
     122             : }
     123             : 
     124          26 : void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
     125             :                                                     const DataLayout &,
     126             :                                                     const MCSymbol *Sym) const {
     127          26 : }
     128             : 
     129             : 
     130             : /// getKindForGlobal - This is a top-level target-independent classifier for
     131             : /// a global variable.  Given an global variable and information from TM, it
     132             : /// classifies the global in a variety of ways that make various target
     133             : /// implementations simpler.  The target implementation is free to ignore this
     134             : /// extra info of course.
     135      212243 : SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
     136             :                                                        const TargetMachine &TM){
     137             :   assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() &&
     138             :          "Can only be used for global definitions");
     139             : 
     140      212243 :   Reloc::Model ReloModel = TM.getRelocationModel();
     141             : 
     142             :   // Early exit - functions should be always in text sections.
     143       69495 :   const auto *GVar = dyn_cast<GlobalVariable>(GO);
     144             :   if (!GVar)
     145             :     return SectionKind::getText();
     146             : 
     147             :   // Handle thread-local data first.
     148      138990 :   if (GVar->isThreadLocal()) {
     149         276 :     if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
     150             :       return SectionKind::getThreadBSS();
     151             :     return SectionKind::getThreadData();
     152             :   }
     153             : 
     154             :   // Variables with common linkage always get classified as common.
     155      138438 :   if (GVar->hasCommonLinkage())
     156             :     return SectionKind::getCommon();
     157             : 
     158             :   // Variable can be easily put to BSS section.
     159       66692 :   if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
     160       30812 :     if (GVar->hasLocalLinkage())
     161             :       return SectionKind::getBSSLocal();
     162        9526 :     else if (GVar->hasExternalLinkage())
     163             :       return SectionKind::getBSSExtern();
     164             :     return SectionKind::getBSS();
     165             :   }
     166             : 
     167       40643 :   const Constant *C = GVar->getInitializer();
     168             : 
     169             :   // If the global is marked constant, we can put it into a mergable section,
     170             :   // a mergable string section, or general .data if it contains relocations.
     171       40643 :   if (GVar->isConstant()) {
     172             :     // If the initializer for the global contains something that requires a
     173             :     // relocation, then we may have to drop this into a writable data section
     174             :     // even though it is marked const.
     175       32304 :     if (!C->needsRelocation()) {
     176             :       // If the global is required to have a unique address, it can't be put
     177             :       // into a mergable section: just drop it into the general read-only
     178             :       // section instead.
     179       57248 :       if (!GVar->hasGlobalUnnamedAddr())
     180             :         return SectionKind::getReadOnly();
     181             : 
     182             :       // If initializer is a null-terminated string, put it in a "cstring"
     183             :       // section of the right width.
     184       55465 :       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
     185             :         if (IntegerType *ITy =
     186       55281 :               dyn_cast<IntegerType>(ATy->getElementType())) {
     187       27835 :           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
     188       55312 :                ITy->getBitWidth() == 32) &&
     189       27616 :               IsNullTerminatedString(C)) {
     190       27491 :             if (ITy->getBitWidth() == 8)
     191             :               return SectionKind::getMergeable1ByteCString();
     192          36 :             if (ITy->getBitWidth() == 16)
     193             :               return SectionKind::getMergeable2ByteCString();
     194             : 
     195             :             assert(ITy->getBitWidth() == 32 && "Unknown width");
     196             :             return SectionKind::getMergeable4ByteCString();
     197             :           }
     198             :         }
     199             :       }
     200             : 
     201             :       // Otherwise, just drop it into a mergable constant section.  If we have
     202             :       // a section for this size, use it, otherwise use the arbitrary sized
     203             :       // mergable section.
     204         317 :       switch (
     205         317 :           GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
     206             :       case 4:  return SectionKind::getMergeableConst4();
     207             :       case 8:  return SectionKind::getMergeableConst8();
     208             :       case 16: return SectionKind::getMergeableConst16();
     209             :       case 32: return SectionKind::getMergeableConst32();
     210             :       default:
     211             :         return SectionKind::getReadOnly();
     212             :       }
     213             : 
     214             :     } else {
     215             :       // In static, ROPI and RWPI relocation models, the linker will resolve
     216             :       // all addresses, so the relocation entries will actually be constants by
     217             :       // the time the app starts up.  However, we can't put this into a
     218             :       // mergable section, because the linker doesn't take relocations into
     219             :       // consideration when it tries to merge entries in the section.
     220        3680 :       if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
     221        3603 :           ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
     222             :         return SectionKind::getReadOnly();
     223             : 
     224             :       // Otherwise, the dynamic linker needs to fix it up, put it in the
     225             :       // writable data.rel section.
     226             :       return SectionKind::getReadOnlyWithRel();
     227             :     }
     228             :   }
     229             : 
     230             :   // Okay, this isn't a constant.
     231             :   return SectionKind::getData();
     232             : }
     233             : 
     234             : /// This method computes the appropriate section to emit the specified global
     235             : /// variable or function definition.  This should not be passed external (or
     236             : /// available externally) globals.
     237      206601 : MCSection *TargetLoweringObjectFile::SectionForGlobal(
     238             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     239             :   // Select section name.
     240      206601 :   if (GO->hasSection())
     241        1179 :     return getExplicitSectionGlobal(GO, Kind, TM);
     242             : 
     243       62879 :   if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
     244       62879 :     auto Attrs = GVar->getAttributes();
     245      188643 :     if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
     246      251505 :         (Attrs.hasAttribute("data-section") && Kind.isData()) ||
     247      125748 :         (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()))  {
     248          13 :        return getExplicitSectionGlobal(GO, Kind, TM);
     249             :     }
     250             :   }
     251             : 
     252      142543 :   if (auto *F = dyn_cast<Function>(GO)) {
     253      285086 :     if (F->hasFnAttribute("implicit-section-name"))
     254           2 :       return getExplicitSectionGlobal(GO, Kind, TM);
     255             :   }
     256             : 
     257             :   // Use default section depending on the 'type' of global
     258      205407 :   return SelectSectionForGlobal(GO, Kind, TM);
     259             : }
     260             : 
     261           7 : MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
     262             :     const Function &F, const TargetMachine &TM) const {
     263           7 :   unsigned Align = 0;
     264           7 :   return getSectionForConstant(F.getParent()->getDataLayout(),
     265             :                                SectionKind::getReadOnly(), /*C=*/nullptr,
     266          14 :                                Align);
     267             : }
     268             : 
     269          29 : bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
     270             :     bool UsesLabelDifference, const Function &F) const {
     271             :   // In PIC mode, we need to emit the jump table to the same section as the
     272             :   // function body itself, otherwise the label differences won't make sense.
     273             :   // FIXME: Need a better predicate for this: what about custom entries?
     274          29 :   if (UsesLabelDifference)
     275             :     return true;
     276             : 
     277             :   // We should also do if the section name is NULL or function is declared
     278             :   // in discardable section
     279             :   // FIXME: this isn't the right predicate, should be based on the MCSection
     280             :   // for the function.
     281          14 :   return F.isWeakForLinker();
     282             : }
     283             : 
     284             : /// Given a mergable constant with the specified size and relocation
     285             : /// information, return a section that it should be placed in.
     286           4 : MCSection *TargetLoweringObjectFile::getSectionForConstant(
     287             :     const DataLayout &DL, SectionKind Kind, const Constant *C,
     288             :     unsigned &Align) const {
     289           4 :   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
     290             :     return ReadOnlySection;
     291             : 
     292           0 :   return DataSection;
     293             : }
     294             : 
     295             : /// getTTypeGlobalReference - Return an MCExpr to use for a
     296             : /// reference to the specified global variable from exception
     297             : /// handling information.
     298          28 : const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
     299             :     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
     300             :     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
     301             :   const MCSymbolRefExpr *Ref =
     302          56 :       MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
     303             : 
     304          28 :   return getTTypeReference(Ref, Encoding, Streamer);
     305             : }
     306             : 
     307          89 : const MCExpr *TargetLoweringObjectFile::
     308             : getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
     309             :                   MCStreamer &Streamer) const {
     310          89 :   switch (Encoding & 0x70) {
     311           0 :   default:
     312           0 :     report_fatal_error("We do not support this DWARF encoding yet!");
     313             :   case dwarf::DW_EH_PE_absptr:
     314             :     // Do nothing special
     315             :     return Sym;
     316          61 :   case dwarf::DW_EH_PE_pcrel: {
     317             :     // Emit a label to the streamer for the current position.  This gives us
     318             :     // .-foo addressing.
     319          61 :     MCSymbol *PCSym = getContext().createTempSymbol();
     320          61 :     Streamer.EmitLabel(PCSym);
     321         122 :     const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
     322         122 :     return MCBinaryExpr::createSub(Sym, PC, getContext());
     323             :   }
     324             :   }
     325             : }
     326             : 
     327           1 : const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
     328             :   // FIXME: It's not clear what, if any, default this should have - perhaps a
     329             :   // null return could mean 'no location' & we should just do that here.
     330           2 :   return MCSymbolRefExpr::create(Sym, *Ctx);
     331             : }
     332             : 
     333       96092 : void TargetLoweringObjectFile::getNameWithPrefix(
     334             :     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
     335             :     const TargetMachine &TM) const {
     336       96092 :   Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
     337       96092 : }

Generated by: LCOV version 1.13