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

Generated by: LCOV version 1.13