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