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