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

Generated by: LCOV version 1.13