1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for constructing a dwarf compile unit.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DwarfCompileUnit.h"
14 #include "AddressPool.h"
15 #include "DwarfExpression.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/CodeGen/DIE.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/TargetFrameLowering.h"
26 #include "llvm/CodeGen/TargetRegisterInfo.h"
27 #include "llvm/CodeGen/TargetSubtargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCSymbolWasm.h"
35 #include "llvm/MC/MachineLocation.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include <iterator>
40 #include <string>
41 #include <utility>
42 
43 using namespace llvm;
44 
45 static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
46 
47   //  According to DWARF Debugging Information Format Version 5,
48   //  3.1.2 Skeleton Compilation Unit Entries:
49   //  "When generating a split DWARF object file (see Section 7.3.2
50   //  on page 187), the compilation unit in the .debug_info section
51   //  is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
52   if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
53     return dwarf::DW_TAG_skeleton_unit;
54 
55   return dwarf::DW_TAG_compile_unit;
56 }
57 
58 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
59                                    AsmPrinter *A, DwarfDebug *DW,
60                                    DwarfFile *DWU, UnitKind Kind)
61     : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
62   insertDIE(Node, &getUnitDie());
63   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
64 }
65 
66 /// addLabelAddress - Add a dwarf label attribute data and value using
67 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
68 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
69                                        const MCSymbol *Label) {
70   // Don't use the address pool in non-fission or in the skeleton unit itself.
71   if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
72     return addLocalLabelAddress(Die, Attribute, Label);
73 
74   if (Label)
75     DD->addArangeLabel(SymbolCU(this, Label));
76 
77   bool UseAddrOffsetFormOrExpressions =
78       DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
79 
80   const MCSymbol *Base = nullptr;
81   if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
82     Base = DD->getSectionLabel(&Label->getSection());
83 
84   if (!Base || Base == Label) {
85     unsigned idx = DD->getAddressPool().getIndex(Label);
86     addAttribute(Die, Attribute,
87                  DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
88                                             : dwarf::DW_FORM_GNU_addr_index,
89                  DIEInteger(idx));
90     return;
91   }
92 
93   // Could be extended to work with DWARFv4 Split DWARF if that's important for
94   // someone. In that case DW_FORM_data would be used.
95   assert(DD->getDwarfVersion() >= 5 &&
96          "Addr+offset expressions are only valuable when using debug_addr (to "
97          "reduce relocations) available in DWARFv5 or higher");
98   if (DD->useAddrOffsetExpressions()) {
99     auto *Loc = new (DIEValueAllocator) DIEBlock();
100     addPoolOpAddress(*Loc, Label);
101     addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
102   } else
103     addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
104                  new (DIEValueAllocator) DIEAddrOffset(
105                      DD->getAddressPool().getIndex(Base), Label, Base));
106 }
107 
108 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
109                                             dwarf::Attribute Attribute,
110                                             const MCSymbol *Label) {
111   if (Label)
112     DD->addArangeLabel(SymbolCU(this, Label));
113 
114   if (Label)
115     addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
116   else
117     addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
118 }
119 
120 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
121   // If we print assembly, we can't separate .file entries according to
122   // compile units. Thus all files will belong to the default compile unit.
123 
124   // FIXME: add a better feature test than hasRawTextSupport. Even better,
125   // extend .file to support this.
126   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
127   if (!File)
128     return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
129                                                     CUID);
130   return Asm->OutStreamer->emitDwarfFileDirective(
131       0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
132       File->getSource(), CUID);
133 }
134 
135 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
136     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
137   // Check for pre-existence.
138   if (DIE *Die = getDIE(GV))
139     return Die;
140 
141   assert(GV);
142 
143   auto *GVContext = GV->getScope();
144   const DIType *GTy = GV->getType();
145 
146   // Construct the context before querying for the existence of the DIE in
147   // case such construction creates the DIE.
148   auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
149   DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
150     : getOrCreateContextDIE(GVContext);
151 
152   // Add to map.
153   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
154   DIScope *DeclContext;
155   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
156     DeclContext = SDMDecl->getScope();
157     assert(SDMDecl->isStaticMember() && "Expected static member decl");
158     assert(GV->isDefinition());
159     // We need the declaration DIE that is in the static member's class.
160     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
161     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
162     // If the global variable's type is different from the one in the class
163     // member type, assume that it's more specific and also emit it.
164     if (GTy != SDMDecl->getBaseType())
165       addType(*VariableDIE, GTy);
166   } else {
167     DeclContext = GV->getScope();
168     // Add name and type.
169     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
170     if (GTy)
171       addType(*VariableDIE, GTy);
172 
173     // Add scoping info.
174     if (!GV->isLocalToUnit())
175       addFlag(*VariableDIE, dwarf::DW_AT_external);
176 
177     // Add line number info.
178     addSourceLine(*VariableDIE, GV);
179   }
180 
181   if (!GV->isDefinition())
182     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
183   else
184     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
185 
186   if (uint32_t AlignInBytes = GV->getAlignInBytes())
187     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
188             AlignInBytes);
189 
190   if (MDTuple *TP = GV->getTemplateParams())
191     addTemplateParams(*VariableDIE, DINodeArray(TP));
192 
193   // Add location.
194   addLocationAttribute(VariableDIE, GV, GlobalExprs);
195 
196   return VariableDIE;
197 }
198 
199 void DwarfCompileUnit::addLocationAttribute(
200     DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
201   bool addToAccelTable = false;
202   DIELoc *Loc = nullptr;
203   Optional<unsigned> NVPTXAddressSpace;
204   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
205   for (const auto &GE : GlobalExprs) {
206     const GlobalVariable *Global = GE.Var;
207     const DIExpression *Expr = GE.Expr;
208 
209     // For compatibility with DWARF 3 and earlier,
210     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
211     // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
212     // DW_AT_const_value(X).
213     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
214       addToAccelTable = true;
215       addConstantValue(
216           *VariableDIE,
217           DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
218               *Expr->isConstant(),
219           Expr->getElement(1));
220       break;
221     }
222 
223     // We cannot describe the location of dllimport'd variables: the
224     // computation of their address requires loads from the IAT.
225     if (Global && Global->hasDLLImportStorageClass())
226       continue;
227 
228     // Nothing to describe without address or constant.
229     if (!Global && (!Expr || !Expr->isConstant()))
230       continue;
231 
232     if (Global && Global->isThreadLocal() &&
233         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
234       continue;
235 
236     if (!Loc) {
237       addToAccelTable = true;
238       Loc = new (DIEValueAllocator) DIELoc;
239       DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
240     }
241 
242     if (Expr) {
243       // According to
244       // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
245       // cuda-gdb requires DW_AT_address_class for all variables to be able to
246       // correctly interpret address space of the variable address.
247       // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
248       // sequence for the NVPTX + gdb target.
249       unsigned LocalNVPTXAddressSpace;
250       if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
251         const DIExpression *NewExpr =
252             DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
253         if (NewExpr != Expr) {
254           Expr = NewExpr;
255           NVPTXAddressSpace = LocalNVPTXAddressSpace;
256         }
257       }
258       DwarfExpr->addFragmentOffset(Expr);
259     }
260 
261     if (Global) {
262       const MCSymbol *Sym = Asm->getSymbol(Global);
263       if (Global->isThreadLocal()) {
264         if (Asm->TM.useEmulatedTLS()) {
265           // TODO: add debug info for emulated thread local mode.
266         } else {
267           // FIXME: Make this work with -gsplit-dwarf.
268           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
269           assert((PointerSize == 4 || PointerSize == 8) &&
270                  "Add support for other sizes if necessary");
271           // Based on GCC's support for TLS:
272           if (!DD->useSplitDwarf()) {
273             // 1) Start with a constNu of the appropriate pointer size
274             addUInt(*Loc, dwarf::DW_FORM_data1,
275                     PointerSize == 4 ? dwarf::DW_OP_const4u
276                                      : dwarf::DW_OP_const8u);
277             // 2) containing the (relocated) offset of the TLS variable
278             //    within the module's TLS block.
279             addExpr(*Loc,
280                     PointerSize == 4 ? dwarf::DW_FORM_data4
281                                      : dwarf::DW_FORM_data8,
282                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
283           } else {
284             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
285             addUInt(*Loc, dwarf::DW_FORM_udata,
286                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
287           }
288           // 3) followed by an OP to make the debugger do a TLS lookup.
289           addUInt(*Loc, dwarf::DW_FORM_data1,
290                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
291                                         : dwarf::DW_OP_form_tls_address);
292         }
293       } else {
294         DD->addArangeLabel(SymbolCU(this, Sym));
295         addOpAddress(*Loc, Sym);
296       }
297     }
298     // Global variables attached to symbols are memory locations.
299     // It would be better if this were unconditional, but malformed input that
300     // mixes non-fragments and fragments for the same variable is too expensive
301     // to detect in the verifier.
302     if (DwarfExpr->isUnknownLocation())
303       DwarfExpr->setMemoryLocationKind();
304     DwarfExpr->addExpression(Expr);
305   }
306   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
307     // According to
308     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
309     // cuda-gdb requires DW_AT_address_class for all variables to be able to
310     // correctly interpret address space of the variable address.
311     const unsigned NVPTX_ADDR_global_space = 5;
312     addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
313             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
314   }
315   if (Loc)
316     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
317 
318   if (DD->useAllLinkageNames())
319     addLinkageName(*VariableDIE, GV->getLinkageName());
320 
321   if (addToAccelTable) {
322     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
323 
324     // If the linkage name is different than the name, go ahead and output
325     // that as well into the name table.
326     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
327         DD->useAllLinkageNames())
328       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
329   }
330 }
331 
332 DIE *DwarfCompileUnit::getOrCreateCommonBlock(
333     const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
334   // Construct the context before querying for the existence of the DIE in case
335   // such construction creates the DIE.
336   DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
337 
338   if (DIE *NDie = getDIE(CB))
339     return NDie;
340   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
341   StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
342   addString(NDie, dwarf::DW_AT_name, Name);
343   addGlobalName(Name, NDie, CB->getScope());
344   if (CB->getFile())
345     addSourceLine(NDie, CB->getLineNo(), CB->getFile());
346   if (DIGlobalVariable *V = CB->getDecl())
347     getCU().addLocationAttribute(&NDie, V, GlobalExprs);
348   return &NDie;
349 }
350 
351 void DwarfCompileUnit::addRange(RangeSpan Range) {
352   DD->insertSectionLabel(Range.Begin);
353 
354   bool SameAsPrevCU = this == DD->getPrevCU();
355   DD->setPrevCU(this);
356   // If we have no current ranges just add the range and return, otherwise,
357   // check the current section and CU against the previous section and CU we
358   // emitted into and the subprogram was contained within. If these are the
359   // same then extend our current range, otherwise add this as a new range.
360   if (CURanges.empty() || !SameAsPrevCU ||
361       (&CURanges.back().End->getSection() !=
362        &Range.End->getSection())) {
363     CURanges.push_back(Range);
364     return;
365   }
366 
367   CURanges.back().End = Range.End;
368 }
369 
370 void DwarfCompileUnit::initStmtList() {
371   if (CUNode->isDebugDirectivesOnly())
372     return;
373 
374   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
375   if (DD->useSectionsAsReferences()) {
376     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
377   } else {
378     LineTableStartSym =
379         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
380   }
381 
382   // DW_AT_stmt_list is a offset of line number information for this
383   // compile unit in debug_line section. For split dwarf this is
384   // left in the skeleton CU and so not included.
385   // The line table entries are not always emitted in assembly, so it
386   // is not okay to use line_table_start here.
387       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
388                       TLOF.getDwarfLineSection()->getBeginSymbol());
389 }
390 
391 void DwarfCompileUnit::applyStmtList(DIE &D) {
392   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
393   addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
394                   TLOF.getDwarfLineSection()->getBeginSymbol());
395 }
396 
397 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
398                                        const MCSymbol *End) {
399   assert(Begin && "Begin label should not be null!");
400   assert(End && "End label should not be null!");
401   assert(Begin->isDefined() && "Invalid starting label");
402   assert(End->isDefined() && "Invalid end label");
403 
404   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
405   if (DD->getDwarfVersion() < 4)
406     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
407   else
408     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
409 }
410 
411 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
412 // and DW_AT_high_pc attributes. If there are global variables in this
413 // scope then create and insert DIEs for these variables.
414 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
415   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
416 
417   SmallVector<RangeSpan, 2> BB_List;
418   // If basic block sections are on, ranges for each basic block section has
419   // to be emitted separately.
420   for (const auto &R : Asm->MBBSectionRanges)
421     BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
422 
423   attachRangesOrLowHighPC(*SPDie, BB_List);
424 
425   if (DD->useAppleExtensionAttributes() &&
426       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
427           *DD->getCurrentFunction()))
428     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
429 
430   // Only include DW_AT_frame_base in full debug info
431   if (!includeMinimalInlineScopes()) {
432     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
433     TargetFrameLowering::DwarfFrameBase FrameBase =
434         TFI->getDwarfFrameBase(*Asm->MF);
435     switch (FrameBase.Kind) {
436     case TargetFrameLowering::DwarfFrameBase::Register: {
437       if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
438         MachineLocation Location(FrameBase.Location.Reg);
439         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
440       }
441       break;
442     }
443     case TargetFrameLowering::DwarfFrameBase::CFA: {
444       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
445       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
446       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
447       break;
448     }
449     case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
450       // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
451       // don't want to depend on target specific headers in this code?
452       const unsigned TI_GLOBAL_RELOC = 3;
453       if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
454         // These need to be relocatable.
455         assert(FrameBase.Location.WasmLoc.Index == 0);  // Only SP so far.
456         auto SPSym = cast<MCSymbolWasm>(
457           Asm->GetExternalSymbolSymbol("__stack_pointer"));
458         // FIXME: this repeats what WebAssemblyMCInstLower::
459         // GetExternalSymbolSymbol does, since if there's no code that
460         // refers to this symbol, we have to set it here.
461         SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
462         SPSym->setGlobalType(wasm::WasmGlobalType{
463             uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
464                             Triple::wasm64
465                         ? wasm::WASM_TYPE_I64
466                         : wasm::WASM_TYPE_I32),
467             true});
468         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
469         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
470         addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
471         if (!isDwoUnit()) {
472           addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
473           DD->addArangeLabel(SymbolCU(this, SPSym));
474         } else {
475           // FIXME: when writing dwo, we need to avoid relocations. Probably
476           // the "right" solution is to treat globals the way func and data
477           // symbols are (with entries in .debug_addr).
478           // For now, since we only ever use index 0, this should work as-is.
479           addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
480         }
481         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
482         addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
483       } else {
484         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
485         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
486         DIExpressionCursor Cursor({});
487         DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
488             FrameBase.Location.WasmLoc.Index);
489         DwarfExpr.addExpression(std::move(Cursor));
490         addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
491       }
492       break;
493     }
494     }
495   }
496 
497   // Add name to the name table, we do this here because we're guaranteed
498   // to have concrete versions of our DW_TAG_subprogram nodes.
499   DD->addSubprogramNames(*CUNode, SP, *SPDie);
500 
501   return *SPDie;
502 }
503 
504 // Construct a DIE for this scope.
505 void DwarfCompileUnit::constructScopeDIE(
506     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
507   if (!Scope || !Scope->getScopeNode())
508     return;
509 
510   auto *DS = Scope->getScopeNode();
511 
512   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
513          "Only handle inlined subprograms here, use "
514          "constructSubprogramScopeDIE for non-inlined "
515          "subprograms");
516 
517   SmallVector<DIE *, 8> Children;
518 
519   // We try to create the scope DIE first, then the children DIEs. This will
520   // avoid creating un-used children then removing them later when we find out
521   // the scope DIE is null.
522   DIE *ScopeDIE;
523   if (Scope->getParent() && isa<DISubprogram>(DS)) {
524     ScopeDIE = constructInlinedScopeDIE(Scope);
525     if (!ScopeDIE)
526       return;
527     // We create children when the scope DIE is not null.
528     createScopeChildrenDIE(Scope, Children);
529   } else {
530     // Early exit when we know the scope DIE is going to be null.
531     if (DD->isLexicalScopeDIENull(Scope))
532       return;
533 
534     bool HasNonScopeChildren = false;
535 
536     // We create children here when we know the scope DIE is not going to be
537     // null and the children will be added to the scope DIE.
538     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
539 
540     // If there are only other scopes as children, put them directly in the
541     // parent instead, as this scope would serve no purpose.
542     if (!HasNonScopeChildren) {
543       FinalChildren.insert(FinalChildren.end(),
544                            std::make_move_iterator(Children.begin()),
545                            std::make_move_iterator(Children.end()));
546       return;
547     }
548     ScopeDIE = constructLexicalScopeDIE(Scope);
549     assert(ScopeDIE && "Scope DIE should not be null.");
550   }
551 
552   // Add children
553   for (auto &I : Children)
554     ScopeDIE->addChild(std::move(I));
555 
556   FinalChildren.push_back(std::move(ScopeDIE));
557 }
558 
559 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
560                                          SmallVector<RangeSpan, 2> Range) {
561 
562   HasRangeLists = true;
563 
564   // Add the range list to the set of ranges to be emitted.
565   auto IndexAndList =
566       (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
567           ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
568 
569   uint32_t Index = IndexAndList.first;
570   auto &List = *IndexAndList.second;
571 
572   // Under fission, ranges are specified by constant offsets relative to the
573   // CU's DW_AT_GNU_ranges_base.
574   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
575   // fission until we support the forms using the .debug_addr section
576   // (DW_RLE_startx_endx etc.).
577   if (DD->getDwarfVersion() >= 5)
578     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
579   else {
580     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
581     const MCSymbol *RangeSectionSym =
582         TLOF.getDwarfRangesSection()->getBeginSymbol();
583     if (isDwoUnit())
584       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
585                       RangeSectionSym);
586     else
587       addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
588                       RangeSectionSym);
589   }
590 }
591 
592 void DwarfCompileUnit::attachRangesOrLowHighPC(
593     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
594   assert(!Ranges.empty());
595   if (!DD->useRangesSection() ||
596       (Ranges.size() == 1 &&
597        (!DD->alwaysUseRanges() ||
598         DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
599             Ranges.front().Begin))) {
600     const RangeSpan &Front = Ranges.front();
601     const RangeSpan &Back = Ranges.back();
602     attachLowHighPC(Die, Front.Begin, Back.End);
603   } else
604     addScopeRangeList(Die, std::move(Ranges));
605 }
606 
607 void DwarfCompileUnit::attachRangesOrLowHighPC(
608     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
609   SmallVector<RangeSpan, 2> List;
610   List.reserve(Ranges.size());
611   for (const InsnRange &R : Ranges) {
612     auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
613     auto *EndLabel = DD->getLabelAfterInsn(R.second);
614 
615     const auto *BeginMBB = R.first->getParent();
616     const auto *EndMBB = R.second->getParent();
617 
618     const auto *MBB = BeginMBB;
619     // Basic block sections allows basic block subsets to be placed in unique
620     // sections. For each section, the begin and end label must be added to the
621     // list. If there is more than one range, debug ranges must be used.
622     // Otherwise, low/high PC can be used.
623     // FIXME: Debug Info Emission depends on block order and this assumes that
624     // the order of blocks will be frozen beyond this point.
625     do {
626       if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
627         auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
628         List.push_back(
629             {MBB->sameSection(BeginMBB) ? BeginLabel
630                                         : MBBSectionRange.BeginLabel,
631              MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
632       }
633       if (MBB->sameSection(EndMBB))
634         break;
635       MBB = MBB->getNextNode();
636     } while (true);
637   }
638   attachRangesOrLowHighPC(Die, std::move(List));
639 }
640 
641 // This scope represents inlined body of a function. Construct DIE to
642 // represent this concrete inlined copy of the function.
643 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
644   assert(Scope->getScopeNode());
645   auto *DS = Scope->getScopeNode();
646   auto *InlinedSP = getDISubprogram(DS);
647   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
648   // was inlined from another compile unit.
649   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
650   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
651 
652   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
653   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
654 
655   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
656 
657   // Add the call site information to the DIE.
658   const DILocation *IA = Scope->getInlinedAt();
659   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
660           getOrCreateSourceID(IA->getFile()));
661   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
662   if (IA->getColumn())
663     addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
664   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
665     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
666             IA->getDiscriminator());
667 
668   // Add name to the name table, we do this here because we're guaranteed
669   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
670   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
671 
672   return ScopeDIE;
673 }
674 
675 // Construct new DW_TAG_lexical_block for this scope and attach
676 // DW_AT_low_pc/DW_AT_high_pc labels.
677 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
678   if (DD->isLexicalScopeDIENull(Scope))
679     return nullptr;
680 
681   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
682   if (Scope->isAbstractScope())
683     return ScopeDIE;
684 
685   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
686 
687   return ScopeDIE;
688 }
689 
690 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
691 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
692   auto D = constructVariableDIEImpl(DV, Abstract);
693   DV.setDIE(*D);
694   return D;
695 }
696 
697 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
698                                          const LexicalScope &Scope) {
699   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
700   insertDIE(DL.getLabel(), LabelDie);
701   DL.setDIE(*LabelDie);
702 
703   if (Scope.isAbstractScope())
704     applyLabelAttributes(DL, *LabelDie);
705 
706   return LabelDie;
707 }
708 
709 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
710                                                 bool Abstract) {
711   // Define variable debug information entry.
712   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
713   insertDIE(DV.getVariable(), VariableDie);
714 
715   if (Abstract) {
716     applyVariableAttributes(DV, *VariableDie);
717     return VariableDie;
718   }
719 
720   // Add variable address.
721 
722   unsigned Index = DV.getDebugLocListIndex();
723   if (Index != ~0U) {
724     addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
725     auto TagOffset = DV.getDebugLocListTagOffset();
726     if (TagOffset)
727       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
728               *TagOffset);
729     return VariableDie;
730   }
731 
732   // Check if variable has a single location description.
733   if (auto *DVal = DV.getValueLoc()) {
734     if (!DVal->isVariadic()) {
735       const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
736       if (Entry->isLocation()) {
737         addVariableAddress(DV, *VariableDie, Entry->getLoc());
738       } else if (Entry->isInt()) {
739         auto *Expr = DV.getSingleExpression();
740         if (Expr && Expr->getNumElements()) {
741           DIELoc *Loc = new (DIEValueAllocator) DIELoc;
742           DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
743           // If there is an expression, emit raw unsigned bytes.
744           DwarfExpr.addFragmentOffset(Expr);
745           DwarfExpr.addUnsignedConstant(Entry->getInt());
746           DwarfExpr.addExpression(Expr);
747           addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
748           if (DwarfExpr.TagOffset)
749             addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
750                     dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
751         } else
752           addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
753       } else if (Entry->isConstantFP()) {
754         addConstantFPValue(*VariableDie, Entry->getConstantFP());
755       } else if (Entry->isConstantInt()) {
756         addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
757       } else if (Entry->isTargetIndexLocation()) {
758         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
759         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
760         const DIBasicType *BT = dyn_cast<DIBasicType>(
761             static_cast<const Metadata *>(DV.getVariable()->getType()));
762         DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
763         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
764       }
765       return VariableDie;
766     }
767     // If any of the location entries are registers with the value 0, then the
768     // location is undefined.
769     if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
770           return Entry.isLocation() && !Entry.getLoc().getReg();
771         }))
772       return VariableDie;
773     const DIExpression *Expr = DV.getSingleExpression();
774     assert(Expr && "Variadic Debug Value must have an Expression.");
775     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
776     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
777     DwarfExpr.addFragmentOffset(Expr);
778     DIExpressionCursor Cursor(Expr);
779     const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
780 
781     auto AddEntry = [&](const DbgValueLocEntry &Entry,
782                         DIExpressionCursor &Cursor) {
783       if (Entry.isLocation()) {
784         if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
785                                                Entry.getLoc().getReg()))
786           return false;
787       } else if (Entry.isInt()) {
788         // If there is an expression, emit raw unsigned bytes.
789         DwarfExpr.addUnsignedConstant(Entry.getInt());
790       } else if (Entry.isConstantFP()) {
791         // DwarfExpression does not support arguments wider than 64 bits
792         // (see PR52584).
793         // TODO: Consider chunking expressions containing overly wide
794         // arguments into separate pointer-sized fragment expressions.
795         APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
796         if (RawBytes.getBitWidth() > 64)
797           return false;
798         DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
799       } else if (Entry.isConstantInt()) {
800         APInt RawBytes = Entry.getConstantInt()->getValue();
801         if (RawBytes.getBitWidth() > 64)
802           return false;
803         DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
804       } else if (Entry.isTargetIndexLocation()) {
805         TargetIndexLocation Loc = Entry.getTargetIndexLocation();
806         // TODO TargetIndexLocation is a target-independent. Currently only the
807         // WebAssembly-specific encoding is supported.
808         assert(Asm->TM.getTargetTriple().isWasm());
809         DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
810       } else {
811         llvm_unreachable("Unsupported Entry type.");
812       }
813       return true;
814     };
815 
816     if (!DwarfExpr.addExpression(
817             std::move(Cursor),
818             [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
819               return AddEntry(DVal->getLocEntries()[Idx], Cursor);
820             }))
821       return VariableDie;
822 
823     // Now attach the location information to the DIE.
824     addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
825     if (DwarfExpr.TagOffset)
826       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
827               *DwarfExpr.TagOffset);
828 
829     return VariableDie;
830   }
831 
832   // .. else use frame index.
833   if (!DV.hasFrameIndexExprs())
834     return VariableDie;
835 
836   Optional<unsigned> NVPTXAddressSpace;
837   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
838   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
839   for (auto &Fragment : DV.getFrameIndexExprs()) {
840     Register FrameReg;
841     const DIExpression *Expr = Fragment.Expr;
842     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
843     StackOffset Offset =
844         TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
845     DwarfExpr.addFragmentOffset(Expr);
846 
847     auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
848     SmallVector<uint64_t, 8> Ops;
849     TRI->getOffsetOpcodes(Offset, Ops);
850 
851     // According to
852     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
853     // cuda-gdb requires DW_AT_address_class for all variables to be able to
854     // correctly interpret address space of the variable address.
855     // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
856     // sequence for the NVPTX + gdb target.
857     unsigned LocalNVPTXAddressSpace;
858     if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
859       const DIExpression *NewExpr =
860           DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
861       if (NewExpr != Expr) {
862         Expr = NewExpr;
863         NVPTXAddressSpace = LocalNVPTXAddressSpace;
864       }
865     }
866     if (Expr)
867       Ops.append(Expr->elements_begin(), Expr->elements_end());
868     DIExpressionCursor Cursor(Ops);
869     DwarfExpr.setMemoryLocationKind();
870     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
871       addOpAddress(*Loc, FrameSymbol);
872     else
873       DwarfExpr.addMachineRegExpression(
874           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
875     DwarfExpr.addExpression(std::move(Cursor));
876   }
877   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
878     // According to
879     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
880     // cuda-gdb requires DW_AT_address_class for all variables to be able to
881     // correctly interpret address space of the variable address.
882     const unsigned NVPTX_ADDR_local_space = 6;
883     addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
884             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
885   }
886   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
887   if (DwarfExpr.TagOffset)
888     addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
889             *DwarfExpr.TagOffset);
890 
891   return VariableDie;
892 }
893 
894 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
895                                             const LexicalScope &Scope,
896                                             DIE *&ObjectPointer) {
897   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
898   if (DV.isObjectPointer())
899     ObjectPointer = Var;
900   return Var;
901 }
902 
903 /// Return all DIVariables that appear in count: expressions.
904 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
905   SmallVector<const DIVariable *, 2> Result;
906   auto *Array = dyn_cast<DICompositeType>(Var->getType());
907   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
908     return Result;
909   if (auto *DLVar = Array->getDataLocation())
910     Result.push_back(DLVar);
911   if (auto *AsVar = Array->getAssociated())
912     Result.push_back(AsVar);
913   if (auto *AlVar = Array->getAllocated())
914     Result.push_back(AlVar);
915   for (auto *El : Array->getElements()) {
916     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
917       if (auto Count = Subrange->getCount())
918         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
919           Result.push_back(Dependency);
920       if (auto LB = Subrange->getLowerBound())
921         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
922           Result.push_back(Dependency);
923       if (auto UB = Subrange->getUpperBound())
924         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
925           Result.push_back(Dependency);
926       if (auto ST = Subrange->getStride())
927         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
928           Result.push_back(Dependency);
929     } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
930       if (auto Count = GenericSubrange->getCount())
931         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
932           Result.push_back(Dependency);
933       if (auto LB = GenericSubrange->getLowerBound())
934         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
935           Result.push_back(Dependency);
936       if (auto UB = GenericSubrange->getUpperBound())
937         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
938           Result.push_back(Dependency);
939       if (auto ST = GenericSubrange->getStride())
940         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
941           Result.push_back(Dependency);
942     }
943   }
944   return Result;
945 }
946 
947 /// Sort local variables so that variables appearing inside of helper
948 /// expressions come first.
949 static SmallVector<DbgVariable *, 8>
950 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
951   SmallVector<DbgVariable *, 8> Result;
952   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
953   // Map back from a DIVariable to its containing DbgVariable.
954   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
955   // Set of DbgVariables in Result.
956   SmallDenseSet<DbgVariable *, 8> Visited;
957   // For cycle detection.
958   SmallDenseSet<DbgVariable *, 8> Visiting;
959 
960   // Initialize the worklist and the DIVariable lookup table.
961   for (auto Var : reverse(Input)) {
962     DbgVar.insert({Var->getVariable(), Var});
963     WorkList.push_back({Var, 0});
964   }
965 
966   // Perform a stable topological sort by doing a DFS.
967   while (!WorkList.empty()) {
968     auto Item = WorkList.back();
969     DbgVariable *Var = Item.getPointer();
970     bool visitedAllDependencies = Item.getInt();
971     WorkList.pop_back();
972 
973     // Dependency is in a different lexical scope or a global.
974     if (!Var)
975       continue;
976 
977     // Already handled.
978     if (Visited.count(Var))
979       continue;
980 
981     // Add to Result if all dependencies are visited.
982     if (visitedAllDependencies) {
983       Visited.insert(Var);
984       Result.push_back(Var);
985       continue;
986     }
987 
988     // Detect cycles.
989     auto Res = Visiting.insert(Var);
990     if (!Res.second) {
991       assert(false && "dependency cycle in local variables");
992       return Result;
993     }
994 
995     // Push dependencies and this node onto the worklist, so that this node is
996     // visited again after all of its dependencies are handled.
997     WorkList.push_back({Var, 1});
998     for (auto *Dependency : dependencies(Var)) {
999       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
1000       WorkList.push_back({DbgVar[Dep], 0});
1001     }
1002   }
1003   return Result;
1004 }
1005 
1006 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
1007                                               SmallVectorImpl<DIE *> &Children,
1008                                               bool *HasNonScopeChildren) {
1009   assert(Children.empty());
1010   DIE *ObjectPointer = nullptr;
1011 
1012   // Emit function arguments (order is significant).
1013   auto Vars = DU->getScopeVariables().lookup(Scope);
1014   for (auto &DV : Vars.Args)
1015     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
1016 
1017   // Emit local variables.
1018   auto Locals = sortLocalVars(Vars.Locals);
1019   for (DbgVariable *DV : Locals)
1020     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
1021 
1022   // Skip imported directives in gmlt-like data.
1023   if (!includeMinimalInlineScopes()) {
1024     // There is no need to emit empty lexical block DIE.
1025     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
1026       Children.push_back(
1027           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
1028   }
1029 
1030   if (HasNonScopeChildren)
1031     *HasNonScopeChildren = !Children.empty();
1032 
1033   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
1034     Children.push_back(constructLabelDIE(*DL, *Scope));
1035 
1036   for (LexicalScope *LS : Scope->getChildren())
1037     constructScopeDIE(LS, Children);
1038 
1039   return ObjectPointer;
1040 }
1041 
1042 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
1043                                                    LexicalScope *Scope) {
1044   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
1045 
1046   if (Scope) {
1047     assert(!Scope->getInlinedAt());
1048     assert(!Scope->isAbstractScope());
1049     // Collect lexical scope children first.
1050     // ObjectPointer might be a local (non-argument) local variable if it's a
1051     // block's synthetic this pointer.
1052     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1053       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
1054   }
1055 
1056   // If this is a variadic function, add an unspecified parameter.
1057   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
1058 
1059   // If we have a single element of null, it is a function that returns void.
1060   // If we have more than one elements and the last one is null, it is a
1061   // variadic function.
1062   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1063       !includeMinimalInlineScopes())
1064     ScopeDIE.addChild(
1065         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
1066 
1067   return ScopeDIE;
1068 }
1069 
1070 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
1071                                                  DIE &ScopeDIE) {
1072   // We create children when the scope DIE is not null.
1073   SmallVector<DIE *, 8> Children;
1074   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
1075 
1076   // Add children
1077   for (auto &I : Children)
1078     ScopeDIE.addChild(std::move(I));
1079 
1080   return ObjectPointer;
1081 }
1082 
1083 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
1084     LexicalScope *Scope) {
1085   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
1086   if (AbsDef)
1087     return;
1088 
1089   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
1090 
1091   DIE *ContextDIE;
1092   DwarfCompileUnit *ContextCU = this;
1093 
1094   if (includeMinimalInlineScopes())
1095     ContextDIE = &getUnitDie();
1096   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
1097   // the important distinction that the debug node is not associated with the
1098   // DIE (since the debug node will be associated with the concrete DIE, if
1099   // any). It could be refactored to some common utility function.
1100   else if (auto *SPDecl = SP->getDeclaration()) {
1101     ContextDIE = &getUnitDie();
1102     getOrCreateSubprogramDIE(SPDecl);
1103   } else {
1104     ContextDIE = getOrCreateContextDIE(SP->getScope());
1105     // The scope may be shared with a subprogram that has already been
1106     // constructed in another CU, in which case we need to construct this
1107     // subprogram in the same CU.
1108     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
1109   }
1110 
1111   // Passing null as the associated node because the abstract definition
1112   // shouldn't be found by lookup.
1113   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
1114   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
1115 
1116   if (!ContextCU->includeMinimalInlineScopes())
1117     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
1118   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
1119     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
1120 }
1121 
1122 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
1123   return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
1124 }
1125 
1126 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1127   if (!useGNUAnalogForDwarf5Feature())
1128     return Tag;
1129   switch (Tag) {
1130   case dwarf::DW_TAG_call_site:
1131     return dwarf::DW_TAG_GNU_call_site;
1132   case dwarf::DW_TAG_call_site_parameter:
1133     return dwarf::DW_TAG_GNU_call_site_parameter;
1134   default:
1135     llvm_unreachable("DWARF5 tag with no GNU analog");
1136   }
1137 }
1138 
1139 dwarf::Attribute
1140 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1141   if (!useGNUAnalogForDwarf5Feature())
1142     return Attr;
1143   switch (Attr) {
1144   case dwarf::DW_AT_call_all_calls:
1145     return dwarf::DW_AT_GNU_all_call_sites;
1146   case dwarf::DW_AT_call_target:
1147     return dwarf::DW_AT_GNU_call_site_target;
1148   case dwarf::DW_AT_call_origin:
1149     return dwarf::DW_AT_abstract_origin;
1150   case dwarf::DW_AT_call_return_pc:
1151     return dwarf::DW_AT_low_pc;
1152   case dwarf::DW_AT_call_value:
1153     return dwarf::DW_AT_GNU_call_site_value;
1154   case dwarf::DW_AT_call_tail_call:
1155     return dwarf::DW_AT_GNU_tail_call;
1156   default:
1157     llvm_unreachable("DWARF5 attribute with no GNU analog");
1158   }
1159 }
1160 
1161 dwarf::LocationAtom
1162 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1163   if (!useGNUAnalogForDwarf5Feature())
1164     return Loc;
1165   switch (Loc) {
1166   case dwarf::DW_OP_entry_value:
1167     return dwarf::DW_OP_GNU_entry_value;
1168   default:
1169     llvm_unreachable("DWARF5 location atom with no GNU analog");
1170   }
1171 }
1172 
1173 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
1174                                                  const DISubprogram *CalleeSP,
1175                                                  bool IsTail,
1176                                                  const MCSymbol *PCAddr,
1177                                                  const MCSymbol *CallAddr,
1178                                                  unsigned CallReg) {
1179   // Insert a call site entry DIE within ScopeDIE.
1180   DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
1181                                      ScopeDIE, nullptr);
1182 
1183   if (CallReg) {
1184     // Indirect call.
1185     addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
1186                MachineLocation(CallReg));
1187   } else {
1188     DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
1189     assert(CalleeDIE && "Could not create DIE for call site entry origin");
1190     addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
1191                 *CalleeDIE);
1192   }
1193 
1194   if (IsTail) {
1195     // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1196     addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
1197 
1198     // Attach the address of the branch instruction to allow the debugger to
1199     // show where the tail call occurred. This attribute has no GNU analog.
1200     //
1201     // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1202     // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1203     // site entries to figure out the PC of tail-calling branch instructions.
1204     // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1205     // don't emit it here.
1206     //
1207     // There's no need to tie non-GDB debuggers to this non-standardness, as it
1208     // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1209     // the standard DW_AT_call_pc info.
1210     if (!useGNUAnalogForDwarf5Feature())
1211       addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
1212   }
1213 
1214   // Attach the return PC to allow the debugger to disambiguate call paths
1215   // from one function to another.
1216   //
1217   // The return PC is only really needed when the call /isn't/ a tail call, but
1218   // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1219   // the DW_AT_call_pc emission logic for an explanation).
1220   if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1221     assert(PCAddr && "Missing return PC information for a call");
1222     addLabelAddress(CallSiteDIE,
1223                     getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
1224   }
1225 
1226   return CallSiteDIE;
1227 }
1228 
1229 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
1230     DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1231   for (const auto &Param : Params) {
1232     unsigned Register = Param.getRegister();
1233     auto CallSiteDieParam =
1234         DIE::get(DIEValueAllocator,
1235                  getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
1236     insertDIE(CallSiteDieParam);
1237     addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
1238                MachineLocation(Register));
1239 
1240     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1241     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1242     DwarfExpr.setCallSiteParamValueFlag();
1243 
1244     DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
1245 
1246     addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1247              DwarfExpr.finalize());
1248 
1249     CallSiteDIE.addChild(CallSiteDieParam);
1250   }
1251 }
1252 
1253 DIE *DwarfCompileUnit::constructImportedEntityDIE(
1254     const DIImportedEntity *Module) {
1255   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
1256   insertDIE(Module, IMDie);
1257   DIE *EntityDie;
1258   auto *Entity = Module->getEntity();
1259   if (auto *NS = dyn_cast<DINamespace>(Entity))
1260     EntityDie = getOrCreateNameSpace(NS);
1261   else if (auto *M = dyn_cast<DIModule>(Entity))
1262     EntityDie = getOrCreateModule(M);
1263   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1264     EntityDie = getOrCreateSubprogramDIE(SP);
1265   else if (auto *T = dyn_cast<DIType>(Entity))
1266     EntityDie = getOrCreateTypeDIE(T);
1267   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1268     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1269   else
1270     EntityDie = getDIE(Entity);
1271   assert(EntityDie);
1272   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1273   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1274   StringRef Name = Module->getName();
1275   if (!Name.empty())
1276     addString(*IMDie, dwarf::DW_AT_name, Name);
1277 
1278   return IMDie;
1279 }
1280 
1281 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1282   DIE *D = getDIE(SP);
1283   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1284     if (D)
1285       // If this subprogram has an abstract definition, reference that
1286       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1287   } else {
1288     assert(D || includeMinimalInlineScopes());
1289     if (D)
1290       // And attach the attributes
1291       applySubprogramAttributesToDefinition(SP, *D);
1292   }
1293 }
1294 
1295 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1296   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1297 
1298   auto *Die = Entity->getDIE();
1299   /// Label may be used to generate DW_AT_low_pc, so put it outside
1300   /// if/else block.
1301   const DbgLabel *Label = nullptr;
1302   if (AbsEntity && AbsEntity->getDIE()) {
1303     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1304     Label = dyn_cast<const DbgLabel>(Entity);
1305   } else {
1306     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1307       applyVariableAttributes(*Var, *Die);
1308     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1309       applyLabelAttributes(*Label, *Die);
1310     else
1311       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1312   }
1313 
1314   if (Label)
1315     if (const auto *Sym = Label->getSymbol())
1316       addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1317 }
1318 
1319 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1320   auto &AbstractEntities = getAbstractEntities();
1321   auto I = AbstractEntities.find(Node);
1322   if (I != AbstractEntities.end())
1323     return I->second.get();
1324   return nullptr;
1325 }
1326 
1327 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1328                                             LexicalScope *Scope) {
1329   assert(Scope && Scope->isAbstractScope());
1330   auto &Entity = getAbstractEntities()[Node];
1331   if (isa<const DILocalVariable>(Node)) {
1332     Entity = std::make_unique<DbgVariable>(
1333                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
1334     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1335   } else if (isa<const DILabel>(Node)) {
1336     Entity = std::make_unique<DbgLabel>(
1337                         cast<const DILabel>(Node), nullptr /* IA */);
1338     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1339   }
1340 }
1341 
1342 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1343   // Don't bother labeling the .dwo unit, as its offset isn't used.
1344   if (!Skeleton && !DD->useSectionsAsReferences()) {
1345     LabelBegin = Asm->createTempSymbol("cu_begin");
1346     Asm->OutStreamer->emitLabel(LabelBegin);
1347   }
1348 
1349   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1350                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1351                                                       : dwarf::DW_UT_compile;
1352   DwarfUnit::emitCommonHeader(UseOffsets, UT);
1353   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1354     Asm->emitInt64(getDWOId());
1355 }
1356 
1357 bool DwarfCompileUnit::hasDwarfPubSections() const {
1358   switch (CUNode->getNameTableKind()) {
1359   case DICompileUnit::DebugNameTableKind::None:
1360     return false;
1361     // Opting in to GNU Pubnames/types overrides the default to ensure these are
1362     // generated for things like Gold's gdb_index generation.
1363   case DICompileUnit::DebugNameTableKind::GNU:
1364     return true;
1365   case DICompileUnit::DebugNameTableKind::Default:
1366     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1367            !CUNode->isDebugDirectivesOnly() &&
1368            DD->getAccelTableKind() != AccelTableKind::Apple &&
1369            DD->getDwarfVersion() < 5;
1370   }
1371   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1372 }
1373 
1374 /// addGlobalName - Add a new global name to the compile unit.
1375 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1376                                      const DIScope *Context) {
1377   if (!hasDwarfPubSections())
1378     return;
1379   std::string FullName = getParentContextString(Context) + Name.str();
1380   GlobalNames[FullName] = &Die;
1381 }
1382 
1383 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1384                                                 const DIScope *Context) {
1385   if (!hasDwarfPubSections())
1386     return;
1387   std::string FullName = getParentContextString(Context) + Name.str();
1388   // Insert, allowing the entry to remain as-is if it's already present
1389   // This way the CU-level type DIE is preferred over the "can't describe this
1390   // type as a unit offset because it's not really in the CU at all, it's only
1391   // in a type unit"
1392   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1393 }
1394 
1395 /// Add a new global type to the unit.
1396 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1397                                      const DIScope *Context) {
1398   if (!hasDwarfPubSections())
1399     return;
1400   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1401   GlobalTypes[FullName] = &Die;
1402 }
1403 
1404 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1405                                              const DIScope *Context) {
1406   if (!hasDwarfPubSections())
1407     return;
1408   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1409   // Insert, allowing the entry to remain as-is if it's already present
1410   // This way the CU-level type DIE is preferred over the "can't describe this
1411   // type as a unit offset because it's not really in the CU at all, it's only
1412   // in a type unit"
1413   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1414 }
1415 
1416 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1417                                           MachineLocation Location) {
1418   if (DV.hasComplexAddress())
1419     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1420   else
1421     addAddress(Die, dwarf::DW_AT_location, Location);
1422 }
1423 
1424 /// Add an address attribute to a die based on the location provided.
1425 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1426                                   const MachineLocation &Location) {
1427   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1428   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1429   if (Location.isIndirect())
1430     DwarfExpr.setMemoryLocationKind();
1431 
1432   DIExpressionCursor Cursor({});
1433   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1434   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1435     return;
1436   DwarfExpr.addExpression(std::move(Cursor));
1437 
1438   // Now attach the location information to the DIE.
1439   addBlock(Die, Attribute, DwarfExpr.finalize());
1440 
1441   if (DwarfExpr.TagOffset)
1442     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1443             *DwarfExpr.TagOffset);
1444 }
1445 
1446 /// Start with the address based on the location provided, and generate the
1447 /// DWARF information necessary to find the actual variable given the extra
1448 /// address information encoded in the DbgVariable, starting from the starting
1449 /// location.  Add the DWARF information to the die.
1450 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1451                                          dwarf::Attribute Attribute,
1452                                          const MachineLocation &Location) {
1453   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1454   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1455   const DIExpression *DIExpr = DV.getSingleExpression();
1456   DwarfExpr.addFragmentOffset(DIExpr);
1457   DwarfExpr.setLocation(Location, DIExpr);
1458 
1459   DIExpressionCursor Cursor(DIExpr);
1460 
1461   if (DIExpr->isEntryValue())
1462     DwarfExpr.beginEntryValueExpression(Cursor);
1463 
1464   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1465   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1466     return;
1467   DwarfExpr.addExpression(std::move(Cursor));
1468 
1469   // Now attach the location information to the DIE.
1470   addBlock(Die, Attribute, DwarfExpr.finalize());
1471 
1472   if (DwarfExpr.TagOffset)
1473     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1474             *DwarfExpr.TagOffset);
1475 }
1476 
1477 /// Add a Dwarf loclistptr attribute data and value.
1478 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1479                                        unsigned Index) {
1480   dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1481                          ? dwarf::DW_FORM_loclistx
1482                          : DD->getDwarfSectionOffsetForm();
1483   addAttribute(Die, Attribute, Form, DIELocList(Index));
1484 }
1485 
1486 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1487                                                DIE &VariableDie) {
1488   StringRef Name = Var.getName();
1489   if (!Name.empty())
1490     addString(VariableDie, dwarf::DW_AT_name, Name);
1491   const auto *DIVar = Var.getVariable();
1492   if (DIVar)
1493     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1494       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1495               AlignInBytes);
1496 
1497   addSourceLine(VariableDie, DIVar);
1498   addType(VariableDie, Var.getType());
1499   if (Var.isArtificial())
1500     addFlag(VariableDie, dwarf::DW_AT_artificial);
1501 }
1502 
1503 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1504                                             DIE &LabelDie) {
1505   StringRef Name = Label.getName();
1506   if (!Name.empty())
1507     addString(LabelDie, dwarf::DW_AT_name, Name);
1508   const auto *DILabel = Label.getLabel();
1509   addSourceLine(LabelDie, DILabel);
1510 }
1511 
1512 /// Add a Dwarf expression attribute data and value.
1513 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1514                                const MCExpr *Expr) {
1515   addAttribute(Die, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1516 }
1517 
1518 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1519     const DISubprogram *SP, DIE &SPDie) {
1520   auto *SPDecl = SP->getDeclaration();
1521   auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1522   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1523   addGlobalName(SP->getName(), SPDie, Context);
1524 }
1525 
1526 bool DwarfCompileUnit::isDwoUnit() const {
1527   return DD->useSplitDwarf() && Skeleton;
1528 }
1529 
1530 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1531   constructTypeDIE(D, CTy);
1532 }
1533 
1534 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1535   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1536          (DD->useSplitDwarf() && !Skeleton);
1537 }
1538 
1539 void DwarfCompileUnit::addAddrTableBase() {
1540   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1541   MCSymbol *Label = DD->getAddressPool().getLabel();
1542   addSectionLabel(getUnitDie(),
1543                   DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1544                                              : dwarf::DW_AT_GNU_addr_base,
1545                   Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1546 }
1547 
1548 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1549   addAttribute(Die, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1550                new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1551 }
1552 
1553 void DwarfCompileUnit::createBaseTypeDIEs() {
1554   // Insert the base_type DIEs directly after the CU so that their offsets will
1555   // fit in the fixed size ULEB128 used inside the location expressions.
1556   // Maintain order by iterating backwards and inserting to the front of CU
1557   // child list.
1558   for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1559     DIE &Die = getUnitDie().addChildFront(
1560       DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1561     SmallString<32> Str;
1562     addString(Die, dwarf::DW_AT_name,
1563               Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1564                     "_" + Twine(Btr.BitSize)).toStringRef(Str));
1565     addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1566     addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
1567 
1568     Btr.Die = &Die;
1569   }
1570 }
1571