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