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