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