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

Generated by: LCOV version 1.13