LCOV - code coverage report
Current view: top level - lib/CodeGen/AsmPrinter - DwarfDebug.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 987 1008 97.9 %
Date: 2017-09-14 15:23:50 Functions: 82 82 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
       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 contains support for writing dwarf debug info into asm files.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "DwarfDebug.h"
      15             : #include "ByteStreamer.h"
      16             : #include "DIEHash.h"
      17             : #include "DebugLocEntry.h"
      18             : #include "DebugLocStream.h"
      19             : #include "DwarfAccelTable.h"
      20             : #include "DwarfCompileUnit.h"
      21             : #include "DwarfExpression.h"
      22             : #include "DwarfFile.h"
      23             : #include "DwarfUnit.h"
      24             : #include "llvm/ADT/APInt.h"
      25             : #include "llvm/ADT/DenseMap.h"
      26             : #include "llvm/ADT/DenseSet.h"
      27             : #include "llvm/ADT/MapVector.h"
      28             : #include "llvm/ADT/STLExtras.h"
      29             : #include "llvm/ADT/SmallVector.h"
      30             : #include "llvm/ADT/StringRef.h"
      31             : #include "llvm/ADT/Triple.h"
      32             : #include "llvm/ADT/Twine.h"
      33             : #include "llvm/BinaryFormat/Dwarf.h"
      34             : #include "llvm/CodeGen/AsmPrinter.h"
      35             : #include "llvm/CodeGen/DIE.h"
      36             : #include "llvm/CodeGen/LexicalScopes.h"
      37             : #include "llvm/CodeGen/MachineBasicBlock.h"
      38             : #include "llvm/CodeGen/MachineFunction.h"
      39             : #include "llvm/CodeGen/MachineInstr.h"
      40             : #include "llvm/CodeGen/MachineModuleInfo.h"
      41             : #include "llvm/CodeGen/MachineOperand.h"
      42             : #include "llvm/IR/Constants.h"
      43             : #include "llvm/IR/DebugInfoMetadata.h"
      44             : #include "llvm/IR/DebugLoc.h"
      45             : #include "llvm/IR/Function.h"
      46             : #include "llvm/IR/GlobalVariable.h"
      47             : #include "llvm/IR/Module.h"
      48             : #include "llvm/MC/MCAsmInfo.h"
      49             : #include "llvm/MC/MCContext.h"
      50             : #include "llvm/MC/MCDwarf.h"
      51             : #include "llvm/MC/MCSection.h"
      52             : #include "llvm/MC/MCStreamer.h"
      53             : #include "llvm/MC/MCSymbol.h"
      54             : #include "llvm/MC/MCTargetOptions.h"
      55             : #include "llvm/MC/MachineLocation.h"
      56             : #include "llvm/MC/SectionKind.h"
      57             : #include "llvm/Pass.h"
      58             : #include "llvm/Support/Casting.h"
      59             : #include "llvm/Support/CommandLine.h"
      60             : #include "llvm/Support/Debug.h"
      61             : #include "llvm/Support/ErrorHandling.h"
      62             : #include "llvm/Support/MD5.h"
      63             : #include "llvm/Support/MathExtras.h"
      64             : #include "llvm/Support/Timer.h"
      65             : #include "llvm/Support/raw_ostream.h"
      66             : #include "llvm/Target/TargetLoweringObjectFile.h"
      67             : #include "llvm/Target/TargetMachine.h"
      68             : #include "llvm/Target/TargetOptions.h"
      69             : #include "llvm/Target/TargetRegisterInfo.h"
      70             : #include "llvm/Target/TargetSubtargetInfo.h"
      71             : #include <algorithm>
      72             : #include <cassert>
      73             : #include <cstddef>
      74             : #include <cstdint>
      75             : #include <iterator>
      76             : #include <string>
      77             : #include <utility>
      78             : #include <vector>
      79             : 
      80             : using namespace llvm;
      81             : 
      82             : #define DEBUG_TYPE "dwarfdebug"
      83             : 
      84             : static cl::opt<bool>
      85       72306 : DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
      86      144612 :                          cl::desc("Disable debug info printing"));
      87             : 
      88       72306 : static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
      89             :     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
      90      216918 :     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
      91             : 
      92       72306 : static cl::opt<bool> GenerateARangeSection("generate-arange-section",
      93             :                                            cl::Hidden,
      94      216918 :                                            cl::desc("Generate dwarf aranges"),
      95      289224 :                                            cl::init(false));
      96             : 
      97       72306 : static cl::opt<bool> SplitDwarfCrossCuReferences(
      98             :     "split-dwarf-cross-cu-references", cl::Hidden,
      99      216918 :     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
     100             : 
     101             : enum DefaultOnOff { Default, Enable, Disable };
     102             : 
     103       72306 : static cl::opt<DefaultOnOff> UnknownLocations(
     104             :     "use-unknown-locations", cl::Hidden,
     105      216918 :     cl::desc("Make an absence of debug location information explicit."),
     106      506142 :     cl::values(clEnumVal(Default, "At top of block or after label"),
     107             :                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
     108      289224 :     cl::init(Default));
     109             : 
     110             : static cl::opt<DefaultOnOff>
     111       72306 : DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
     112      216918 :                  cl::desc("Output prototype dwarf accelerator tables."),
     113      506142 :                  cl::values(clEnumVal(Default, "Default for platform"),
     114             :                             clEnumVal(Enable, "Enabled"),
     115             :                             clEnumVal(Disable, "Disabled")),
     116      289224 :                  cl::init(Default));
     117             : 
     118             : enum LinkageNameOption {
     119             :   DefaultLinkageNames,
     120             :   AllLinkageNames,
     121             :   AbstractLinkageNames
     122             : };
     123             : 
     124             : static cl::opt<LinkageNameOption>
     125       72306 :     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
     126      216918 :                       cl::desc("Which DWARF linkage-name attributes to emit."),
     127      506142 :                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
     128             :                                             "Default for platform"),
     129             :                                  clEnumValN(AllLinkageNames, "All", "All"),
     130             :                                  clEnumValN(AbstractLinkageNames, "Abstract",
     131             :                                             "Abstract subprograms")),
     132      289224 :                       cl::init(DefaultLinkageNames));
     133             : 
     134             : static const char *const DWARFGroupName = "dwarf";
     135             : static const char *const DWARFGroupDescription = "DWARF Emission";
     136             : static const char *const DbgTimerName = "writer";
     137             : static const char *const DbgTimerDescription = "DWARF Debug Writer";
     138             : 
     139       14119 : void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
     140       28238 :   BS.EmitInt8(
     141       45025 :       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
     142       41690 :                   : dwarf::OperationEncodingString(Op));
     143       14119 : }
     144             : 
     145        1755 : void DebugLocDwarfExpression::emitSigned(int64_t Value) {
     146        3510 :   BS.EmitSLEB128(Value, Twine(Value));
     147        1755 : }
     148             : 
     149         616 : void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
     150        1232 :   BS.EmitULEB128(Value, Twine(Value));
     151         616 : }
     152             : 
     153        1716 : bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
     154             :                                               unsigned MachineReg) {
     155             :   // This information is not available while emitting .debug_loc entries.
     156        1716 :   return false;
     157             : }
     158             : 
     159         172 : bool DbgVariable::isBlockByrefVariable() const {
     160             :   assert(Var && "Invalid complex DbgVariable!");
     161         688 :   return Var->getType().resolve()->isBlockByrefStruct();
     162             : }
     163             : 
     164       27653 : const DIType *DbgVariable::getType() const {
     165       82959 :   DIType *Ty = Var->getType().resolve();
     166             :   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
     167             :   // addresses instead.
     168       27653 :   if (Ty->isBlockByrefStruct()) {
     169             :     /* Byref variables, in Blocks, are declared by the programmer as
     170             :        "SomeType VarName;", but the compiler creates a
     171             :        __Block_byref_x_VarName struct, and gives the variable VarName
     172             :        either the struct, or a pointer to the struct, as its type.  This
     173             :        is necessary for various behind-the-scenes things the compiler
     174             :        needs to do with by-reference variables in blocks.
     175             : 
     176             :        However, as far as the original *programmer* is concerned, the
     177             :        variable should still have type 'SomeType', as originally declared.
     178             : 
     179             :        The following function dives into the __Block_byref_x_VarName
     180             :        struct to find the original type of the variable.  This will be
     181             :        passed back to the code generating the type for the Debug
     182             :        Information Entry for the variable 'VarName'.  'VarName' will then
     183             :        have the original type 'SomeType' in its debug information.
     184             : 
     185             :        The original type 'SomeType' will be the type of the field named
     186             :        'VarName' inside the __Block_byref_x_VarName struct.
     187             : 
     188             :        NOTE: In order for this to not completely fail on the debugger
     189             :        side, the Debug Information Entry for the variable VarName needs to
     190             :        have a DW_AT_location that tells the debugger how to unwind through
     191             :        the pointers and __Block_byref_x_VarName struct to find the actual
     192             :        value of the variable.  The function addBlockByrefType does this.  */
     193           3 :     DIType *subType = Ty;
     194           3 :     uint16_t tag = Ty->getTag();
     195             : 
     196           3 :     if (tag == dwarf::DW_TAG_pointer_type)
     197           0 :       subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
     198             : 
     199           6 :     auto Elements = cast<DICompositeType>(subType)->getElements();
     200          24 :     for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
     201          42 :       auto *DT = cast<DIDerivedType>(Elements[i]);
     202          42 :       if (getName() == DT->getName())
     203           3 :         return resolve(DT->getBaseType());
     204             :     }
     205             :   }
     206             :   return Ty;
     207             : }
     208             : 
     209         442 : ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
     210         884 :   if (FrameIndexExprs.size() == 1)
     211         878 :     return FrameIndexExprs;
     212             : 
     213             :   assert(llvm::all_of(FrameIndexExprs,
     214             :                       [](const FrameIndexExpr &A) {
     215             :                         return A.Expr->isFragment();
     216             :                       }) &&
     217             :          "multiple FI expressions without DW_OP_LLVM_fragment");
     218           6 :   std::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(),
     219           5 :             [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
     220          20 :               return A.Expr->getFragmentInfo()->OffsetInBits <
     221          25 :                      B.Expr->getFragmentInfo()->OffsetInBits;
     222             :             });
     223           6 :   return FrameIndexExprs;
     224             : }
     225             : 
     226             : static const DwarfAccelTable::Atom TypeAtoms[] = {
     227             :     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
     228             :     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
     229             :     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
     230             : 
     231       16474 : DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
     232       32948 :     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
     233             :       InfoHolder(A, "info_string", DIEValueAllocator),
     234             :       SkeletonHolder(A, "skel_string", DIEValueAllocator),
     235       32948 :       IsDarwin(A->TM.getTargetTriple().isOSDarwin()),
     236       16474 :       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
     237             :                                        dwarf::DW_FORM_data4)),
     238       16474 :       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
     239             :                                       dwarf::DW_FORM_data4)),
     240       16474 :       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
     241             :                                            dwarf::DW_FORM_data4)),
     242      461272 :       AccelTypes(TypeAtoms) {
     243       32948 :   const Triple &TT = Asm->TM.getTargetTriple();
     244             : 
     245             :   // Make sure we know our "debugger tuning."  The target option takes
     246             :   // precedence; fall back to triple-based defaults.
     247       16474 :   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
     248         173 :     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
     249       16301 :   else if (IsDarwin)
     250        2382 :     DebuggerTuning = DebuggerKind::LLDB;
     251          23 :   else if (TT.isPS4CPU())
     252          23 :     DebuggerTuning = DebuggerKind::SCE;
     253             :   else
     254       13896 :     DebuggerTuning = DebuggerKind::GDB;
     255             : 
     256             :   // Turn on accelerator tables for LLDB by default.
     257       16474 :   if (DwarfAccelTables == Default)
     258       32938 :     HasDwarfAccelTables = tuneForLLDB();
     259             :   else
     260           5 :     HasDwarfAccelTables = DwarfAccelTables == Enable;
     261             : 
     262       32948 :   HasAppleExtensionAttributes = tuneForLLDB();
     263             : 
     264             :   // Handle split DWARF.
     265       32948 :   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
     266             : 
     267             :   // SCE defaults to linkage names only for abstract subprograms.
     268       16474 :   if (DwarfLinkageNames == DefaultLinkageNames)
     269       16464 :     UseAllLinkageNames = !tuneForSCE();
     270             :   else
     271          10 :     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
     272             : 
     273       16474 :   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
     274       32908 :   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
     275       32908 :                                     : MMI->getModule()->getDwarfVersion();
     276             :   // Use dwarf 4 by default if nothing is requested.
     277       16474 :   DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
     278             : 
     279             :   // Work around a GDB bug. GDB doesn't support the standard opcode;
     280             :   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
     281             :   // is defined as of DWARF 3.
     282             :   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
     283             :   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
     284       16474 :   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
     285             : 
     286             :   // GDB does not fully support the DWARF 4 representation for bitfields.
     287       16474 :   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
     288             : 
     289       49422 :   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
     290       16474 : }
     291             : 
     292             : // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
     293             : DwarfDebug::~DwarfDebug() = default;
     294             : 
     295             : static bool isObjCClass(StringRef Name) {
     296      185286 :   return Name.startswith("+") || Name.startswith("-");
     297             : }
     298             : 
     299          23 : static bool hasObjCCategory(StringRef Name) {
     300             :   if (!isObjCClass(Name))
     301             :     return false;
     302             : 
     303          23 :   return Name.find(") ") != StringRef::npos;
     304             : }
     305             : 
     306          23 : static void getObjCClassCategory(StringRef In, StringRef &Class,
     307             :                                  StringRef &Category) {
     308          23 :   if (!hasObjCCategory(In)) {
     309          69 :     Class = In.slice(In.find('[') + 1, In.find(' '));
     310          23 :     Category = "";
     311          23 :     return;
     312             :   }
     313             : 
     314           0 :   Class = In.slice(In.find('[') + 1, In.find('('));
     315           0 :   Category = In.slice(In.find('[') + 1, In.find(' '));
     316             : }
     317             : 
     318          23 : static StringRef getObjCMethodName(StringRef In) {
     319          69 :   return In.slice(In.find(' ') + 1, In.find(']'));
     320             : }
     321             : 
     322             : // Add the various names to the Dwarf accelerator table names.
     323             : // TODO: Determine whether or not we should add names for programs
     324             : // that do not have a DW_AT_name or DW_AT_linkage_name field - this
     325             : // is only slightly different than the lookup of non-standard ObjC names.
     326       92623 : void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
     327       92623 :   if (!SP->isDefinition())
     328             :     return;
     329       92623 :   addAccelName(SP->getName(), Die);
     330             : 
     331             :   // If the linkage name is different than the name, go ahead and output
     332             :   // that as well into the name table.
     333      460397 :   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
     334       91671 :     addAccelName(SP->getLinkageName(), Die);
     335             : 
     336             :   // If this is an Objective-C selector name add it to the ObjC accelerator
     337             :   // too.
     338       92623 :   if (isObjCClass(SP->getName())) {
     339          23 :     StringRef Class, Category;
     340          23 :     getObjCClassCategory(SP->getName(), Class, Category);
     341          23 :     addAccelObjC(Class, Die);
     342          23 :     if (Category != "")
     343           0 :       addAccelObjC(Category, Die);
     344             :     // Also add the base method name to the name table.
     345          23 :     addAccelName(getObjCMethodName(SP->getName()), Die);
     346             :   }
     347             : }
     348             : 
     349             : /// Check whether we should create a DIE for the given Scope, return true
     350             : /// if we don't create a DIE (the corresponding DIE is null).
     351        6578 : bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
     352        6578 :   if (Scope->isAbstractScope())
     353             :     return false;
     354             : 
     355             :   // We don't create a DIE if there is no Range.
     356        5422 :   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
     357        5422 :   if (Ranges.empty())
     358             :     return true;
     359             : 
     360       10844 :   if (Ranges.size() > 1)
     361             :     return false;
     362             : 
     363             :   // We don't create a DIE if we have a single Range and the end label
     364             :   // is null.
     365        5902 :   return !getLabelAfterInsn(Ranges.front().second);
     366             : }
     367             : 
     368        5086 : template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
     369        5086 :   F(CU);
     370        5086 :   if (auto *SkelCU = CU.getSkeleton())
     371          35 :     if (CU.getCUNode()->getSplitDebugInlining())
     372             :       F(*SkelCU);
     373        5086 : }
     374             : 
     375         679 : bool DwarfDebug::shareAcrossDWOCUs() const {
     376         679 :   return SplitDwarfCrossCuReferences;
     377             : }
     378             : 
     379       36331 : void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
     380             :                                                      LexicalScope *Scope) {
     381             :   assert(Scope && Scope->getScopeNode());
     382             :   assert(Scope->isAbstractScope());
     383             :   assert(!Scope->getInlinedAt());
     384             : 
     385       72662 :   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
     386             : 
     387             :   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
     388             :   // was inlined from another compile unit.
     389       36336 :   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
     390             :     // Avoid building the original CU if it won't be used
     391           2 :     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
     392             :   else {
     393       36329 :     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
     394       36329 :     if (auto *SkelCU = CU.getSkeleton()) {
     395           5 :       (shareAcrossDWOCUs() ? CU : SrcCU)
     396           5 :           .constructAbstractSubprogramScopeDIE(Scope);
     397           5 :       if (CU.getCUNode()->getSplitDebugInlining())
     398           5 :         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
     399             :     } else
     400       36324 :       CU.constructAbstractSubprogramScopeDIE(Scope);
     401             :   }
     402       36331 : }
     403             : 
     404         738 : void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
     405         738 :   if (!U.hasDwarfPubSections())
     406             :     return;
     407             : 
     408         436 :   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
     409             : }
     410             : 
     411             : // Create new DwarfCompileUnit for the given metadata node with tag
     412             : // DW_TAG_compile_unit.
     413             : DwarfCompileUnit &
     414       47848 : DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
     415       47848 :   if (auto *CU = CUMap.lookup(DIUnit))
     416             :     return *CU;
     417         738 :   StringRef FN = DIUnit->getFilename();
     418         738 :   CompilationDir = DIUnit->getDirectory();
     419             : 
     420             :   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
     421        2952 :       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
     422         738 :   DwarfCompileUnit &NewCU = *OwnedUnit;
     423        1476 :   DIE &Die = NewCU.getUnitDie();
     424        1476 :   InfoHolder.addUnit(std::move(OwnedUnit));
     425         738 :   if (useSplitDwarf()) {
     426          54 :     NewCU.setSkeleton(constructSkeletonCU(NewCU));
     427          81 :     NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
     428          27 :                   Asm->TM.Options.MCOptions.SplitDwarfFile);
     429             :   }
     430             : 
     431        9861 :   for (auto *IE : DIUnit->getImportedEntities())
     432        6909 :     NewCU.addImportedEntity(IE);
     433             : 
     434             :   // LTO with assembly output shares a single line table amongst multiple CUs.
     435             :   // To avoid the compilation directory being ambiguous, let the line table
     436             :   // explicitly describe the directory of all files, never relying on the
     437             :   // compilation directory.
     438        1476 :   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
     439        1440 :     Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
     440             :         NewCU.getUniqueID(), CompilationDir);
     441             : 
     442        1476 :   StringRef Producer = DIUnit->getProducer();
     443        1476 :   StringRef Flags = DIUnit->getFlags();
     444         738 :   if (!Flags.empty()) {
     445           6 :     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
     446           2 :     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
     447             :   } else
     448         737 :     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
     449             : 
     450        2952 :   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
     451         738 :                 DIUnit->getSourceLanguage());
     452         738 :   NewCU.addString(Die, dwarf::DW_AT_name, FN);
     453             : 
     454         738 :   if (!useSplitDwarf()) {
     455         711 :     NewCU.initStmtList();
     456             : 
     457             :     // If we're using split dwarf the compilation dir is going to be in the
     458             :     // skeleton CU and so we don't need to duplicate it here.
     459        1422 :     if (!CompilationDir.empty())
     460         663 :       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
     461             : 
     462         711 :     addGnuPubAttributes(NewCU, Die);
     463             :   }
     464             : 
     465         738 :   if (useAppleExtensionAttributes()) {
     466         197 :     if (DIUnit->isOptimized())
     467          85 :       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
     468             : 
     469         394 :     StringRef Flags = DIUnit->getFlags();
     470         197 :     if (!Flags.empty())
     471           0 :       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
     472             : 
     473         197 :     if (unsigned RVer = DIUnit->getRuntimeVersion())
     474          45 :       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
     475             :                     dwarf::DW_FORM_data1, RVer);
     476             :   }
     477             : 
     478         738 :   if (useSplitDwarf())
     479          27 :     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
     480             :   else
     481         711 :     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
     482             : 
     483         738 :   if (DIUnit->getDWOId()) {
     484             :     // This CU is either a clang module DWO or a skeleton CU.
     485          81 :     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
     486             :                   DIUnit->getDWOId());
     487          54 :     if (!DIUnit->getSplitDebugFilename().empty())
     488             :       // This is a prefabricated skeleton CU.
     489          10 :       NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
     490             :                       DIUnit->getSplitDebugFilename());
     491             :   }
     492             : 
     493        1476 :   CUMap.insert({DIUnit, &NewCU});
     494        2214 :   CUDieMap.insert({&Die, &NewCU});
     495             :   return NewCU;
     496             : }
     497             : 
     498        6907 : void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
     499             :                                                   const DIImportedEntity *N) {
     500        6907 :   if (isa<DILocalScope>(N->getScope()))
     501             :     return;
     502       13784 :   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
     503        6892 :     D->addChild(TheCU.constructImportedEntityDIE(N));
     504             : }
     505             : 
     506             : /// Sort and unique GVEs by comparing their fragment offset.
     507             : static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
     508         429 : sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
     509        1716 :   std::sort(GVEs.begin(), GVEs.end(),
     510           9 :             [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
     511           9 :               if (A.Expr != B.Expr && A.Expr && B.Expr) {
     512          18 :                 auto FragmentA = A.Expr->getFragmentInfo();
     513          18 :                 auto FragmentB = B.Expr->getFragmentInfo();
     514           9 :                 if (FragmentA && FragmentB)
     515          27 :                   return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
     516             :               }
     517             :               return false;
     518             :             });
     519        1716 :   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
     520             :                          [](DwarfCompileUnit::GlobalExpr A,
     521             :                             DwarfCompileUnit::GlobalExpr B) {
     522             :                            return A.Expr == B.Expr;
     523             :                          }),
     524         858 :              GVEs.end());
     525         429 :   return GVEs;
     526             : }
     527             : 
     528             : // Emit all Dwarf sections that should come prior to the content. Create
     529             : // global DIEs and emit initial debug info sections. This is invoked by
     530             : // the target AsmPrinter.
     531       16474 : void DwarfDebug::beginModule() {
     532             :   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
     533       98844 :                      DWARFGroupDescription, TimePassesIsEnabled);
     534       16474 :   if (DisableDebugInfoPrinting)
     535           0 :     return;
     536             : 
     537       16474 :   const Module *M = MMI->getModule();
     538             : 
     539       32948 :   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
     540       16474 :                                        M->debug_compile_units_end());
     541             :   // Tell MMI whether we have debug info.
     542       32948 :   MMI->setDebugInfoAvailability(NumDebugCUs > 0);
     543       16474 :   SingleCU = NumDebugCUs == 1;
     544             :   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
     545       32948 :       GVMap;
     546       87040 :   for (const GlobalVariable &Global : M->globals()) {
     547      141132 :     SmallVector<DIGlobalVariableExpression *, 1> GVs;
     548       70566 :     Global.getDebugInfo(GVs);
     549      211993 :     for (auto *GVE : GVs)
     550         885 :       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
     551             :   }
     552             : 
     553       16474 :   for (DICompileUnit *CUNode : M->debug_compile_units()) {
     554             :     // FIXME: Move local imported entities into a list attached to the
     555             :     // subprogram, then this search won't be needed and a
     556             :     // getImportedEntities().empty() test should go below with the rest.
     557             :     bool HasNonLocalImportedEntities = llvm::any_of(
     558        1548 :         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
     559          35 :           return !isa<DILocalScope>(IE->getScope());
     560         809 :         });
     561             : 
     562        1204 :     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
     563         726 :         CUNode->getRetainedTypes().empty() &&
     564        1836 :         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
     565         461 :       continue;
     566             : 
     567         313 :     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
     568             : 
     569             :     // Global Variables.
     570        1374 :     for (auto *GVE : CUNode->getGlobalVariables()) {
     571             :       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
     572             :       // already know about the variable and it isn't adding a constant
     573             :       // expression.
     574         870 :       auto &GVMapEntry = GVMap[GVE->getVariable()];
     575         435 :       auto *Expr = GVE->getExpression();
     576         870 :       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
     577         142 :         GVMapEntry.push_back({nullptr, Expr});
     578             :     }
     579         626 :     DenseSet<DIGlobalVariable *> Processed;
     580        1374 :     for (auto *GVE : CUNode->getGlobalVariables()) {
     581         435 :       DIGlobalVariable *GV = GVE->getVariable();
     582         435 :       if (Processed.insert(GV).second)
     583         858 :         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
     584             :     }
     585             : 
     586        1046 :     for (auto *Ty : CUNode->getEnumTypes()) {
     587             :       // The enum types array by design contains pointers to
     588             :       // MDNodes rather than DIRefs. Unique them here.
     589         214 :       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
     590             :     }
     591        1703 :     for (auto *Ty : CUNode->getRetainedTypes()) {
     592             :       // The retained types array by design contains pointers to
     593             :       // MDNodes rather than DIRefs. Unique them here.
     594         733 :       if (DIType *RT = dyn_cast<DIType>(Ty))
     595             :           // There is no point in force-emitting a forward declaration.
     596         733 :           CU.getOrCreateTypeDIE(RT);
     597             :     }
     598             :     // Emit imported_modules last so that the relevant context is already
     599             :     // available.
     600        7846 :     for (auto *IE : CUNode->getImportedEntities())
     601        6907 :       constructAndAddImportedEntityDIE(CU, IE);
     602             :   }
     603             : }
     604             : 
     605         725 : void DwarfDebug::finishVariableDefinitions() {
     606       12794 :   for (const auto &Var : ConcreteVariables) {
     607       10619 :     DIE *VariableDie = Var->getDIE();
     608             :     assert(VariableDie);
     609             :     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
     610             :     // in the ConcreteVariables list, rather than looking it up again here.
     611             :     // DIE::getUnit isn't simple - it walks parent pointers, etc.
     612       21238 :     DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie());
     613             :     assert(Unit);
     614       10619 :     Unit->finishVariableDefinition(*Var);
     615             :   }
     616         725 : }
     617             : 
     618         725 : void DwarfDebug::finishSubprogramDefinitions() {
     619        7261 :   for (const DISubprogram *SP : ProcessedSPNodes) {
     620             :     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
     621       10172 :     forBothCUs(
     622       10172 :         getOrCreateDwarfCompileUnit(SP->getUnit()),
     623        5119 :         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
     624             :   }
     625         725 : }
     626             : 
     627         725 : void DwarfDebug::finalizeModuleInfo() {
     628         725 :   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
     629             : 
     630         725 :   finishSubprogramDefinitions();
     631             : 
     632         725 :   finishVariableDefinitions();
     633             : 
     634             :   // Include the DWO file name in the hash if there's more than one CU.
     635             :   // This handles ThinLTO's situation where imported CUs may very easily be
     636             :   // duplicate with the same CU partially imported into another ThinLTO unit.
     637         725 :   StringRef DWOName;
     638        1450 :   if (CUMap.size() > 1)
     639          84 :     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
     640             : 
     641             :   // Handle anything that needs to be done on a per-unit basis after
     642             :   // all other generation.
     643        1455 :   for (const auto &P : CUMap) {
     644         730 :     auto &TheCU = *P.second;
     645             :     // Emit DW_AT_containing_type attribute to connect types with their
     646             :     // vtable holding type.
     647         730 :     TheCU.constructContainingTypeDIEs();
     648             : 
     649             :     // Add CU specific attributes if we need to add any.
     650             :     // If we're splitting the dwarf out now that we've got the entire
     651             :     // CU then add the dwo id to it.
     652         730 :     auto *SkCU = TheCU.getSkeleton();
     653         730 :     if (useSplitDwarf()) {
     654             :       // Emit a unique identifier for this CU.
     655             :       uint64_t ID =
     656         108 :           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
     657          81 :       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
     658             :                     dwarf::DW_FORM_data8, ID);
     659          81 :       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
     660             :                     dwarf::DW_FORM_data8, ID);
     661             : 
     662             :       // We don't keep track of which addresses are used in which CU so this
     663             :       // is a bit pessimistic under LTO.
     664          54 :       if (!AddrPool.isEmpty()) {
     665          24 :         const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
     666          24 :         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
     667          48 :                               Sym, Sym);
     668             :       }
     669          27 :       if (!SkCU->getRangeLists().empty()) {
     670           2 :         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
     671           2 :         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
     672           4 :                               Sym, Sym);
     673             :       }
     674             :     }
     675             : 
     676             :     // If we have code split among multiple sections or non-contiguous
     677             :     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
     678             :     // remain in the .o file, otherwise add a DW_AT_low_pc.
     679             :     // FIXME: We should use ranges allow reordering of code ala
     680             :     // .subsections_via_symbols in mach-o. This would mean turning on
     681             :     // ranges for all subprogram DIEs for mach-o.
     682         730 :     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
     683        1460 :     if (unsigned NumRanges = TheCU.getRanges().size()) {
     684         581 :       if (NumRanges > 1)
     685             :         // A DW_AT_low_pc attribute may also be specified in combination with
     686             :         // DW_AT_ranges to specify the default base address for use in
     687             :         // location lists (see Section 2.6.2) and range lists (see Section
     688             :         // 2.17.3).
     689         240 :         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
     690             :       else
     691        1002 :         U.setBaseAddress(TheCU.getRanges().front().getStart());
     692        1743 :       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
     693             :     }
     694             : 
     695        1460 :     auto *CUNode = cast<DICompileUnit>(P.first);
     696             :     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
     697        1460 :     if (CUNode->getMacros())
     698           2 :       U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
     699           2 :                         U.getMacroLabelBegin(),
     700           6 :                         TLOF.getDwarfMacinfoSection()->getBeginSymbol());
     701             :   }
     702             : 
     703             :   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
     704         725 :   for (auto *CUNode : MMI->getModule()->debug_compile_units())
     705         773 :     if (CUNode->getDWOId())
     706          27 :       getOrCreateDwarfCompileUnit(CUNode);
     707             : 
     708             :   // Compute DIE offsets and sizes.
     709         725 :   InfoHolder.computeSizeAndOffsets();
     710         725 :   if (useSplitDwarf())
     711          23 :     SkeletonHolder.computeSizeAndOffsets();
     712         725 : }
     713             : 
     714             : // Emit all Dwarf sections that should come after the content.
     715       16378 : void DwarfDebug::endModule() {
     716             :   assert(CurFn == nullptr);
     717             :   assert(CurMI == nullptr);
     718             : 
     719             :   // If we aren't actually generating debug info (check beginModule -
     720             :   // conditionalized on !DisableDebugInfoPrinting and the presence of the
     721             :   // llvm.dbg.cu metadata node)
     722       16378 :   if (!MMI->hasDebugInfo())
     723             :     return;
     724             : 
     725             :   // Finalize the debug info for the module.
     726         725 :   finalizeModuleInfo();
     727             : 
     728         725 :   emitDebugStr();
     729             : 
     730         725 :   if (useSplitDwarf())
     731          23 :     emitDebugLocDWO();
     732             :   else
     733             :     // Emit info into a debug loc section.
     734         702 :     emitDebugLoc();
     735             : 
     736             :   // Corresponding abbreviations into a abbrev section.
     737         725 :   emitAbbreviations();
     738             : 
     739             :   // Emit all the DIEs into a debug info section.
     740         725 :   emitDebugInfo();
     741             : 
     742             :   // Emit info into a debug aranges section.
     743         725 :   if (GenerateARangeSection)
     744           6 :     emitDebugARanges();
     745             : 
     746             :   // Emit info into a debug ranges section.
     747         725 :   emitDebugRanges();
     748             : 
     749             :   // Emit info into a debug macinfo section.
     750         725 :   emitDebugMacinfo();
     751             : 
     752         725 :   if (useSplitDwarf()) {
     753          23 :     emitDebugStrDWO();
     754          23 :     emitDebugInfoDWO();
     755          23 :     emitDebugAbbrevDWO();
     756          23 :     emitDebugLineDWO();
     757             :     // Emit DWO addresses.
     758          23 :     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
     759             :   }
     760             : 
     761             :   // Emit info into the dwarf accelerator table sections.
     762         725 :   if (useDwarfAccelTables()) {
     763         200 :     emitAccelNames();
     764         200 :     emitAccelObjC();
     765         200 :     emitAccelNamespaces();
     766         200 :     emitAccelTypes();
     767             :   }
     768             : 
     769             :   // Emit the pubnames and pubtypes sections if requested.
     770         725 :   emitDebugPubSections();
     771             : 
     772             :   // clean up.
     773             :   // FIXME: AbstractVariables.clear();
     774             : }
     775             : 
     776       11092 : void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV,
     777             :                                                  const MDNode *ScopeNode) {
     778       11092 :   const DILocalVariable *Cleansed = nullptr;
     779       11092 :   if (CU.getExistingAbstractVariable(IV, Cleansed))
     780        7796 :     return;
     781             : 
     782        6592 :   CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
     783             :                                        cast<DILocalScope>(ScopeNode)));
     784             : }
     785             : 
     786       10624 : void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU,
     787             :     InlinedVariable IV, const MDNode *ScopeNode) {
     788       10624 :   const DILocalVariable *Cleansed = nullptr;
     789       10624 :   if (CU.getExistingAbstractVariable(IV, Cleansed))
     790        5791 :     return;
     791             : 
     792        4833 :   if (LexicalScope *Scope =
     793       14499 :           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
     794        2419 :     CU.createAbstractVariable(Cleansed, Scope);
     795             : }
     796             : 
     797             : // Collect variable information from side table maintained by MF.
     798        6093 : void DwarfDebug::collectVariableInfoFromMFTable(
     799             :     DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) {
     800       12186 :   SmallDenseMap<InlinedVariable, DbgVariable *> MFVars;
     801       18729 :   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
     802         450 :     if (!VI.Var)
     803           3 :       continue;
     804             :     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
     805             :            "Expected inlined-at fields to agree");
     806             : 
     807        1350 :     InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
     808         900 :     Processed.insert(Var);
     809         450 :     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
     810             : 
     811             :     // If variable scope is not found then skip this variable.
     812         450 :     if (!Scope)
     813           3 :       continue;
     814             : 
     815         447 :     ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode());
     816         894 :     auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second);
     817         894 :     RegVar->initializeMMI(VI.Expr, VI.Slot);
     818         447 :     if (DbgVariable *DbgVar = MFVars.lookup(Var))
     819           5 :       DbgVar->addMMIEntry(*RegVar);
     820         884 :     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
     821        1326 :       MFVars.insert({Var, RegVar.get()});
     822         442 :       ConcreteVariables.push_back(std::move(RegVar));
     823             :     }
     824             :   }
     825        6093 : }
     826             : 
     827             : // Get .debug_loc entry for the instruction range starting at MI.
     828       35461 : static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
     829       35461 :   const DIExpression *Expr = MI->getDebugExpression();
     830             :   assert(MI->getNumOperands() == 4);
     831       70922 :   if (MI->getOperand(0).isReg()) {
     832       35027 :     auto RegOp = MI->getOperand(0);
     833       35027 :     auto Op1 = MI->getOperand(1);
     834             :     // If the second operand is an immediate, this is a
     835             :     // register-indirect address.
     836             :     assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
     837       70054 :     MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
     838       35027 :     return DebugLocEntry::Value(Expr, MLoc);
     839             :   }
     840         434 :   if (MI->getOperand(0).isImm())
     841         424 :     return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
     842          10 :   if (MI->getOperand(0).isFPImm())
     843          10 :     return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
     844           0 :   if (MI->getOperand(0).isCImm())
     845           0 :     return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
     846             : 
     847           0 :   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
     848             : }
     849             : 
     850             : /// \brief If this and Next are describing different fragments of the same
     851             : /// variable, merge them by appending Next's values to the current
     852             : /// list of values.
     853             : /// Return true if the merge was successful.
     854          98 : bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
     855          98 :   if (Begin == Next.Begin) {
     856          90 :     auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
     857          90 :     auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
     858          60 :     if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
     859             :       return false;
     860             : 
     861             :     // We can only merge entries if none of the fragments overlap any others.
     862             :     // In doing so, we can take advantage of the fact that both lists are
     863             :     // sorted.
     864         162 :     for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
     865         113 :       for (; j < Next.Values.size(); ++j) {
     866          93 :         int res = DebugHandlerBase::fragmentCmp(
     867          62 :             cast<DIExpression>(Values[i].Expression),
     868          93 :             cast<DIExpression>(Next.Values[j].Expression));
     869          31 :         if (res == 0) // The two expressions overlap, we can't merge.
     870             :           return false;
     871             :         // Values[i] is entirely before Next.Values[j],
     872             :         // so go back to the next entry of Values.
     873          28 :         else if (res == -1)
     874             :           break;
     875             :         // Next.Values[j] is entirely before Values[i], so go on to the
     876             :         // next entry of Next.Values.
     877             :       }
     878             :     }
     879             : 
     880          54 :     addValues(Next.Values);
     881          27 :     End = Next.End;
     882          27 :     return true;
     883             :   }
     884             :   return false;
     885             : }
     886             : 
     887             : /// Build the location list for all DBG_VALUEs in the function that
     888             : /// describe the same variable.  If the ranges of several independent
     889             : /// fragments of the same variable overlap partially, split them up and
     890             : /// combine the ranges. The resulting DebugLocEntries are will have
     891             : /// strict monotonically increasing begin addresses and will never
     892             : /// overlap.
     893             : //
     894             : // Input:
     895             : //
     896             : //   Ranges History [var, loc, fragment ofs size]
     897             : // 0 |      [x, (reg0, fragment 0, 32)]
     898             : // 1 | |    [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
     899             : // 2 | |    ...
     900             : // 3   |    [clobber reg0]
     901             : // 4        [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
     902             : //                                     x.
     903             : //
     904             : // Output:
     905             : //
     906             : // [0-1]    [x, (reg0, fragment  0, 32)]
     907             : // [1-3]    [x, (reg0, fragment  0, 32), (reg1, fragment 32, 32)]
     908             : // [3-4]    [x, (reg1, fragment 32, 32)]
     909             : // [4- ]    [x, (mem,  fragment  0, 64)]
     910             : void
     911        8790 : DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
     912             :                               const DbgValueHistoryMap::InstrRanges &Ranges) {
     913       17580 :   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
     914             : 
     915       61873 :   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
     916       35503 :     const MachineInstr *Begin = I->first;
     917       35503 :     const MachineInstr *End = I->second;
     918             :     assert(Begin->isDebugValue() && "Invalid History entry");
     919             : 
     920             :     // Check if a variable is inaccessible in this range.
     921       71048 :     if (Begin->getNumOperands() > 1 &&
     922      106075 :         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
     923          42 :       OpenRanges.clear();
     924          42 :       continue;
     925             :     }
     926             : 
     927             :     // If this fragment overlaps with any open ranges, truncate them.
     928       35461 :     const DIExpression *DIExpr = Begin->getDebugExpression();
     929       35461 :     auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
     930         121 :       return fragmentsOverlap(DIExpr, R.getExpression());
     931       35582 :     });
     932       70922 :     OpenRanges.erase(Last, OpenRanges.end());
     933             : 
     934       35461 :     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
     935             :     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
     936             : 
     937             :     const MCSymbol *EndLabel;
     938       35461 :     if (End != nullptr)
     939       33456 :       EndLabel = getLabelAfterInsn(End);
     940        4010 :     else if (std::next(I) == Ranges.end())
     941         798 :       EndLabel = Asm->getFunctionEnd();
     942             :     else
     943        2414 :       EndLabel = getLabelBeforeInsn(std::next(I)->first);
     944             :     assert(EndLabel && "Forgot label after instruction ending a range!");
     945             : 
     946             :     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
     947             : 
     948       35461 :     auto Value = getDebugLocValue(Begin);
     949       70922 :     DebugLocEntry Loc(StartLabel, EndLabel, Value);
     950       35461 :     bool couldMerge = false;
     951             : 
     952             :     // If this is a fragment, it may belong to the current DebugLocEntry.
     953       70922 :     if (DIExpr->isFragment()) {
     954             :       // Add this value to the list of open ranges.
     955         149 :       OpenRanges.push_back(Value);
     956             : 
     957             :       // Attempt to add the fragment to the last entry.
     958         149 :       if (!DebugLoc.empty())
     959         196 :         if (DebugLoc.back().MergeValues(Loc))
     960             :           couldMerge = true;
     961             :     }
     962             : 
     963             :     if (!couldMerge) {
     964             :       // Need to add a new DebugLocEntry. Add all values from still
     965             :       // valid non-overlapping fragments.
     966       35434 :       if (OpenRanges.size())
     967         122 :         Loc.addValues(OpenRanges);
     968             : 
     969       35434 :       DebugLoc.push_back(std::move(Loc));
     970             :     }
     971             : 
     972             :     // Attempt to coalesce the ranges of two otherwise identical
     973             :     // DebugLocEntries.
     974       70922 :     auto CurEntry = DebugLoc.rbegin();
     975             :     DEBUG({
     976             :       dbgs() << CurEntry->getValues().size() << " Values:\n";
     977             :       for (auto &Value : CurEntry->getValues())
     978             :         Value.dump();
     979             :       dbgs() << "-----\n";
     980             :     });
     981             : 
     982       70922 :     auto PrevEntry = std::next(CurEntry);
     983      182434 :     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
     984       22713 :       DebugLoc.pop_back();
     985             :   }
     986        8790 : }
     987             : 
     988       10177 : DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU,
     989             :                                                 LexicalScope &Scope,
     990             :                                                 InlinedVariable IV) {
     991       10177 :   ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode());
     992       20354 :   ConcreteVariables.push_back(
     993       20354 :       llvm::make_unique<DbgVariable>(IV.first, IV.second));
     994       30531 :   InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
     995       30531 :   return ConcreteVariables.back().get();
     996             : }
     997             : 
     998             : /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
     999             : /// enclosing lexical scope. The check ensures there are no other instructions
    1000             : /// in the same lexical scope preceding the DBG_VALUE and that its range is
    1001             : /// either open or otherwise rolls off the end of the scope.
    1002        5362 : static bool validThroughout(LexicalScopes &LScopes,
    1003             :                             const MachineInstr *DbgValue,
    1004             :                             const MachineInstr *RangeEnd) {
    1005             :   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
    1006        5362 :   auto MBB = DbgValue->getParent();
    1007       16086 :   auto DL = DbgValue->getDebugLoc();
    1008        5362 :   auto *LScope = LScopes.findLexicalScope(DL);
    1009             :   // Scope doesn't exist; this is a dead DBG_VALUE.
    1010        5362 :   if (!LScope)
    1011             :     return false;
    1012        5360 :   auto &LSRange = LScope->getRanges();
    1013       10720 :   if (LSRange.size() == 0)
    1014             :     return false;
    1015             : 
    1016             :   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
    1017       10720 :   const MachineInstr *LScopeBegin = LSRange.front().first;
    1018             :   // Early exit if the lexical scope begins outside of the current block.
    1019        5360 :   if (LScopeBegin->getParent() != MBB)
    1020             :     return false;
    1021        3717 :   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
    1022       71318 :   for (++Pred; Pred != MBB->rend(); ++Pred) {
    1023       33005 :     if (Pred->getFlag(MachineInstr::FrameSetup))
    1024             :       break;
    1025       72796 :     auto PredDL = Pred->getDebugLoc();
    1026       85260 :     if (!PredDL || Pred->isMetaInstruction())
    1027       24284 :       continue;
    1028             :     // Check whether the instruction preceding the DBG_VALUE is in the same
    1029             :     // (sub)scope as the DBG_VALUE.
    1030       33140 :     if (DL->getScope() == PredDL->getScope())
    1031         627 :       return false;
    1032        7867 :     auto *PredScope = LScopes.findLexicalScope(PredDL);
    1033        7867 :     if (!PredScope || LScope->dominates(PredScope))
    1034             :       return false;
    1035             :   }
    1036             : 
    1037             :   // If the range of the DBG_VALUE is open-ended, report success.
    1038        3090 :   if (!RangeEnd)
    1039             :     return true;
    1040             : 
    1041             :   // Fail if there are instructions belonging to our scope in another block.
    1042        4236 :   const MachineInstr *LScopeEnd = LSRange.back().second;
    1043        2118 :   if (LScopeEnd->getParent() != MBB)
    1044             :     return false;
    1045             : 
    1046             :   // Single, constant DBG_VALUEs in the prologue are promoted to be live
    1047             :   // throughout the function. This is a hack, presumably for DWARF v2 and not
    1048             :   // necessarily correct. It would be much better to use a dbg.declare instead
    1049             :   // if we know the constant is live throughout the scope.
    1050        3746 :   if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
    1051             :     return true;
    1052             : 
    1053             :   return false;
    1054             : }
    1055             : 
    1056             : // Find variables for each lexical scope.
    1057        6093 : void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
    1058             :                                      const DISubprogram *SP,
    1059             :                                      DenseSet<InlinedVariable> &Processed) {
    1060             :   // Grab the variable info that was squirreled away in the MMI side-table.
    1061        6093 :   collectVariableInfoFromMFTable(TheCU, Processed);
    1062             : 
    1063       34902 :   for (const auto &I : DbgValues) {
    1064       10530 :     InlinedVariable IV = I.first;
    1065       21060 :     if (Processed.count(IV))
    1066        1750 :       continue;
    1067             : 
    1068             :     // Instruction ranges, specifying where IV is accessible.
    1069       10520 :     const auto &Ranges = I.second;
    1070       10520 :     if (Ranges.empty())
    1071           0 :       continue;
    1072             : 
    1073       10520 :     LexicalScope *Scope = nullptr;
    1074       10520 :     if (const DILocation *IA = IV.second)
    1075       26008 :       Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
    1076             :     else
    1077        4794 :       Scope = LScopes.findLexicalScope(IV.first->getScope());
    1078             :     // If variable scope is not found then skip this variable.
    1079         758 :     if (!Scope)
    1080         758 :       continue;
    1081             : 
    1082       19524 :     Processed.insert(IV);
    1083        9762 :     DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV);
    1084             : 
    1085       19524 :     const MachineInstr *MInsn = Ranges.front().first;
    1086             :     assert(MInsn->isDebugValue() && "History must begin with debug value");
    1087             : 
    1088             :     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
    1089       25858 :     if (Ranges.size() == 1 &&
    1090       10724 :         validThroughout(LScopes, MInsn, Ranges.front().second)) {
    1091         972 :       RegVar->initializeDbgValue(MInsn);
    1092         972 :       continue;
    1093             :     }
    1094             : 
    1095             :     // Handle multiple DBG_VALUE instructions describing one variable.
    1096       17580 :     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
    1097             : 
    1098             :     // Build the location list for this variable.
    1099       17580 :     SmallVector<DebugLocEntry, 8> Entries;
    1100        8790 :     buildLocationList(Entries, Ranges);
    1101             : 
    1102             :     // If the variable has a DIBasicType, extract it.  Basic types cannot have
    1103             :     // unique identifiers, so don't bother resolving the type with the
    1104             :     // identifier map.
    1105             :     const DIBasicType *BT = dyn_cast<DIBasicType>(
    1106       26370 :         static_cast<const Metadata *>(IV.first->getType()));
    1107             : 
    1108             :     // Finalize the entry by lowering it into a DWARF bytestream.
    1109       39091 :     for (auto &Entry : Entries)
    1110       12721 :       Entry.finalize(*Asm, List, BT);
    1111             :   }
    1112             : 
    1113             :   // Collect info for variables that were optimized out.
    1114       20236 :   for (const DILocalVariable *DV : SP->getVariables()) {
    1115        5871 :     if (Processed.insert(InlinedVariable(DV, nullptr)).second)
    1116        1267 :       if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
    1117         830 :         createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr));
    1118             :   }
    1119        6093 : }
    1120             : 
    1121             : // Process beginning of an instruction.
    1122     1738269 : void DwarfDebug::beginInstruction(const MachineInstr *MI) {
    1123     1738269 :   DebugHandlerBase::beginInstruction(MI);
    1124             :   assert(CurMI);
    1125             : 
    1126     1738269 :   const auto *SP = MI->getParent()->getParent()->getFunction()->getSubprogram();
    1127     3057080 :   if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
    1128             :     return;
    1129             : 
    1130             :   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
    1131             :   if (MI->isMetaInstruction())
    1132             :     return;
    1133     1142114 :   const DebugLoc &DL = MI->getDebugLoc();
    1134             :   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
    1135             :   // the last line number actually emitted, to see if it was line 0.
    1136             :   unsigned LastAsmLine =
    1137     2284228 :       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
    1138             : 
    1139     2284228 :   if (DL == PrevInstLoc) {
    1140             :     // If we have an ongoing unspecified location, nothing to do here.
    1141      622671 :     if (!DL)
    1142             :       return;
    1143             :     // We have an explicit location, same as the previous location.
    1144             :     // But we might be coming back to it after a line 0 record.
    1145      593181 :     if (LastAsmLine == 0 && DL.getLine() != 0) {
    1146             :       // Reinstate the source location but not marked as a statement.
    1147        2799 :       const MDNode *Scope = DL.getScope();
    1148        2799 :       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
    1149             :     }
    1150             :     return;
    1151             :   }
    1152             : 
    1153      519443 :   if (!DL) {
    1154             :     // We have an unspecified location, which might want to be line 0.
    1155             :     // If we have already emitted a line-0 record, don't repeat it.
    1156      125289 :     if (LastAsmLine == 0)
    1157             :       return;
    1158             :     // If user said Don't Do That, don't do that.
    1159      116075 :     if (UnknownLocations == Disable)
    1160             :       return;
    1161             :     // See if we have a reason to emit a line-0 record now.
    1162             :     // Reasons to emit a line-0 record include:
    1163             :     // - User asked for it (UnknownLocations).
    1164             :     // - Instruction has a label, so it's referenced from somewhere else,
    1165             :     //   possibly debug information; we want it to have a source location.
    1166             :     // - Instruction is at the top of a block; we don't want to inherit the
    1167             :     //   location from the physically previous (maybe unrelated) block.
    1168      225082 :     if (UnknownLocations == Enable || PrevLabel ||
    1169      218018 :         (PrevInstBB && PrevInstBB != MI->getParent())) {
    1170             :       // Preserve the file and column numbers, if we can, to save space in
    1171             :       // the encoded line table.
    1172             :       // Do not update PrevInstLoc, it remembers the last non-0 line.
    1173       18661 :       const MDNode *Scope = nullptr;
    1174       18661 :       unsigned Column = 0;
    1175       37322 :       if (PrevInstLoc) {
    1176       18661 :         Scope = PrevInstLoc.getScope();
    1177       18661 :         Column = PrevInstLoc.getCol();
    1178             :       }
    1179       18661 :       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
    1180             :     }
    1181             :     return;
    1182             :   }
    1183             : 
    1184             :   // We have an explicit location, different from the previous location.
    1185             :   // Don't repeat a line-0 record, but otherwise emit the new location.
    1186             :   // (The new location might be an explicit line 0, which we do emit.)
    1187      788308 :   if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
    1188             :     return;
    1189      394116 :   unsigned Flags = 0;
    1190      788232 :   if (DL == PrologEndLoc) {
    1191        6059 :     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
    1192       24236 :     PrologEndLoc = DebugLoc();
    1193             :   }
    1194             :   // If the line changed, we call that a new statement; unless we went to
    1195             :   // line 0 and came back, in which case it is not a new statement.
    1196      788232 :   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
    1197      394116 :   if (DL.getLine() && DL.getLine() != OldLine)
    1198      325760 :     Flags |= DWARF2_FLAG_IS_STMT;
    1199             : 
    1200      394116 :   const MDNode *Scope = DL.getScope();
    1201      394116 :   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
    1202             : 
    1203             :   // If we're not at line 0, remember this location.
    1204      394116 :   if (DL.getLine())
    1205      393931 :     PrevInstLoc = DL;
    1206             : }
    1207             : 
    1208        6093 : static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
    1209             :   // First known non-DBG_VALUE and non-frame setup location marks
    1210             :   // the beginning of the function body.
    1211       24469 :   for (const auto &MBB : *MF)
    1212      166807 :     for (const auto &MI : MBB)
    1213       57060 :       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
    1214       37858 :           MI.getDebugLoc())
    1215       12118 :         return MI.getDebugLoc();
    1216          34 :   return DebugLoc();
    1217             : }
    1218             : 
    1219             : // Gather pre-function debug information.  Assumes being called immediately
    1220             : // after the function entry point has been emitted.
    1221        6093 : void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
    1222        6093 :   CurFn = MF;
    1223             : 
    1224        6093 :   auto *SP = MF->getFunction()->getSubprogram();
    1225             :   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
    1226        6093 :   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
    1227             :     return;
    1228             : 
    1229        6093 :   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
    1230             : 
    1231             :   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
    1232             :   // belongs to so that we add to the correct per-cu line table in the
    1233             :   // non-asm case.
    1234       12186 :   if (Asm->OutStreamer->hasRawTextSupport())
    1235             :     // Use a single line table if we are generating assembly.
    1236         592 :     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
    1237             :   else
    1238       11594 :     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
    1239             : 
    1240             :   // Record beginning of function.
    1241       18279 :   PrologEndLoc = findPrologueEndLoc(MF);
    1242       12186 :   if (PrologEndLoc) {
    1243             :     // We'd like to list the prologue as "not statements" but GDB behaves
    1244             :     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
    1245       18177 :     auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
    1246        6059 :     recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
    1247             :   }
    1248             : }
    1249             : 
    1250      134737 : void DwarfDebug::skippedNonDebugFunction() {
    1251             :   // If we don't have a subprogram for this function then there will be a hole
    1252             :   // in the range information. Keep note of this by setting the previously used
    1253             :   // section to nullptr.
    1254      134737 :   PrevCU = nullptr;
    1255      134737 :   CurFn = nullptr;
    1256      134737 : }
    1257             : 
    1258             : // Gather and emit post-function debug information.
    1259        6093 : void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
    1260        6093 :   const DISubprogram *SP = MF->getFunction()->getSubprogram();
    1261             : 
    1262             :   assert(CurFn == MF &&
    1263             :       "endFunction should be called with the same function as beginFunction");
    1264             : 
    1265             :   // Set DwarfDwarfCompileUnitID in MCContext to default value.
    1266       18279 :   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
    1267             : 
    1268        6093 :   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
    1269             :   assert(!FnScope || SP == FnScope->getScopeNode());
    1270       12186 :   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
    1271             : 
    1272       11179 :   DenseSet<InlinedVariable> ProcessedVars;
    1273        6093 :   collectVariableInfo(TheCU, SP, ProcessedVars);
    1274             : 
    1275             :   // Add the range of this function to the list of ranges for the CU.
    1276       12186 :   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
    1277             : 
    1278             :   // Under -gmlt, skip building the subprogram if there are no inlined
    1279             :   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
    1280             :   // is still needed as we need its source location.
    1281       12185 :   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
    1282       11129 :       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
    1283       17177 :       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
    1284             :     assert(InfoHolder.getScopeVariables().empty());
    1285        1007 :     PrevLabel = nullptr;
    1286        1007 :     CurFn = nullptr;
    1287        1007 :     return;
    1288             :   }
    1289             : 
    1290             : #ifndef NDEBUG
    1291             :   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
    1292             : #endif
    1293             :   // Construct abstract scopes.
    1294       51589 :   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
    1295       72662 :     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
    1296             :     // Collect info for variables that were optimized out.
    1297      120086 :     for (const DILocalVariable *DV : SP->getVariables()) {
    1298       33279 :       if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
    1299           1 :         continue;
    1300       11092 :       ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr),
    1301       33276 :                                       DV->getScope());
    1302             :       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
    1303             :              && "ensureAbstractVariableIsCreated inserted abstract scopes");
    1304             :     }
    1305       36331 :     constructAbstractSubprogramScopeDIE(TheCU, AScope);
    1306             :   }
    1307             : 
    1308        5086 :   ProcessedSPNodes.insert(SP);
    1309        5086 :   TheCU.constructSubprogramScopeDIE(SP, FnScope);
    1310        5086 :   if (auto *SkelCU = TheCU.getSkeleton())
    1311          77 :     if (!LScopes.getAbstractScopesList().empty() &&
    1312           7 :         TheCU.getCUNode()->getSplitDebugInlining())
    1313           5 :       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
    1314             : 
    1315             :   // Clear debug info
    1316             :   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
    1317             :   // DbgVariables except those that are also in AbstractVariables (since they
    1318             :   // can be used cross-function)
    1319       10172 :   InfoHolder.getScopeVariables().clear();
    1320        5086 :   PrevLabel = nullptr;
    1321        5086 :   CurFn = nullptr;
    1322             : }
    1323             : 
    1324             : // Register a source line with debug info. Returns the  unique label that was
    1325             : // emitted and which provides correspondence to the source line list.
    1326      421635 : void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
    1327             :                                   unsigned Flags) {
    1328      421635 :   StringRef Fn;
    1329             :   StringRef Dir;
    1330      421635 :   unsigned Src = 1;
    1331      421635 :   unsigned Discriminator = 0;
    1332      421635 :   if (auto *Scope = cast_or_null<DIScope>(S)) {
    1333      421635 :     Fn = Scope->getFilename();
    1334      421635 :     Dir = Scope->getDirectory();
    1335      421635 :     if (Line != 0 && getDwarfVersion() >= 4)
    1336          65 :       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
    1337          65 :         Discriminator = LBF->getDiscriminator();
    1338             : 
    1339      843270 :     unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
    1340     1264905 :     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
    1341             :               .getOrCreateSourceID(Fn, Dir);
    1342             :   }
    1343     1264905 :   Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
    1344      421635 :                                           Discriminator, Fn);
    1345      421635 : }
    1346             : 
    1347             : //===----------------------------------------------------------------------===//
    1348             : // Emit Methods
    1349             : //===----------------------------------------------------------------------===//
    1350             : 
    1351             : // Emit the debug info section.
    1352         725 : void DwarfDebug::emitDebugInfo() {
    1353         725 :   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
    1354         725 :   Holder.emitUnits(/* UseOffsets */ false);
    1355         725 : }
    1356             : 
    1357             : // Emit the abbreviation section.
    1358         725 : void DwarfDebug::emitAbbreviations() {
    1359         725 :   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
    1360             : 
    1361         725 :   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
    1362         725 : }
    1363             : 
    1364         800 : void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
    1365             :                            StringRef TableName) {
    1366         800 :   Accel.FinalizeTable(Asm, TableName);
    1367        1600 :   Asm->OutStreamer->SwitchSection(Section);
    1368             : 
    1369             :   // Emit the full data.
    1370         800 :   Accel.emit(Asm, Section->getBeginSymbol(), this);
    1371         800 : }
    1372             : 
    1373             : // Emit visible names into a hashed accelerator table section.
    1374         200 : void DwarfDebug::emitAccelNames() {
    1375         200 :   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
    1376             :             "Names");
    1377         200 : }
    1378             : 
    1379             : // Emit objective C classes and categories into a hashed accelerator table
    1380             : // section.
    1381         200 : void DwarfDebug::emitAccelObjC() {
    1382         200 :   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
    1383             :             "ObjC");
    1384         200 : }
    1385             : 
    1386             : // Emit namespace dies into a hashed accelerator table.
    1387         200 : void DwarfDebug::emitAccelNamespaces() {
    1388         400 :   emitAccel(AccelNamespace,
    1389         200 :             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
    1390             :             "namespac");
    1391         200 : }
    1392             : 
    1393             : // Emit type dies into a hashed accelerator table.
    1394         200 : void DwarfDebug::emitAccelTypes() {
    1395         200 :   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
    1396             :             "types");
    1397         200 : }
    1398             : 
    1399             : // Public name handling.
    1400             : // The format for the various pubnames:
    1401             : //
    1402             : // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
    1403             : // for the DIE that is named.
    1404             : //
    1405             : // gnu pubnames - offset/index value/name tuples where the offset is the offset
    1406             : // into the CU and the index value is computed according to the type of value
    1407             : // for the DIE that is named.
    1408             : //
    1409             : // For type units the offset is the offset of the skeleton DIE. For split dwarf
    1410             : // it's the offset within the debug_info/debug_types dwo section, however, the
    1411             : // reference in the pubname header doesn't change.
    1412             : 
    1413             : /// computeIndexValue - Compute the gdb index value for the DIE and CU.
    1414          52 : static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
    1415             :                                                         const DIE *Die) {
    1416             :   // Entities that ended up only in a Type Unit reference the CU instead (since
    1417             :   // the pub entry has offsets within the CU there's no real offset that can be
    1418             :   // provided anyway). As it happens all such entities (namespaces and types,
    1419             :   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
    1420             :   // not to be true it would be necessary to persist this information from the
    1421             :   // point at which the entry is added to the index data structure - since by
    1422             :   // the time the index is built from that, the original type/namespace DIE in a
    1423             :   // type unit has already been destroyed so it can't be queried for properties
    1424             :   // like tag, etc.
    1425          52 :   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
    1426           2 :     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
    1427           2 :                                           dwarf::GIEL_EXTERNAL);
    1428          50 :   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
    1429             : 
    1430             :   // We could have a specification DIE that has our most of our knowledge,
    1431             :   // look for that now.
    1432         100 :   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
    1433          12 :     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
    1434          12 :     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
    1435           6 :       Linkage = dwarf::GIEL_EXTERNAL;
    1436          88 :   } else if (Die->findAttribute(dwarf::DW_AT_external))
    1437          16 :     Linkage = dwarf::GIEL_EXTERNAL;
    1438             : 
    1439          50 :   switch (Die->getTag()) {
    1440           5 :   case dwarf::DW_TAG_class_type:
    1441             :   case dwarf::DW_TAG_structure_type:
    1442             :   case dwarf::DW_TAG_union_type:
    1443             :   case dwarf::DW_TAG_enumeration_type:
    1444           5 :     return dwarf::PubIndexEntryDescriptor(
    1445           5 :         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
    1446             :                               ? dwarf::GIEL_STATIC
    1447           5 :                               : dwarf::GIEL_EXTERNAL);
    1448           3 :   case dwarf::DW_TAG_typedef:
    1449             :   case dwarf::DW_TAG_base_type:
    1450             :   case dwarf::DW_TAG_subrange_type:
    1451           3 :     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
    1452          10 :   case dwarf::DW_TAG_namespace:
    1453          10 :     return dwarf::GIEK_TYPE;
    1454          14 :   case dwarf::DW_TAG_subprogram:
    1455          14 :     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
    1456          18 :   case dwarf::DW_TAG_variable:
    1457          18 :     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
    1458           0 :   case dwarf::DW_TAG_enumerator:
    1459           0 :     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
    1460           0 :                                           dwarf::GIEL_STATIC);
    1461           0 :   default:
    1462           0 :     return dwarf::GIEK_NONE;
    1463             :   }
    1464             : }
    1465             : 
    1466             : /// emitDebugPubSections - Emit visible names and types into debug pubnames and
    1467             : /// pubtypes sections.
    1468         725 : void DwarfDebug::emitDebugPubSections() {
    1469        3638 :   for (const auto &NU : CUMap) {
    1470         738 :     DwarfCompileUnit *TheU = NU.second;
    1471         738 :     if (!TheU->hasDwarfPubSections())
    1472         275 :       continue;
    1473             : 
    1474         463 :     bool GnuStyle = TheU->getCUNode()->getGnuPubnames();
    1475             : 
    1476        1852 :     Asm->OutStreamer->SwitchSection(
    1477           6 :         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
    1478         920 :                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
    1479         926 :     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
    1480             : 
    1481        1852 :     Asm->OutStreamer->SwitchSection(
    1482           6 :         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
    1483         920 :                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
    1484         926 :     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
    1485             :   }
    1486         725 : }
    1487             : 
    1488         926 : void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
    1489             :                                      DwarfCompileUnit *TheU,
    1490             :                                      const StringMap<const DIE *> &Globals) {
    1491         926 :   if (auto *Skeleton = TheU->getSkeleton())
    1492          54 :     TheU = Skeleton;
    1493             : 
    1494             :   // Emit the header.
    1495        4630 :   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
    1496        3704 :   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
    1497        3704 :   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
    1498         926 :   Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
    1499             : 
    1500        1852 :   Asm->OutStreamer->EmitLabel(BeginLabel);
    1501             : 
    1502        2778 :   Asm->OutStreamer->AddComment("DWARF Version");
    1503         926 :   Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
    1504             : 
    1505        2778 :   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
    1506         926 :   Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
    1507             : 
    1508        2778 :   Asm->OutStreamer->AddComment("Compilation Unit Length");
    1509        1852 :   Asm->EmitInt32(TheU->getLength());
    1510             : 
    1511             :   // Emit the pubnames for this compilation unit.
    1512       17878 :   for (const auto &GI : Globals) {
    1513        7087 :     const char *Name = GI.getKeyData();
    1514        7087 :     const DIE *Entity = GI.second;
    1515             : 
    1516       21261 :     Asm->OutStreamer->AddComment("DIE offset");
    1517        7087 :     Asm->EmitInt32(Entity->getOffset());
    1518             : 
    1519        7087 :     if (GnuStyle) {
    1520          52 :       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
    1521         156 :       Asm->OutStreamer->AddComment(
    1522         364 :           Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
    1523         156 :           dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
    1524         104 :       Asm->EmitInt8(Desc.toBits());
    1525             :     }
    1526             : 
    1527       21261 :     Asm->OutStreamer->AddComment("External Name");
    1528       28348 :     Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
    1529             :   }
    1530             : 
    1531        2778 :   Asm->OutStreamer->AddComment("End Mark");
    1532         926 :   Asm->EmitInt32(0);
    1533        1852 :   Asm->OutStreamer->EmitLabel(EndLabel);
    1534         926 : }
    1535             : 
    1536             : /// Emit null-terminated strings into a debug str section.
    1537         725 : void DwarfDebug::emitDebugStr() {
    1538         725 :   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
    1539         725 :   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
    1540         725 : }
    1541             : 
    1542       12717 : void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
    1543             :                                    const DebugLocStream::Entry &Entry) {
    1544       12717 :   auto &&Comments = DebugLocs.getComments(Entry);
    1545       12717 :   auto Comment = Comments.begin();
    1546       12717 :   auto End = Comments.end();
    1547       55503 :   for (uint8_t Byte : DebugLocs.getBytes(Entry))
    1548       86044 :     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
    1549       12717 : }
    1550             : 
    1551       12756 : static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
    1552             :                               ByteStreamer &Streamer,
    1553             :                               const DebugLocEntry::Value &Value,
    1554             :                               DwarfExpression &DwarfExpr) {
    1555       12756 :   auto *DIExpr = Value.getExpression();
    1556       12756 :   DIExpressionCursor ExprCursor(DIExpr);
    1557       12756 :   DwarfExpr.addFragmentOffset(DIExpr);
    1558             :   // Regular entry.
    1559       12756 :   if (Value.isInt()) {
    1560         489 :     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
    1561          64 :                BT->getEncoding() == dwarf::DW_ATE_signed_char))
    1562          39 :       DwarfExpr.addSignedConstant(Value.getInt());
    1563             :     else
    1564         386 :       DwarfExpr.addUnsignedConstant(Value.getInt());
    1565       12331 :   } else if (Value.isLocation()) {
    1566       12321 :     MachineLocation Location = Value.getLoc();
    1567       12321 :     if (Location.isIndirect())
    1568        1130 :       DwarfExpr.setMemoryLocationKind();
    1569       12321 :     DIExpressionCursor Cursor(DIExpr);
    1570       12321 :     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
    1571       12321 :     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
    1572             :       return;
    1573       12309 :     return DwarfExpr.addExpression(std::move(Cursor));
    1574          10 :   } else if (Value.isConstantFP()) {
    1575          30 :     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
    1576          10 :     DwarfExpr.addUnsignedConstant(RawBytes);
    1577             :   }
    1578         435 :   DwarfExpr.addExpression(std::move(ExprCursor));
    1579             : }
    1580             : 
    1581       12721 : void DebugLocEntry::finalize(const AsmPrinter &AP,
    1582             :                              DebugLocStream::ListBuilder &List,
    1583             :                              const DIBasicType *BT) {
    1584       38163 :   DebugLocStream::EntryBuilder Entry(List, Begin, End);
    1585       12721 :   BufferByteStreamer Streamer = Entry.getStreamer();
    1586       38163 :   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
    1587       25442 :   const DebugLocEntry::Value &Value = Values[0];
    1588       12721 :   if (Value.isFragment()) {
    1589             :     // Emit all fragments that belong to the same variable and range.
    1590             :     assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
    1591             :           return P.isFragment();
    1592             :         }) && "all values are expected to be fragments");
    1593             :     assert(std::is_sorted(Values.begin(), Values.end()) &&
    1594             :            "fragments are expected to be sorted");
    1595             : 
    1596         279 :     for (auto Fragment : Values)
    1597          96 :       emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr);
    1598             : 
    1599             :   } else {
    1600             :     assert(Values.size() == 1 && "only fragments may have >1 value");
    1601       12660 :     emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr);
    1602             :   }
    1603       12721 :   DwarfExpr.finalize();
    1604       12721 : }
    1605             : 
    1606       12715 : void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
    1607             :   // Emit the size.
    1608       38145 :   Asm->OutStreamer->AddComment("Loc expr size");
    1609       25430 :   Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
    1610             : 
    1611             :   // Emit the entry.
    1612       25430 :   APByteStreamer Streamer(*Asm);
    1613       12715 :   emitDebugLocEntry(Streamer, Entry);
    1614       12715 : }
    1615             : 
    1616             : // Emit locations into the debug loc section.
    1617         702 : void DwarfDebug::emitDebugLoc() {
    1618        1404 :   if (DebugLocs.getLists().empty())
    1619             :     return;
    1620             : 
    1621             :   // Start the dwarf loc section.
    1622         450 :   Asm->OutStreamer->SwitchSection(
    1623         150 :       Asm->getObjFileLowering().getDwarfLocSection());
    1624         150 :   unsigned char Size = Asm->MAI->getCodePointerSize();
    1625        9205 :   for (const auto &List : DebugLocs.getLists()) {
    1626       17510 :     Asm->OutStreamer->EmitLabel(List.Label);
    1627        8755 :     const DwarfCompileUnit *CU = List.CU;
    1628       30218 :     for (const auto &Entry : DebugLocs.getEntries(List)) {
    1629             :       // Set up the range. This range is relative to the entry point of the
    1630             :       // compile unit. This is a hard coded 0 for low_pc when we're emitting
    1631             :       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
    1632       12708 :       if (auto *Base = CU->getBaseAddress()) {
    1633         818 :         Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
    1634         818 :         Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
    1635             :       } else {
    1636       23780 :         Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
    1637       23780 :         Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
    1638             :       }
    1639             : 
    1640       12708 :       emitDebugLocEntryLocation(Entry);
    1641             :     }
    1642       17510 :     Asm->OutStreamer->EmitIntValue(0, Size);
    1643       17510 :     Asm->OutStreamer->EmitIntValue(0, Size);
    1644             :   }
    1645             : }
    1646             : 
    1647          23 : void DwarfDebug::emitDebugLocDWO() {
    1648          69 :   Asm->OutStreamer->SwitchSection(
    1649          23 :       Asm->getObjFileLowering().getDwarfLocDWOSection());
    1650          74 :   for (const auto &List : DebugLocs.getLists()) {
    1651          10 :     Asm->OutStreamer->EmitLabel(List.Label);
    1652          17 :     for (const auto &Entry : DebugLocs.getEntries(List)) {
    1653             :       // Just always use start_length for now - at least that's one address
    1654             :       // rather than two. We could get fancier and try to, say, reuse an
    1655             :       // address we know we've emitted elsewhere (the start of the function?
    1656             :       // The start of the CU or CU subrange that encloses this range?)
    1657           7 :       Asm->EmitInt8(dwarf::DW_LLE_startx_length);
    1658           7 :       unsigned idx = AddrPool.getIndex(Entry.BeginSym);
    1659           7 :       Asm->EmitULEB128(idx);
    1660           7 :       Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
    1661             : 
    1662           7 :       emitDebugLocEntryLocation(Entry);
    1663             :     }
    1664           5 :     Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
    1665             :   }
    1666          23 : }
    1667             : 
    1668             : struct ArangeSpan {
    1669             :   const MCSymbol *Start, *End;
    1670             : };
    1671             : 
    1672             : // Emit a debug aranges section, containing a CU lookup for any
    1673             : // address we can tie back to a CU.
    1674           6 : void DwarfDebug::emitDebugARanges() {
    1675             :   // Provides a unique id per text section.
    1676          12 :   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
    1677             : 
    1678             :   // Filter labels by section.
    1679          42 :   for (const SymbolCU &SCU : ArangeLabels) {
    1680          18 :     if (SCU.Sym->isInSection()) {
    1681             :       // Make a note of this symbol and it's section.
    1682          34 :       MCSection *Section = &SCU.Sym->getSection();
    1683          17 :       if (!Section->getKind().isMetadata())
    1684          17 :         SectionMap[Section].push_back(SCU);
    1685             :     } else {
    1686             :       // Some symbols (e.g. common/bss on mach-o) can have no section but still
    1687             :       // appear in the output. This sucks as we rely on sections to build
    1688             :       // arange spans. We can do it without, but it's icky.
    1689           1 :       SectionMap[nullptr].push_back(SCU);
    1690             :     }
    1691             :   }
    1692             : 
    1693          12 :   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
    1694             : 
    1695          35 :   for (auto &I : SectionMap) {
    1696          11 :     MCSection *Section = I.first;
    1697          11 :     SmallVector<SymbolCU, 8> &List = I.second;
    1698          22 :     if (List.size() < 1)
    1699           0 :       continue;
    1700             : 
    1701             :     // If we have no section (e.g. common), just write out
    1702             :     // individual spans for each symbol.
    1703          11 :     if (!Section) {
    1704           3 :       for (const SymbolCU &Cur : List) {
    1705             :         ArangeSpan Span;
    1706           1 :         Span.Start = Cur.Sym;
    1707           1 :         Span.End = nullptr;
    1708             :         assert(Cur.CU);
    1709           2 :         Spans[Cur.CU].push_back(Span);
    1710             :       }
    1711           1 :       continue;
    1712             :     }
    1713             : 
    1714             :     // Sort the symbols by offset within the section.
    1715          20 :     std::sort(
    1716          14 :         List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
    1717          56 :           unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
    1718          56 :           unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
    1719             : 
    1720             :           // Symbols with no order assigned should be placed at the end.
    1721             :           // (e.g. section end labels)
    1722          14 :           if (IA == 0)
    1723             :             return false;
    1724           0 :           if (IB == 0)
    1725             :             return true;
    1726           0 :           return IA < IB;
    1727             :         });
    1728             : 
    1729             :     // Insert a final terminator.
    1730          30 :     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
    1731             : 
    1732             :     // Build spans between each label.
    1733          20 :     const MCSymbol *StartSym = List[0].Sym;
    1734          37 :     for (size_t n = 1, e = List.size(); n < e; n++) {
    1735          34 :       const SymbolCU &Prev = List[n - 1];
    1736          34 :       const SymbolCU &Cur = List[n];
    1737             : 
    1738             :       // Try and build the longest span we can within the same CU.
    1739          17 :       if (Cur.CU != Prev.CU) {
    1740             :         ArangeSpan Span;
    1741          11 :         Span.Start = StartSym;
    1742          11 :         Span.End = Cur.Sym;
    1743             :         assert(Prev.CU);
    1744          22 :         Spans[Prev.CU].push_back(Span);
    1745          11 :         StartSym = Cur.Sym;
    1746             :       }
    1747             :     }
    1748             :   }
    1749             : 
    1750             :   // Start the dwarf aranges section.
    1751          18 :   Asm->OutStreamer->SwitchSection(
    1752           6 :       Asm->getObjFileLowering().getDwarfARangesSection());
    1753             : 
    1754           6 :   unsigned PtrSize = Asm->MAI->getCodePointerSize();
    1755             : 
    1756             :   // Build a list of CUs used.
    1757          12 :   std::vector<DwarfCompileUnit *> CUs;
    1758          25 :   for (const auto &it : Spans) {
    1759           7 :     DwarfCompileUnit *CU = it.first;
    1760           7 :     CUs.push_back(CU);
    1761             :   }
    1762             : 
    1763             :   // Sort the CU list (again, to ensure consistent output order).
    1764          12 :   std::sort(CUs.begin(), CUs.end(),
    1765             :             [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
    1766           1 :               return A->getUniqueID() < B->getUniqueID();
    1767             :             });
    1768             : 
    1769             :   // Emit an arange table for each CU we used.
    1770          31 :   for (DwarfCompileUnit *CU : CUs) {
    1771           7 :     std::vector<ArangeSpan> &List = Spans[CU];
    1772             : 
    1773             :     // Describe the skeleton CU's offset and length, not the dwo file's.
    1774           7 :     if (auto *Skel = CU->getSkeleton())
    1775           0 :       CU = Skel;
    1776             : 
    1777             :     // Emit size of content not including length itself.
    1778           7 :     unsigned ContentSize =
    1779             :         sizeof(int16_t) + // DWARF ARange version number
    1780             :         sizeof(int32_t) + // Offset of CU in the .debug_info section
    1781             :         sizeof(int8_t) +  // Pointer Size (in bytes)
    1782             :         sizeof(int8_t);   // Segment Size (in bytes)
    1783             : 
    1784           7 :     unsigned TupleSize = PtrSize * 2;
    1785             : 
    1786             :     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
    1787             :     unsigned Padding =
    1788          14 :         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
    1789             : 
    1790           7 :     ContentSize += Padding;
    1791           7 :     ContentSize += (List.size() + 1) * TupleSize;
    1792             : 
    1793             :     // For each compile unit, write the list of spans it covers.
    1794          21 :     Asm->OutStreamer->AddComment("Length of ARange Set");
    1795           7 :     Asm->EmitInt32(ContentSize);
    1796          21 :     Asm->OutStreamer->AddComment("DWARF Arange version number");
    1797           7 :     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
    1798          21 :     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
    1799           7 :     Asm->emitDwarfSymbolReference(CU->getLabelBegin());
    1800          21 :     Asm->OutStreamer->AddComment("Address Size (in bytes)");
    1801           7 :     Asm->EmitInt8(PtrSize);
    1802          21 :     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
    1803           7 :     Asm->EmitInt8(0);
    1804             : 
    1805          14 :     Asm->OutStreamer->emitFill(Padding, 0xff);
    1806             : 
    1807          40 :     for (const ArangeSpan &Span : List) {
    1808          24 :       Asm->EmitLabelReference(Span.Start, PtrSize);
    1809             : 
    1810             :       // Calculate the size as being from the span start to it's end.
    1811          12 :       if (Span.End) {
    1812          11 :         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
    1813             :       } else {
    1814             :         // For symbols without an end marker (e.g. common), we
    1815             :         // write a single arange entry containing just that one symbol.
    1816           2 :         uint64_t Size = SymSize[Span.Start];
    1817           1 :         if (Size == 0)
    1818           0 :           Size = 1;
    1819             : 
    1820           2 :         Asm->OutStreamer->EmitIntValue(Size, PtrSize);
    1821             :       }
    1822             :     }
    1823             : 
    1824          21 :     Asm->OutStreamer->AddComment("ARange terminator");
    1825          14 :     Asm->OutStreamer->EmitIntValue(0, PtrSize);
    1826          14 :     Asm->OutStreamer->EmitIntValue(0, PtrSize);
    1827             :   }
    1828           6 : }
    1829             : 
    1830             : /// Emit address ranges into a debug ranges section.
    1831         725 : void DwarfDebug::emitDebugRanges() {
    1832        1450 :   if (CUMap.empty())
    1833             :     return;
    1834             : 
    1835             :   // Start the dwarf ranges section.
    1836        2076 :   Asm->OutStreamer->SwitchSection(
    1837         692 :       Asm->getObjFileLowering().getDwarfRangesSection());
    1838             : 
    1839             :   // Size for our labels.
    1840         692 :   unsigned char Size = Asm->MAI->getCodePointerSize();
    1841             : 
    1842             :   // Grab the specific ranges for the compile units in the module.
    1843        3506 :   for (const auto &I : CUMap) {
    1844         738 :     DwarfCompileUnit *TheCU = I.second;
    1845             : 
    1846         738 :     if (auto *Skel = TheCU->getSkeleton())
    1847          27 :       TheCU = Skel;
    1848             : 
    1849             :     // Iterate over the misc ranges for the compile units in the module.
    1850       56878 :     for (const RangeSpanList &List : TheCU->getRangeLists()) {
    1851             :       // Emit our symbol so we can find the beginning of the range.
    1852      109328 :       Asm->OutStreamer->EmitLabel(List.getSym());
    1853             : 
    1854             :       // Gather all the ranges that apply to the same section so they can share
    1855             :       // a base address entry.
    1856      109328 :       MapVector<const MCSection *, std::vector<const RangeSpan *>> MV;
    1857      338066 :       for (const RangeSpan &Range : List.getRanges()) {
    1858      522222 :         MV[&Range.getStart()->getSection()].push_back(&Range);
    1859             :       }
    1860             : 
    1861       54664 :       auto *CUBase = TheCU->getBaseAddress();
    1862       54664 :       bool BaseIsSet = false;
    1863      278394 :       for (const auto &P : MV) {
    1864             :         // Don't bother with a base address entry if there's only one range in
    1865             :         // this section in this range list - for example ranges for a CU will
    1866             :         // usually consist of single regions from each of many sections
    1867             :         // (-ffunction-sections, or just C++ inline functions) except under LTO
    1868             :         // or optnone where there may be holes in a single CU's section
    1869             :         // contrubutions.
    1870       59738 :         auto *Base = CUBase;
    1871      173930 :         if (!Base && P.second.size() > 1 &&
    1872       54530 :             UseDwarfRangesBaseAddressSpecifier) {
    1873           1 :           BaseIsSet = true;
    1874             :           // FIXME/use care: This may not be a useful base address if it's not
    1875             :           // the lowest address/range in this object.
    1876           2 :           Base = P.second.front()->getStart();
    1877           2 :           Asm->OutStreamer->EmitIntValue(-1, Size);
    1878           2 :           Asm->OutStreamer->EmitSymbolValue(Base, Size);
    1879       59737 :         } else if (BaseIsSet) {
    1880           1 :           BaseIsSet = false;
    1881           2 :           Asm->OutStreamer->EmitIntValue(-1, Size);
    1882           2 :           Asm->OutStreamer->EmitIntValue(0, Size);
    1883             :         }
    1884             : 
    1885      413026 :         for (const auto *RS : P.second) {
    1886      174074 :           const MCSymbol *Begin = RS->getStart();
    1887      174074 :           const MCSymbol *End = RS->getEnd();
    1888             :           assert(Begin && "Range without a begin symbol?");
    1889             :           assert(End && "Range without an end symbol?");
    1890      174074 :           if (Base) {
    1891         171 :             Asm->EmitLabelDifference(Begin, Base, Size);
    1892         171 :             Asm->EmitLabelDifference(End, Base, Size);
    1893             :           } else {
    1894      347806 :             Asm->OutStreamer->EmitSymbolValue(Begin, Size);
    1895      347806 :             Asm->OutStreamer->EmitSymbolValue(End, Size);
    1896             :           }
    1897             :         }
    1898             :       }
    1899             : 
    1900             :       // And terminate the list with two 0 values.
    1901      109328 :       Asm->OutStreamer->EmitIntValue(0, Size);
    1902      109328 :       Asm->OutStreamer->EmitIntValue(0, Size);
    1903             :     }
    1904             :   }
    1905             : }
    1906             : 
    1907         741 : void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
    1908        2230 :   for (auto *MN : Nodes) {
    1909           4 :     if (auto *M = dyn_cast<DIMacro>(MN))
    1910           4 :       emitMacro(*M);
    1911           3 :     else if (auto *F = dyn_cast<DIMacroFile>(MN))
    1912           3 :       emitMacroFile(*F, U);
    1913             :     else
    1914           0 :       llvm_unreachable("Unexpected DI type!");
    1915             :   }
    1916         741 : }
    1917             : 
    1918           4 : void DwarfDebug::emitMacro(DIMacro &M) {
    1919           4 :   Asm->EmitULEB128(M.getMacinfoType());
    1920           4 :   Asm->EmitULEB128(M.getLine());
    1921           4 :   StringRef Name = M.getName();
    1922           4 :   StringRef Value = M.getValue();
    1923           8 :   Asm->OutStreamer->EmitBytes(Name);
    1924           4 :   if (!Value.empty()) {
    1925             :     // There should be one space between macro name and macro value.
    1926           2 :     Asm->EmitInt8(' ');
    1927           4 :     Asm->OutStreamer->EmitBytes(Value);
    1928             :   }
    1929           4 :   Asm->EmitInt8('\0');
    1930           4 : }
    1931             : 
    1932           3 : void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
    1933             :   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
    1934           3 :   Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
    1935           3 :   Asm->EmitULEB128(F.getLine());
    1936           3 :   DIFile *File = F.getFile();
    1937             :   unsigned FID =
    1938           6 :       U.getOrCreateSourceID(File->getFilename(), File->getDirectory());
    1939           3 :   Asm->EmitULEB128(FID);
    1940           3 :   handleMacroNodes(F.getElements(), U);
    1941           3 :   Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
    1942           3 : }
    1943             : 
    1944             : /// Emit macros into a debug macinfo section.
    1945         725 : void DwarfDebug::emitDebugMacinfo() {
    1946        1450 :   if (CUMap.empty())
    1947             :     return;
    1948             : 
    1949             :   // Start the dwarf macinfo section.
    1950        2076 :   Asm->OutStreamer->SwitchSection(
    1951         692 :       Asm->getObjFileLowering().getDwarfMacinfoSection());
    1952             : 
    1953        3506 :   for (const auto &P : CUMap) {
    1954         738 :     auto &TheCU = *P.second;
    1955         738 :     auto *SkCU = TheCU.getSkeleton();
    1956         738 :     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
    1957        1476 :     auto *CUNode = cast<DICompileUnit>(P.first);
    1958        1476 :     Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
    1959         738 :     handleMacroNodes(CUNode->getMacros(), U);
    1960             :   }
    1961        2076 :   Asm->OutStreamer->AddComment("End Of Macro List Mark");
    1962         692 :   Asm->EmitInt8(0);
    1963             : }
    1964             : 
    1965             : // DWARF5 Experimental Separate Dwarf emitters.
    1966             : 
    1967          27 : void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
    1968             :                                   std::unique_ptr<DwarfCompileUnit> NewU) {
    1969          81 :   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
    1970          27 :                   Asm->TM.Options.MCOptions.SplitDwarfFile);
    1971             : 
    1972          54 :   if (!CompilationDir.empty())
    1973          27 :     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
    1974             : 
    1975          27 :   addGnuPubAttributes(*NewU, Die);
    1976             : 
    1977          54 :   SkeletonHolder.addUnit(std::move(NewU));
    1978          27 : }
    1979             : 
    1980             : // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
    1981             : // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
    1982             : // DW_AT_addr_base, DW_AT_ranges_base.
    1983          27 : DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
    1984             : 
    1985             :   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
    1986          81 :       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
    1987          27 :   DwarfCompileUnit &NewCU = *OwnedUnit;
    1988          54 :   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
    1989             : 
    1990          27 :   NewCU.initStmtList();
    1991             : 
    1992          81 :   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
    1993             : 
    1994          27 :   return NewCU;
    1995             : }
    1996             : 
    1997             : // Emit the .debug_info.dwo section for separated dwarf. This contains the
    1998             : // compile units that would normally be in debug_info.
    1999          23 : void DwarfDebug::emitDebugInfoDWO() {
    2000             :   assert(useSplitDwarf() && "No split dwarf debug info?");
    2001             :   // Don't emit relocations into the dwo file.
    2002          23 :   InfoHolder.emitUnits(/* UseOffsets */ true);
    2003          23 : }
    2004             : 
    2005             : // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
    2006             : // abbreviations for the .debug_info.dwo section.
    2007          23 : void DwarfDebug::emitDebugAbbrevDWO() {
    2008             :   assert(useSplitDwarf() && "No split dwarf?");
    2009          23 :   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
    2010          23 : }
    2011             : 
    2012          23 : void DwarfDebug::emitDebugLineDWO() {
    2013             :   assert(useSplitDwarf() && "No split dwarf?");
    2014          69 :   Asm->OutStreamer->SwitchSection(
    2015          23 :       Asm->getObjFileLowering().getDwarfLineDWOSection());
    2016          69 :   SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
    2017          23 : }
    2018             : 
    2019             : // Emit the .debug_str.dwo section for separated dwarf. This contains the
    2020             : // string section and is identical in format to traditional .debug_str
    2021             : // sections.
    2022          23 : void DwarfDebug::emitDebugStrDWO() {
    2023             :   assert(useSplitDwarf() && "No split dwarf?");
    2024          23 :   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
    2025          23 :   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
    2026             :                          OffSec);
    2027          23 : }
    2028             : 
    2029          36 : MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
    2030          36 :   if (!useSplitDwarf())
    2031             :     return nullptr;
    2032          19 :   if (SingleCU)
    2033          19 :     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
    2034          19 :   return &SplitTypeUnitFileTable;
    2035             : }
    2036             : 
    2037          36 : uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
    2038          36 :   MD5 Hash;
    2039          36 :   Hash.update(Identifier);
    2040             :   // ... take the least significant 8 bytes and return those. Our MD5
    2041             :   // implementation always returns its results in little endian, so we actually
    2042             :   // need the "high" word.
    2043             :   MD5::MD5Result Result;
    2044          36 :   Hash.final(Result);
    2045          36 :   return Result.high();
    2046             : }
    2047             : 
    2048          46 : void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
    2049             :                                       StringRef Identifier, DIE &RefDie,
    2050             :                                       const DICompositeType *CTy) {
    2051             :   // Fast path if we're building some type units and one has already used the
    2052             :   // address pool we know we're going to throw away all this work anyway, so
    2053             :   // don't bother building dependent types.
    2054          46 :   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
    2055          17 :     return;
    2056             : 
    2057         180 :   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
    2058          45 :   if (!Ins.second) {
    2059           9 :     CU.addDIETypeSignature(RefDie, Ins.first->second);
    2060           9 :     return;
    2061             :   }
    2062             : 
    2063          36 :   bool TopLevelType = TypeUnitsUnderConstruction.empty();
    2064          36 :   AddrPool.resetUsedFlag();
    2065             : 
    2066          36 :   auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
    2067         137 :                                                     getDwoLineTable(CU));
    2068          36 :   DwarfTypeUnit &NewTU = *OwnedUnit;
    2069          72 :   DIE &UnitDie = NewTU.getUnitDie();
    2070          36 :   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
    2071             : 
    2072         144 :   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
    2073          36 :                 CU.getLanguage());
    2074             : 
    2075          36 :   uint64_t Signature = makeTypeSignature(Identifier);
    2076          72 :   NewTU.setTypeSignature(Signature);
    2077          36 :   Ins.first->second = Signature;
    2078             : 
    2079          36 :   if (useSplitDwarf())
    2080          19 :     NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
    2081             :   else {
    2082          17 :     CU.applyStmtList(UnitDie);
    2083          17 :     NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
    2084             :   }
    2085             : 
    2086          72 :   NewTU.setType(NewTU.createTypeDIE(CTy));
    2087             : 
    2088          36 :   if (TopLevelType) {
    2089          65 :     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
    2090          24 :     TypeUnitsUnderConstruction.clear();
    2091             : 
    2092             :     // Types referencing entries in the address table cannot be placed in type
    2093             :     // units.
    2094          24 :     if (AddrPool.hasBeenUsed()) {
    2095             : 
    2096             :       // Remove all the types built while building this type.
    2097             :       // This is pessimistic as some of these types might not be dependent on
    2098             :       // the type that used an address.
    2099          32 :       for (const auto &TU : TypeUnitsToAdd)
    2100          11 :         TypeSignatures.erase(TU.second);
    2101             : 
    2102             :       // Construct this type in the CU directly.
    2103             :       // This is inefficient because all the dependent types will be rebuilt
    2104             :       // from scratch, including building them in type units, discovering that
    2105             :       // they depend on addresses, throwing them out and rebuilding them.
    2106          14 :       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
    2107           7 :       return;
    2108             :     }
    2109             : 
    2110             :     // If the type wasn't dependent on fission addresses, finish adding the type
    2111             :     // and all its dependent types.
    2112          76 :     for (auto &TU : TypeUnitsToAdd) {
    2113          50 :       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
    2114          50 :       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
    2115             :     }
    2116             :   }
    2117          29 :   CU.addDIETypeSignature(RefDie, Signature);
    2118             : }
    2119             : 
    2120             : // Accelerator table mutators - add each name along with its companion
    2121             : // DIE to the proper table while ensuring that the name that we're going
    2122             : // to reference is in the string table. We do this since the names we
    2123             : // add may not only be identical to the names in the DIE.
    2124      184668 : void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
    2125      184668 :   if (!useDwarfAccelTables())
    2126             :     return;
    2127        1006 :   AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
    2128             : }
    2129             : 
    2130          23 : void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
    2131          23 :   if (!useDwarfAccelTables())
    2132             :     return;
    2133          20 :   AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
    2134             : }
    2135             : 
    2136         224 : void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
    2137         224 :   if (!useDwarfAccelTables())
    2138             :     return;
    2139          10 :   AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
    2140             : }
    2141             : 
    2142        6858 : void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
    2143        6858 :   if (!useDwarfAccelTables())
    2144             :     return;
    2145         886 :   AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
    2146             : }
    2147             : 
    2148      575405 : uint16_t DwarfDebug::getDwarfVersion() const {
    2149     1150810 :   return Asm->OutStreamer->getContext().getDwarfVersion();
    2150      216918 : }

Generated by: LCOV version 1.13