LCOV - code coverage report
Current view: top level - lib/CodeGen/AsmPrinter - DwarfCompileUnit.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 462 469 98.5 %
Date: 2018-09-23 13:06:45 Functions: 47 47 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
       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 constructing a dwarf compile unit.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "DwarfCompileUnit.h"
      15             : #include "AddressPool.h"
      16             : #include "DwarfDebug.h"
      17             : #include "DwarfExpression.h"
      18             : #include "DwarfUnit.h"
      19             : #include "llvm/ADT/None.h"
      20             : #include "llvm/ADT/STLExtras.h"
      21             : #include "llvm/ADT/SmallVector.h"
      22             : #include "llvm/ADT/StringRef.h"
      23             : #include "llvm/BinaryFormat/Dwarf.h"
      24             : #include "llvm/CodeGen/AsmPrinter.h"
      25             : #include "llvm/CodeGen/DIE.h"
      26             : #include "llvm/CodeGen/LexicalScopes.h"
      27             : #include "llvm/CodeGen/MachineFunction.h"
      28             : #include "llvm/CodeGen/MachineInstr.h"
      29             : #include "llvm/CodeGen/MachineOperand.h"
      30             : #include "llvm/CodeGen/TargetFrameLowering.h"
      31             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      32             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      33             : #include "llvm/IR/DataLayout.h"
      34             : #include "llvm/IR/DebugInfo.h"
      35             : #include "llvm/IR/DebugInfoMetadata.h"
      36             : #include "llvm/IR/GlobalVariable.h"
      37             : #include "llvm/MC/MCSection.h"
      38             : #include "llvm/MC/MCStreamer.h"
      39             : #include "llvm/MC/MCSymbol.h"
      40             : #include "llvm/MC/MachineLocation.h"
      41             : #include "llvm/Support/Casting.h"
      42             : #include "llvm/Target/TargetLoweringObjectFile.h"
      43             : #include "llvm/Target/TargetMachine.h"
      44             : #include "llvm/Target/TargetOptions.h"
      45             : #include <algorithm>
      46             : #include <cassert>
      47             : #include <cstdint>
      48             : #include <iterator>
      49             : #include <memory>
      50             : #include <string>
      51             : #include <utility>
      52             : 
      53             : using namespace llvm;
      54             : 
      55        3420 : DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
      56             :                                    AsmPrinter *A, DwarfDebug *DW,
      57        3420 :                                    DwarfFile *DWU)
      58        3420 :     : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID) {
      59        3420 :   insertDIE(Node, &getUnitDie());
      60        6840 :   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
      61        3420 : }
      62             : 
      63             : /// addLabelAddress - Add a dwarf label attribute data and value using
      64             : /// DW_FORM_addr or DW_FORM_GNU_addr_index.
      65      121880 : void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
      66             :                                        const MCSymbol *Label) {
      67             :   // Don't use the address pool in non-fission or in the skeleton unit itself.
      68             :   // FIXME: Once GDB supports this, it's probably worthwhile using the address
      69             :   // pool from the skeleton - maybe even in non-fission (possibly fewer
      70             :   // relocations by sharing them in the pool, but we have other ideas about how
      71             :   // to reduce the number of relocations as well/instead).
      72      121880 :   if (!DD->useSplitDwarf() || !Skeleton)
      73      113398 :     return addLocalLabelAddress(Die, Attribute, Label);
      74             : 
      75        8482 :   if (Label)
      76        8482 :     DD->addArangeLabel(SymbolCU(this, Label));
      77             : 
      78       16964 :   unsigned idx = DD->getAddressPool().getIndex(Label);
      79        8482 :   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
      80        8482 :                DIEInteger(idx));
      81             : }
      82             : 
      83      113398 : void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
      84             :                                             dwarf::Attribute Attribute,
      85             :                                             const MCSymbol *Label) {
      86      113398 :   if (Label)
      87      113398 :     DD->addArangeLabel(SymbolCU(this, Label));
      88             : 
      89      113398 :   if (Label)
      90      113398 :     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
      91      113398 :                  DIELabel(Label));
      92             :   else
      93           0 :     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
      94           0 :                  DIEInteger(0));
      95      113398 : }
      96             : 
      97     1658489 : unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
      98             :   // If we print assembly, we can't separate .file entries according to
      99             :   // compile units. Thus all files will belong to the default compile unit.
     100             : 
     101             :   // FIXME: add a better feature test than hasRawTextSupport. Even better,
     102             :   // extend .file to support this.
     103     3316978 :   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
     104     1658489 :   if (!File)
     105        2090 :     return Asm->OutStreamer->EmitDwarfFileDirective(0, "", "", nullptr, None, CUID);
     106     1657452 :   return Asm->OutStreamer->EmitDwarfFileDirective(
     107             :       0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
     108     1657444 :       File->getSource(), CUID);
     109             : }
     110             : 
     111        4340 : DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
     112             :     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
     113             :   // Check for pre-existence.
     114        4340 :   if (DIE *Die = getDIE(GV))
     115             :     return Die;
     116             : 
     117             :   assert(GV);
     118             : 
     119             :   auto *GVContext = GV->getScope();
     120             :   auto *GTy = DD->resolve(GV->getType());
     121             : 
     122             :   // Construct the context before querying for the existence of the DIE in
     123             :   // case such construction creates the DIE.
     124        4287 :   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
     125             : 
     126             :   // Add to map.
     127        8574 :   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
     128             :   DIScope *DeclContext;
     129             :   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
     130             :     DeclContext = resolve(SDMDecl->getScope());
     131             :     assert(SDMDecl->isStaticMember() && "Expected static member decl");
     132             :     assert(GV->isDefinition());
     133             :     // We need the declaration DIE that is in the static member's class.
     134         142 :     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
     135         142 :     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
     136             :     // If the global variable's type is different from the one in the class
     137             :     // member type, assume that it's more specific and also emit it.
     138         142 :     if (GTy != DD->resolve(SDMDecl->getBaseType()))
     139           7 :       addType(*VariableDIE, GTy);
     140             :   } else {
     141             :     DeclContext = GV->getScope();
     142             :     // Add name and type.
     143        4145 :     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
     144        4145 :     addType(*VariableDIE, GTy);
     145             : 
     146             :     // Add scoping info.
     147        4145 :     if (!GV->isLocalToUnit())
     148        1622 :       addFlag(*VariableDIE, dwarf::DW_AT_external);
     149             : 
     150             :     // Add line number info.
     151        4145 :     addSourceLine(*VariableDIE, GV);
     152             :   }
     153             : 
     154        4287 :   if (!GV->isDefinition())
     155         215 :     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
     156             :   else
     157        4072 :     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
     158             : 
     159        4287 :   if (uint32_t AlignInBytes = GV->getAlignInBytes())
     160          38 :     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
     161             :             AlignInBytes);
     162             : 
     163             :   // Add location.
     164             :   bool addToAccelTable = false;
     165             :   DIELoc *Loc = nullptr;
     166             :   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
     167        8343 :   for (const auto &GE : GlobalExprs) {
     168        4080 :     const GlobalVariable *Global = GE.Var;
     169        4080 :     const DIExpression *Expr = GE.Expr;
     170             : 
     171             :     // For compatibility with DWARF 3 and earlier,
     172             :     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
     173             :     // DW_AT_const_value(X).
     174        4080 :     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
     175             :       addToAccelTable = true;
     176          24 :       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
     177          24 :       break;
     178             :     }
     179             : 
     180             :     // We cannot describe the location of dllimport'd variables: the
     181             :     // computation of their address requires loads from the IAT.
     182        4056 :     if (Global && Global->hasDLLImportStorageClass())
     183             :       continue;
     184             : 
     185             :     // Nothing to describe without address or constant.
     186        4055 :     if (!Global && (!Expr || !Expr->isConstant()))
     187        1144 :       continue;
     188             : 
     189        2911 :     if (Global && Global->isThreadLocal() &&
     190          36 :         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
     191             :       continue;
     192             : 
     193        2910 :     if (!Loc) {
     194             :       addToAccelTable = true;
     195        2902 :       Loc = new (DIEValueAllocator) DIELoc;
     196        2902 :       DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
     197             :     }
     198             : 
     199        2910 :     if (Expr)
     200        2910 :       DwarfExpr->addFragmentOffset(Expr);
     201             : 
     202        2910 :     if (Global) {
     203        2903 :       const MCSymbol *Sym = Asm->getSymbol(Global);
     204        2903 :       if (Global->isThreadLocal()) {
     205          35 :         if (Asm->TM.useEmulatedTLS()) {
     206             :           // TODO: add debug info for emulated thread local mode.
     207             :         } else {
     208             :           // FIXME: Make this work with -gsplit-dwarf.
     209          32 :           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
     210             :           assert((PointerSize == 4 || PointerSize == 8) &&
     211             :                  "Add support for other sizes if necessary");
     212             :           // Based on GCC's support for TLS:
     213          32 :           if (!DD->useSplitDwarf()) {
     214             :             // 1) Start with a constNu of the appropriate pointer size
     215          52 :             addUInt(*Loc, dwarf::DW_FORM_data1,
     216             :                     PointerSize == 4 ? dwarf::DW_OP_const4u
     217             :                                      : dwarf::DW_OP_const8u);
     218             :             // 2) containing the (relocated) offset of the TLS variable
     219             :             //    within the module's TLS block.
     220          28 :             addExpr(*Loc, dwarf::DW_FORM_udata,
     221          28 :                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
     222             :           } else {
     223           4 :             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
     224           4 :             addUInt(*Loc, dwarf::DW_FORM_udata,
     225           8 :                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
     226             :           }
     227             :           // 3) followed by an OP to make the debugger do a TLS lookup.
     228          32 :           addUInt(*Loc, dwarf::DW_FORM_data1,
     229          32 :                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
     230             :                                         : dwarf::DW_OP_form_tls_address);
     231             :         }
     232             :       } else {
     233        2868 :         DD->addArangeLabel(SymbolCU(this, Sym));
     234        2868 :         addOpAddress(*Loc, Sym);
     235             :       }
     236             :     }
     237             :     // Global variables attached to symbols are memory locations.
     238             :     // It would be better if this were unconditional, but malformed input that
     239             :     // mixes non-fragments and fragments for the same variable is too expensive
     240             :     // to detect in the verifier.
     241        2910 :     if (DwarfExpr->isUnknownLocation())
     242             :       DwarfExpr->setMemoryLocationKind();
     243        5820 :     DwarfExpr->addExpression(Expr);
     244             :   }
     245        4287 :   if (Loc)
     246        2902 :     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
     247             : 
     248        4287 :   if (DD->useAllLinkageNames())
     249        4276 :     addLinkageName(*VariableDIE, GV->getLinkageName());
     250             : 
     251        4287 :   if (addToAccelTable) {
     252        2926 :     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
     253             : 
     254             :     // If the linkage name is different than the name, go ahead and output
     255             :     // that as well into the name table.
     256        1171 :     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
     257        1171 :         DD->useAllLinkageNames())
     258        1166 :       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
     259             :   }
     260             : 
     261             :   return VariableDIE;
     262             : }
     263             : 
     264       38727 : void DwarfCompileUnit::addRange(RangeSpan Range) {
     265       38727 :   bool SameAsPrevCU = this == DD->getPrevCU();
     266             :   DD->setPrevCU(this);
     267             :   // If we have no current ranges just add the range and return, otherwise,
     268             :   // check the current section and CU against the previous section and CU we
     269             :   // emitted into and the subprogram was contained within. If these are the
     270             :   // same then extend our current range, otherwise add this as a new range.
     271       74783 :   if (CURanges.empty() || !SameAsPrevCU ||
     272       36056 :       (&CURanges.back().getEnd()->getSection() !=
     273       36056 :        &Range.getEnd()->getSection())) {
     274       34879 :     CURanges.push_back(Range);
     275       34879 :     return;
     276             :   }
     277             : 
     278        3848 :   CURanges.back().setEnd(Range.getEnd());
     279             : }
     280             : 
     281        2843 : void DwarfCompileUnit::initStmtList() {
     282        2843 :   if (CUNode->isDebugDirectivesOnly())
     283             :     return;
     284             : 
     285             :   // Define start line table label for each Compile Unit.
     286             :   MCSymbol *LineTableStartSym;
     287        2841 :   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
     288        2841 :   if (DD->useSectionsAsReferences()) {
     289           8 :     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
     290             :   } else {
     291             :     LineTableStartSym =
     292        5666 :         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
     293             :   }
     294             : 
     295             :   // DW_AT_stmt_list is a offset of line number information for this
     296             :   // compile unit in debug_line section. For split dwarf this is
     297             :   // left in the skeleton CU and so not included.
     298             :   // The line table entries are not always emitted in assembly, so it
     299             :   // is not okay to use line_table_start here.
     300             :   StmtListValue =
     301             :       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
     302        5682 :                       TLOF.getDwarfLineSection()->getBeginSymbol());
     303             : }
     304             : 
     305          20 : void DwarfCompileUnit::applyStmtList(DIE &D) {
     306          40 :   D.addValue(DIEValueAllocator, *StmtListValue);
     307          20 : }
     308             : 
     309      121564 : void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
     310             :                                        const MCSymbol *End) {
     311             :   assert(Begin && "Begin label should not be null!");
     312             :   assert(End && "End label should not be null!");
     313             :   assert(Begin->isDefined() && "Invalid starting label");
     314             :   assert(End->isDefined() && "Invalid end label");
     315             : 
     316      121564 :   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
     317      121564 :   if (DD->getDwarfVersion() < 4)
     318         311 :     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
     319             :   else
     320      121253 :     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
     321      121564 : }
     322             : 
     323             : // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
     324             : // and DW_AT_high_pc attributes. If there are global variables in this
     325             : // scope then create and insert DIEs for these variables.
     326       37773 : DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
     327       37773 :   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
     328             : 
     329       37773 :   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
     330       38079 :   if (DD->useAppleExtensionAttributes() &&
     331         306 :       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
     332             :           *DD->getCurrentFunction()))
     333         213 :     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
     334             : 
     335             :   // Only include DW_AT_frame_base in full debug info
     336       37773 :   if (!includeMinimalInlineScopes()) {
     337       33233 :     if (Asm->MF->getTarget().getTargetTriple().isNVPTX()) {
     338           6 :       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
     339           6 :       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
     340           6 :       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
     341             :     } else {
     342       33227 :       const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
     343       33227 :       MachineLocation Location(RI->getFrameRegister(*Asm->MF));
     344       33227 :       if (RI->isPhysicalRegister(Location.getReg()))
     345       33227 :         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
     346             :     }
     347             :   }
     348             : 
     349             :   // Add name to the name table, we do this here because we're guaranteed
     350             :   // to have concrete versions of our DW_TAG_subprogram nodes.
     351       37773 :   DD->addSubprogramNames(*CUNode, SP, *SPDie);
     352             : 
     353       37773 :   return *SPDie;
     354             : }
     355             : 
     356             : // Construct a DIE for this scope.
     357      203320 : void DwarfCompileUnit::constructScopeDIE(
     358             :     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
     359      203320 :   if (!Scope || !Scope->getScopeNode())
     360       39178 :     return;
     361             : 
     362             :   auto *DS = Scope->getScopeNode();
     363             : 
     364             :   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
     365             :          "Only handle inlined subprograms here, use "
     366             :          "constructSubprogramScopeDIE for non-inlined "
     367             :          "subprograms");
     368             : 
     369             :   SmallVector<DIE *, 8> Children;
     370             : 
     371             :   // We try to create the scope DIE first, then the children DIEs. This will
     372             :   // avoid creating un-used children then removing them later when we find out
     373             :   // the scope DIE is null.
     374             :   DIE *ScopeDIE;
     375      203320 :   if (Scope->getParent() && isa<DISubprogram>(DS)) {
     376      161106 :     ScopeDIE = constructInlinedScopeDIE(Scope);
     377      161106 :     if (!ScopeDIE)
     378             :       return;
     379             :     // We create children when the scope DIE is not null.
     380      161106 :     createScopeChildrenDIE(Scope, Children);
     381             :   } else {
     382             :     // Early exit when we know the scope DIE is going to be null.
     383       42214 :     if (DD->isLexicalScopeDIENull(Scope))
     384       39178 :       return;
     385             : 
     386       42214 :     bool HasNonScopeChildren = false;
     387             : 
     388             :     // We create children here when we know the scope DIE is not going to be
     389             :     // null and the children will be added to the scope DIE.
     390       42214 :     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
     391             : 
     392             :     // If there are only other scopes as children, put them directly in the
     393             :     // parent instead, as this scope would serve no purpose.
     394       42214 :     if (!HasNonScopeChildren) {
     395       39178 :       FinalChildren.insert(FinalChildren.end(),
     396             :                            std::make_move_iterator(Children.begin()),
     397             :                            std::make_move_iterator(Children.end()));
     398       39178 :       return;
     399             :     }
     400        3036 :     ScopeDIE = constructLexicalScopeDIE(Scope);
     401             :     assert(ScopeDIE && "Scope DIE should not be null.");
     402             :   }
     403             : 
     404             :   // Add children
     405      329854 :   for (auto &I : Children)
     406      165712 :     ScopeDIE->addChild(std::move(I));
     407             : 
     408      164142 :   FinalChildren.push_back(std::move(ScopeDIE));
     409             : }
     410             : 
     411       82187 : void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
     412             :                                          SmallVector<RangeSpan, 2> Range) {
     413       82187 :   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
     414             : 
     415             :   // Emit the offset into .debug_ranges or .debug_rnglists as a relocatable
     416             :   // label. emitDIE() will handle emitting it appropriately.
     417             :   const MCSymbol *RangeSectionSym =
     418       82187 :       DD->getDwarfVersion() >= 5
     419           6 :           ? TLOF.getDwarfRnglistsSection()->getBeginSymbol()
     420       82187 :           : TLOF.getDwarfRangesSection()->getBeginSymbol();
     421             : 
     422      246561 :   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
     423             : 
     424             :   // Under fission, ranges are specified by constant offsets relative to the
     425             :   // CU's DW_AT_GNU_ranges_base.
     426             :   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
     427             :   // fission until we support the forms using the .debug_addr section
     428             :   // (DW_RLE_startx_endx etc.).
     429       82187 :   if (isDwoUnit()) {
     430         132 :     if (DD->getDwarfVersion() < 5)
     431         132 :       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
     432         132 :                       RangeSectionSym);
     433             :   } else {
     434       82055 :     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
     435       82055 :                     RangeSectionSym);
     436             :   }
     437             : 
     438             :   // Add the range list to the set of ranges to be emitted.
     439       82319 :   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
     440       82187 : }
     441             : 
     442      165978 : void DwarfCompileUnit::attachRangesOrLowHighPC(
     443             :     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
     444      331956 :   if (Ranges.size() == 1 || !DD->useRangesSection()) {
     445       83791 :     const RangeSpan &Front = Ranges.front();
     446             :     const RangeSpan &Back = Ranges.back();
     447       83791 :     attachLowHighPC(Die, Front.getStart(), Back.getEnd());
     448             :   } else
     449      164374 :     addScopeRangeList(Die, std::move(Ranges));
     450      165978 : }
     451             : 
     452      163617 : void DwarfCompileUnit::attachRangesOrLowHighPC(
     453             :     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
     454             :   SmallVector<RangeSpan, 2> List;
     455      163617 :   List.reserve(Ranges.size());
     456      488741 :   for (const InsnRange &R : Ranges)
     457      325124 :     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
     458      325124 :                              DD->getLabelAfterInsn(R.second)));
     459      327234 :   attachRangesOrLowHighPC(Die, std::move(List));
     460      163617 : }
     461             : 
     462             : // This scope represents inlined body of a function. Construct DIE to
     463             : // represent this concrete inlined copy of the function.
     464      161106 : DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
     465             :   assert(Scope->getScopeNode());
     466      161106 :   auto *DS = Scope->getScopeNode();
     467      161106 :   auto *InlinedSP = getDISubprogram(DS);
     468             :   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
     469             :   // was inlined from another compile unit.
     470      161106 :   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
     471             :   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
     472             : 
     473      161106 :   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
     474      161106 :   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
     475             : 
     476      161106 :   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
     477             : 
     478             :   // Add the call site information to the DIE.
     479      161106 :   const DILocation *IA = Scope->getInlinedAt();
     480      322212 :   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
     481      161106 :           getOrCreateSourceID(IA->getFile()));
     482      322212 :   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
     483       26388 :   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
     484           8 :     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
     485             :             IA->getDiscriminator());
     486             : 
     487             :   // Add name to the name table, we do this here because we're guaranteed
     488             :   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
     489      161106 :   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
     490             : 
     491      161106 :   return ScopeDIE;
     492             : }
     493             : 
     494             : // Construct new DW_TAG_lexical_block for this scope and attach
     495             : // DW_AT_low_pc/DW_AT_high_pc labels.
     496        3036 : DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
     497        3036 :   if (DD->isLexicalScopeDIENull(Scope))
     498             :     return nullptr;
     499             : 
     500        3036 :   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
     501        3036 :   if (Scope->isAbstractScope())
     502             :     return ScopeDIE;
     503             : 
     504        2511 :   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
     505             : 
     506        2511 :   return ScopeDIE;
     507             : }
     508             : 
     509             : /// constructVariableDIE - Construct a DIE for the given DbgVariable.
     510      131784 : DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
     511      131784 :   auto D = constructVariableDIEImpl(DV, Abstract);
     512             :   DV.setDIE(*D);
     513      131784 :   return D;
     514             : }
     515             : 
     516           6 : DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
     517             :                                          const LexicalScope &Scope) {
     518           6 :   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
     519          12 :   insertDIE(DL.getLabel(), LabelDie);
     520             :   DL.setDIE(*LabelDie);
     521             : 
     522           6 :   if (Scope.isAbstractScope())
     523           1 :     applyLabelAttributes(DL, *LabelDie);
     524             : 
     525           6 :   return LabelDie;
     526             : }
     527             : 
     528      131784 : DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
     529             :                                                 bool Abstract) {
     530             :   // Define variable debug information entry.
     531      131784 :   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
     532      263568 :   insertDIE(DV.getVariable(), VariableDie);
     533             : 
     534      131784 :   if (Abstract) {
     535       14857 :     applyVariableAttributes(DV, *VariableDie);
     536       14857 :     return VariableDie;
     537             :   }
     538             : 
     539             :   // Add variable address.
     540             : 
     541      116927 :   unsigned Offset = DV.getDebugLocListIndex();
     542      116927 :   if (Offset != ~0U) {
     543       46920 :     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
     544       46920 :     return VariableDie;
     545             :   }
     546             : 
     547             :   // Check if variable is described by a DBG_VALUE instruction.
     548       70007 :   if (const MachineInstr *DVInsn = DV.getMInsn()) {
     549             :     assert(DVInsn->getNumOperands() == 4);
     550       26880 :     if (DVInsn->getOperand(0).isReg()) {
     551        8530 :       auto RegOp = DVInsn->getOperand(0);
     552        8530 :       auto Op1 = DVInsn->getOperand(1);
     553             :       // If the second operand is an immediate, this is an indirect value.
     554             :       assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
     555             :       MachineLocation Location(RegOp.getReg(), Op1.isImm());
     556        8530 :       addVariableAddress(DV, *VariableDie, Location);
     557        4910 :     } else if (DVInsn->getOperand(0).isImm()) {
     558             :       // This variable is described by a single constant.
     559             :       // Check whether it has a DIExpression.
     560             :       auto *Expr = DV.getSingleExpression();
     561          81 :       if (Expr && Expr->getNumElements()) {
     562             :         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
     563          81 :         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
     564             :         // If there is an expression, emit raw unsigned bytes.
     565          81 :         DwarfExpr.addFragmentOffset(Expr);
     566          81 :         DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm());
     567          81 :         DwarfExpr.addExpression(Expr);
     568          81 :         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
     569             :       } else
     570        4823 :         addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
     571           6 :     } else if (DVInsn->getOperand(0).isFPImm())
     572           5 :       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
     573           1 :     else if (DVInsn->getOperand(0).isCImm())
     574           1 :       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
     575             :                        DV.getType());
     576             : 
     577       13440 :     return VariableDie;
     578             :   }
     579             : 
     580             :   // .. else use frame index.
     581       56567 :   if (!DV.hasFrameIndexExprs())
     582             :     return VariableDie;
     583             : 
     584             :   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
     585       54507 :   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
     586      109017 :   for (auto &Fragment : DV.getFrameIndexExprs()) {
     587       54510 :     unsigned FrameReg = 0;
     588       54510 :     const DIExpression *Expr = Fragment.Expr;
     589       54510 :     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
     590       54510 :     int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
     591       54510 :     DwarfExpr.addFragmentOffset(Expr);
     592             :     SmallVector<uint64_t, 8> Ops;
     593       54510 :     Ops.push_back(dwarf::DW_OP_plus_uconst);
     594       54510 :     Ops.push_back(Offset);
     595       54510 :     Ops.append(Expr->elements_begin(), Expr->elements_end());
     596             :     DIExpressionCursor Cursor(Ops);
     597             :     DwarfExpr.setMemoryLocationKind();
     598       54510 :     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
     599           1 :       addOpAddress(*Loc, FrameSymbol);
     600             :     else
     601       54509 :       DwarfExpr.addMachineRegExpression(
     602       54509 :           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
     603       54510 :     DwarfExpr.addExpression(std::move(Cursor));
     604             :   }
     605       54507 :   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
     606             : 
     607             :   return VariableDie;
     608             : }
     609             : 
     610      131784 : DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
     611             :                                             const LexicalScope &Scope,
     612             :                                             DIE *&ObjectPointer) {
     613      131784 :   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
     614      131784 :   if (DV.isObjectPointer())
     615       40547 :     ObjectPointer = Var;
     616      131784 :   return Var;
     617             : }
     618             : 
     619             : /// Return all DIVariables that appear in count: expressions.
     620       15262 : static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
     621             :   SmallVector<const DIVariable *, 2> Result;
     622       15262 :   auto *Array = dyn_cast<DICompositeType>(Var->getType());
     623        2674 :   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
     624             :     return Result;
     625        1488 :   for (auto *El : Array->getElements()) {
     626             :     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
     627             :       auto Count = Subrange->getCount();
     628          15 :       if (auto *Dependency = Count.dyn_cast<DIVariable *>())
     629          15 :         Result.push_back(Dependency);
     630             :     }
     631             :   }
     632             :   return Result;
     633             : }
     634             : 
     635             : /// Sort local variables so that variables appearing inside of helper
     636             : /// expressions come first.
     637             : static SmallVector<DbgVariable *, 8>
     638      261485 : sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
     639             :   SmallVector<DbgVariable *, 8> Result;
     640             :   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
     641             :   // Map back from a DIVariable to its containing DbgVariable.
     642             :   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
     643             :   // Set of DbgVariables in Result.
     644             :   SmallDenseSet<DbgVariable *, 8> Visited;
     645             :   // For cycle detection.
     646             :   SmallDenseSet<DbgVariable *, 8> Visiting;
     647             : 
     648             :   // Initialize the worklist and the DIVariable lookup table.
     649      276747 :   for (auto Var : reverse(Input)) {
     650       15262 :     DbgVar.insert({Var->getVariable(), Var});
     651       15262 :     WorkList.push_back({Var, 0});
     652             :   }
     653             : 
     654             :   // Perform a stable topological sort by doing a DFS.
     655      292024 :   while (!WorkList.empty()) {
     656       30539 :     auto Item = WorkList.back();
     657       30539 :     DbgVariable *Var = Item.getPointer();
     658             :     bool visitedAllDependencies = Item.getInt();
     659             :     WorkList.pop_back();
     660             : 
     661             :     // Dependency is in a different lexical scope or a global.
     662       30539 :     if (!Var)
     663       15277 :       continue;
     664             : 
     665             :     // Already handled.
     666             :     if (Visited.count(Var))
     667          12 :       continue;
     668             : 
     669             :     // Add to Result if all dependencies are visited.
     670       30524 :     if (visitedAllDependencies) {
     671             :       Visited.insert(Var);
     672       15262 :       Result.push_back(Var);
     673       15262 :       continue;
     674             :     }
     675             : 
     676             :     // Detect cycles.
     677             :     auto Res = Visiting.insert(Var);
     678       15262 :     if (!Res.second) {
     679             :       assert(false && "dependency cycle in local variables");
     680           0 :       return Result;
     681             :     }
     682             : 
     683             :     // Push dependencies and this node onto the worklist, so that this node is
     684             :     // visited again after all of its dependencies are handled.
     685       30524 :     WorkList.push_back({Var, 1});
     686       30539 :     for (auto *Dependency : dependencies(Var)) {
     687          15 :       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
     688          30 :       WorkList.push_back({DbgVar[Dep], 0});
     689             :     }
     690             :   }
     691             :   return Result;
     692             : }
     693             : 
     694      261485 : DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
     695             :                                               SmallVectorImpl<DIE *> &Children,
     696             :                                               bool *HasNonScopeChildren) {
     697             :   assert(Children.empty());
     698      261485 :   DIE *ObjectPointer = nullptr;
     699             : 
     700             :   // Emit function arguments (order is significant).
     701      784455 :   auto Vars = DU->getScopeVariables().lookup(Scope);
     702      378007 :   for (auto &DV : Vars.Args)
     703      116522 :     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
     704             : 
     705             :   // Emit local variables.
     706      261485 :   auto Locals = sortLocalVars(Vars.Locals);
     707      276747 :   for (DbgVariable *DV : Locals)
     708       15262 :     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
     709             : 
     710             :   // Skip imported directives in gmlt-like data.
     711      261485 :   if (!includeMinimalInlineScopes()) {
     712             :     // There is no need to emit empty lexical block DIE.
     713      122295 :     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
     714         238 :       Children.push_back(
     715         119 :           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
     716             :   }
     717             : 
     718      261485 :   if (HasNonScopeChildren)
     719       42214 :     *HasNonScopeChildren = !Children.empty();
     720             : 
     721      784461 :   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
     722           6 :     Children.push_back(constructLabelDIE(*DL, *Scope));
     723             : 
     724      464805 :   for (LexicalScope *LS : Scope->getChildren())
     725      203320 :     constructScopeDIE(LS, Children);
     726             : 
     727      261485 :   return ObjectPointer;
     728             : }
     729             : 
     730       37773 : void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) {
     731       37773 :   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
     732             : 
     733       37773 :   if (Scope) {
     734             :     assert(!Scope->getInlinedAt());
     735             :     assert(!Scope->isAbstractScope());
     736             :     // Collect lexical scope children first.
     737             :     // ObjectPointer might be a local (non-argument) local variable if it's a
     738             :     // block's synthetic this pointer.
     739       37713 :     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
     740       17372 :       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
     741             :   }
     742             : 
     743             :   // If this is a variadic function, add an unspecified parameter.
     744             :   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
     745             : 
     746             :   // If we have a single element of null, it is a function that returns void.
     747             :   // If we have more than one elements and the last one is null, it is a
     748             :   // variadic function.
     749       37809 :   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
     750          36 :       !includeMinimalInlineScopes())
     751             :     ScopeDIE.addChild(
     752          35 :         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
     753       37773 : }
     754             : 
     755       58165 : DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
     756             :                                                  DIE &ScopeDIE) {
     757             :   // We create children when the scope DIE is not null.
     758             :   SmallVector<DIE *, 8> Children;
     759       58165 :   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
     760             : 
     761             :   // Add children
     762      188504 :   for (auto &I : Children)
     763      130339 :     ScopeDIE.addChild(std::move(I));
     764             : 
     765       58165 :   return ObjectPointer;
     766             : }
     767             : 
     768       62130 : void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
     769             :     LexicalScope *Scope) {
     770       62130 :   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
     771       62130 :   if (AbsDef)
     772             :     return;
     773             : 
     774       20452 :   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
     775             : 
     776             :   DIE *ContextDIE;
     777             :   DwarfCompileUnit *ContextCU = this;
     778             : 
     779       20452 :   if (includeMinimalInlineScopes())
     780             :     ContextDIE = &getUnitDie();
     781             :   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
     782             :   // the important distinction that the debug node is not associated with the
     783             :   // DIE (since the debug node will be associated with the concrete DIE, if
     784             :   // any). It could be refactored to some common utility function.
     785             :   else if (auto *SPDecl = SP->getDeclaration()) {
     786             :     ContextDIE = &getUnitDie();
     787        4460 :     getOrCreateSubprogramDIE(SPDecl);
     788             :   } else {
     789        1474 :     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
     790             :     // The scope may be shared with a subprogram that has already been
     791             :     // constructed in another CU, in which case we need to construct this
     792             :     // subprogram in the same CU.
     793        1473 :     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
     794             :   }
     795             : 
     796             :   // Passing null as the associated node because the abstract definition
     797             :   // shouldn't be found by lookup.
     798       20452 :   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
     799       20452 :   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
     800             : 
     801       20452 :   if (!ContextCU->includeMinimalInlineScopes())
     802        5933 :     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
     803       20452 :   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
     804        3888 :     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
     805             : }
     806             : 
     807      104763 : DIE *DwarfCompileUnit::constructImportedEntityDIE(
     808             :     const DIImportedEntity *Module) {
     809      104763 :   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
     810      104763 :   insertDIE(Module, IMDie);
     811             :   DIE *EntityDie;
     812             :   auto *Entity = resolve(Module->getEntity());
     813             :   if (auto *NS = dyn_cast<DINamespace>(Entity))
     814         605 :     EntityDie = getOrCreateNameSpace(NS);
     815             :   else if (auto *M = dyn_cast<DIModule>(Entity))
     816           7 :     EntityDie = getOrCreateModule(M);
     817             :   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
     818       86770 :     EntityDie = getOrCreateSubprogramDIE(SP);
     819             :   else if (auto *T = dyn_cast<DIType>(Entity))
     820       17112 :     EntityDie = getOrCreateTypeDIE(T);
     821             :   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
     822         268 :     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
     823             :   else
     824           1 :     EntityDie = getDIE(Entity);
     825             :   assert(EntityDie);
     826      104763 :   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
     827      104763 :   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
     828      104763 :   StringRef Name = Module->getName();
     829      104763 :   if (!Name.empty())
     830          42 :     addString(*IMDie, dwarf::DW_AT_name, Name);
     831             : 
     832      104763 :   return IMDie;
     833             : }
     834             : 
     835       45839 : void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
     836       45839 :   DIE *D = getDIE(SP);
     837       91678 :   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
     838         699 :     if (D)
     839             :       // If this subprogram has an abstract definition, reference that
     840         694 :       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
     841             :   } else {
     842             :     assert(D || includeMinimalInlineScopes());
     843       45140 :     if (D)
     844             :       // And attach the attributes
     845       37079 :       applySubprogramAttributesToDefinition(SP, *D);
     846             :   }
     847       45839 : }
     848             : 
     849      116932 : void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
     850      116932 :   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
     851             : 
     852      116932 :   auto *Die = Entity->getDIE();
     853             :   /// Label may be used to generate DW_AT_low_pc, so put it outside
     854             :   /// if/else block.
     855             :   const DbgLabel *Label = nullptr;
     856      116932 :   if (AbsEntity && AbsEntity->getDIE()) {
     857       55943 :     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
     858             :     Label = dyn_cast<const DbgLabel>(Entity);
     859             :   } else {
     860             :     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
     861       60985 :       applyVariableAttributes(*Var, *Die);
     862             :     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
     863           4 :       applyLabelAttributes(*Label, *Die);
     864             :     else
     865           0 :       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
     866             :   }
     867             : 
     868             :   if (Label) {
     869           5 :     const MCSymbol *Sym = Label->getSymbol();
     870           5 :     addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
     871             :   }
     872      116932 : }
     873             : 
     874      279214 : DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
     875      279214 :   auto &AbstractEntities = getAbstractEntities();
     876      279214 :   auto I = AbstractEntities.find(Node);
     877      279214 :   if (I != AbstractEntities.end())
     878      141821 :     return I->second.get();
     879             :   return nullptr;
     880             : }
     881             : 
     882       14858 : void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
     883             :                                             LexicalScope *Scope) {
     884             :   assert(Scope && Scope->isAbstractScope());
     885       14858 :   auto &Entity = getAbstractEntities()[Node];
     886       29716 :   if (isa<const DILocalVariable>(Node)) {
     887       14857 :     Entity = llvm::make_unique<DbgVariable>(
     888             :                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
     889       29714 :     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
     890           1 :   } else if (isa<const DILabel>(Node)) {
     891             :     Entity = llvm::make_unique<DbgLabel>(
     892             :                         cast<const DILabel>(Node), nullptr /* IA */);
     893           2 :     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
     894             :   }
     895       14858 : }
     896             : 
     897        3416 : void DwarfCompileUnit::emitHeader(bool UseOffsets) {
     898             :   // Don't bother labeling the .dwo unit, as its offset isn't used.
     899        3416 :   if (!Skeleton && !DD->useSectionsAsReferences()) {
     900        5662 :     LabelBegin = Asm->createTempSymbol("cu_begin");
     901        5662 :     Asm->OutStreamer->EmitLabel(LabelBegin);
     902             :   }
     903             : 
     904        3416 :   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
     905        2839 :                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
     906             :                                                       : dwarf::DW_UT_compile;
     907        3416 :   DwarfUnit::emitCommonHeader(UseOffsets, UT);
     908        3416 :   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
     909          16 :     Asm->emitInt64(getDWOId());
     910        3416 : }
     911             : 
     912      140831 : bool DwarfCompileUnit::hasDwarfPubSections() const {
     913      140831 :   switch (CUNode->getNameTableKind()) {
     914             :   case DICompileUnit::DebugNameTableKind::None:
     915             :     return false;
     916             :     // Opting in to GNU Pubnames/types overrides the default to ensure these are
     917             :     // generated for things like Gold's gdb_index generation.
     918       26192 :   case DICompileUnit::DebugNameTableKind::GNU:
     919       26192 :     return true;
     920        5050 :   case DICompileUnit::DebugNameTableKind::Default:
     921        5050 :     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
     922        3624 :            !CUNode->isDebugDirectivesOnly();
     923             :   }
     924           0 :   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
     925             : }
     926             : 
     927             : /// addGlobalName - Add a new global name to the compile unit.
     928       65080 : void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
     929             :                                      const DIScope *Context) {
     930       65080 :   if (!hasDwarfPubSections())
     931       54086 :     return;
     932       35766 :   std::string FullName = getParentContextString(Context) + Name.str();
     933       10994 :   GlobalNames[FullName] = &Die;
     934             : }
     935             : 
     936           8 : void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
     937             :                                                 const DIScope *Context) {
     938           8 :   if (!hasDwarfPubSections())
     939           0 :     return;
     940          24 :   std::string FullName = getParentContextString(Context) + Name.str();
     941             :   // Insert, allowing the entry to remain as-is if it's already present
     942             :   // This way the CU-level type DIE is preferred over the "can't describe this
     943             :   // type as a unit offset because it's not really in the CU at all, it's only
     944             :   // in a type unit"
     945          20 :   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
     946             : }
     947             : 
     948             : /// Add a new global type to the unit.
     949       69983 : void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
     950             :                                      const DIScope *Context) {
     951       69983 :   if (!hasDwarfPubSections())
     952       53885 :     return;
     953       35593 :   std::string FullName = getParentContextString(Context) + Ty->getName().str();
     954       16098 :   GlobalTypes[FullName] = &Die;
     955             : }
     956             : 
     957          76 : void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
     958             :                                              const DIScope *Context) {
     959          76 :   if (!hasDwarfPubSections())
     960           0 :     return;
     961         152 :   std::string FullName = getParentContextString(Context) + Ty->getName().str();
     962             :   // Insert, allowing the entry to remain as-is if it's already present
     963             :   // This way the CU-level type DIE is preferred over the "can't describe this
     964             :   // type as a unit offset because it's not really in the CU at all, it's only
     965             :   // in a type unit"
     966         154 :   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
     967             : }
     968             : 
     969             : /// addVariableAddress - Add DW_AT_location attribute for a
     970             : /// DbgVariable based on provided MachineLocation.
     971        8530 : void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
     972             :                                           MachineLocation Location) {
     973             :   // addBlockByrefAddress is obsolete and will be removed soon.
     974             :   // The clang frontend always generates block byref variables with a
     975             :   // complex expression that encodes exactly what addBlockByrefAddress
     976             :   // would do.
     977             :   assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
     978             :          "block byref variable without a complex expression");
     979        8530 :   if (DV.hasComplexAddress())
     980        1579 :     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
     981             :   else
     982        6951 :     addAddress(Die, dwarf::DW_AT_location, Location);
     983        8530 : }
     984             : 
     985             : /// Add an address attribute to a die based on the location provided.
     986       40178 : void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
     987             :                                   const MachineLocation &Location) {
     988       40178 :   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
     989       40178 :   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
     990       40178 :   if (Location.isIndirect())
     991             :     DwarfExpr.setMemoryLocationKind();
     992             : 
     993             :   DIExpressionCursor Cursor({});
     994       40178 :   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
     995       40178 :   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
     996             :     return;
     997       35505 :   DwarfExpr.addExpression(std::move(Cursor));
     998             : 
     999             :   // Now attach the location information to the DIE.
    1000       35505 :   addBlock(Die, Attribute, DwarfExpr.finalize());
    1001             : }
    1002             : 
    1003             : /// Start with the address based on the location provided, and generate the
    1004             : /// DWARF information necessary to find the actual variable given the extra
    1005             : /// address information encoded in the DbgVariable, starting from the starting
    1006             : /// location.  Add the DWARF information to the die.
    1007        1579 : void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
    1008             :                                          dwarf::Attribute Attribute,
    1009             :                                          const MachineLocation &Location) {
    1010        1579 :   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
    1011        1579 :   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
    1012             :   const DIExpression *DIExpr = DV.getSingleExpression();
    1013        1579 :   DwarfExpr.addFragmentOffset(DIExpr);
    1014        1579 :   if (Location.isIndirect())
    1015             :     DwarfExpr.setMemoryLocationKind();
    1016             : 
    1017             :   DIExpressionCursor Cursor(DIExpr);
    1018        1579 :   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
    1019        1579 :   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
    1020             :     return;
    1021         186 :   DwarfExpr.addExpression(std::move(Cursor));
    1022             : 
    1023             :   // Now attach the location information to the DIE.
    1024         186 :   addBlock(Die, Attribute, DwarfExpr.finalize());
    1025             : }
    1026             : 
    1027             : /// Add a Dwarf loclistptr attribute data and value.
    1028       46920 : void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
    1029             :                                        unsigned Index) {
    1030       46920 :   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
    1031             :                                                 : dwarf::DW_FORM_data4;
    1032       46920 :   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
    1033       46920 : }
    1034             : 
    1035       75842 : void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
    1036             :                                                DIE &VariableDie) {
    1037       75842 :   StringRef Name = Var.getName();
    1038       75842 :   if (!Name.empty())
    1039       73392 :     addString(VariableDie, dwarf::DW_AT_name, Name);
    1040             :   const auto *DIVar = Var.getVariable();
    1041       75842 :   if (DIVar)
    1042       75842 :     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
    1043          12 :       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
    1044             :               AlignInBytes);
    1045             : 
    1046       75842 :   addSourceLine(VariableDie, DIVar);
    1047       75842 :   addType(VariableDie, Var.getType());
    1048       75842 :   if (Var.isArtificial())
    1049       21194 :     addFlag(VariableDie, dwarf::DW_AT_artificial);
    1050       75842 : }
    1051             : 
    1052           5 : void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
    1053             :                                             DIE &LabelDie) {
    1054           5 :   StringRef Name = Label.getName();
    1055           5 :   if (!Name.empty())
    1056           5 :     addString(LabelDie, dwarf::DW_AT_name, Name);
    1057             :   const auto *DILabel = Label.getLabel();
    1058           5 :   addSourceLine(LabelDie, DILabel);
    1059           5 : }
    1060             : 
    1061             : /// Add a Dwarf expression attribute data and value.
    1062          28 : void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
    1063             :                                const MCExpr *Expr) {
    1064          28 :   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
    1065          28 : }
    1066             : 
    1067       57531 : void DwarfCompileUnit::applySubprogramAttributesToDefinition(
    1068             :     const DISubprogram *SP, DIE &SPDie) {
    1069             :   auto *SPDecl = SP->getDeclaration();
    1070             :   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
    1071       57531 :   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
    1072       57531 :   addGlobalName(SP->getName(), SPDie, Context);
    1073       57531 : }
    1074             : 
    1075     4839667 : bool DwarfCompileUnit::isDwoUnit() const {
    1076     4839667 :   return DD->useSplitDwarf() && Skeleton;
    1077             : }
    1078             : 
    1079      439211 : bool DwarfCompileUnit::includeMinimalInlineScopes() const {
    1080      439211 :   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
    1081      243500 :          (DD->useSplitDwarf() && !Skeleton);
    1082             : }

Generated by: LCOV version 1.13