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       // FIXME: when writing dwo, we need to avoid relocations. Probably
426       // the "right" solution is to treat globals the way func and data symbols
427       // are (with entries in .debug_addr).
428       if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC && !isDwoUnit()) {
429         // These need to be relocatable.
430         assert(FrameBase.Location.WasmLoc.Index == 0);  // Only SP so far.
431         auto SPSym = cast<MCSymbolWasm>(
432           Asm->GetExternalSymbolSymbol("__stack_pointer"));
433         // FIXME: this repeats what WebAssemblyMCInstLower::
434         // GetExternalSymbolSymbol does, since if there's no code that
435         // refers to this symbol, we have to set it here.
436         SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
437         SPSym->setGlobalType(wasm::WasmGlobalType{
438             uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
439                             Triple::wasm64
440                         ? wasm::WASM_TYPE_I64
441                         : wasm::WASM_TYPE_I32),
442             true});
443         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
444         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
445         addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
446         addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
447         DD->addArangeLabel(SymbolCU(this, SPSym));
448         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
449         addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
450       } else {
451         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
452         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
453         DIExpressionCursor Cursor({});
454         DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
455             FrameBase.Location.WasmLoc.Index);
456         DwarfExpr.addExpression(std::move(Cursor));
457         addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
458       }
459       break;
460     }
461     }
462   }
463 
464   // Add name to the name table, we do this here because we're guaranteed
465   // to have concrete versions of our DW_TAG_subprogram nodes.
466   DD->addSubprogramNames(*CUNode, SP, *SPDie);
467 
468   return *SPDie;
469 }
470 
471 // Construct a DIE for this scope.
472 void DwarfCompileUnit::constructScopeDIE(
473     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
474   if (!Scope || !Scope->getScopeNode())
475     return;
476 
477   auto *DS = Scope->getScopeNode();
478 
479   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
480          "Only handle inlined subprograms here, use "
481          "constructSubprogramScopeDIE for non-inlined "
482          "subprograms");
483 
484   SmallVector<DIE *, 8> Children;
485 
486   // We try to create the scope DIE first, then the children DIEs. This will
487   // avoid creating un-used children then removing them later when we find out
488   // the scope DIE is null.
489   DIE *ScopeDIE;
490   if (Scope->getParent() && isa<DISubprogram>(DS)) {
491     ScopeDIE = constructInlinedScopeDIE(Scope);
492     if (!ScopeDIE)
493       return;
494     // We create children when the scope DIE is not null.
495     createScopeChildrenDIE(Scope, Children);
496   } else {
497     // Early exit when we know the scope DIE is going to be null.
498     if (DD->isLexicalScopeDIENull(Scope))
499       return;
500 
501     bool HasNonScopeChildren = false;
502 
503     // We create children here when we know the scope DIE is not going to be
504     // null and the children will be added to the scope DIE.
505     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
506 
507     // If there are only other scopes as children, put them directly in the
508     // parent instead, as this scope would serve no purpose.
509     if (!HasNonScopeChildren) {
510       FinalChildren.insert(FinalChildren.end(),
511                            std::make_move_iterator(Children.begin()),
512                            std::make_move_iterator(Children.end()));
513       return;
514     }
515     ScopeDIE = constructLexicalScopeDIE(Scope);
516     assert(ScopeDIE && "Scope DIE should not be null.");
517   }
518 
519   // Add children
520   for (auto &I : Children)
521     ScopeDIE->addChild(std::move(I));
522 
523   FinalChildren.push_back(std::move(ScopeDIE));
524 }
525 
526 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
527                                          SmallVector<RangeSpan, 2> Range) {
528 
529   HasRangeLists = true;
530 
531   // Add the range list to the set of ranges to be emitted.
532   auto IndexAndList =
533       (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
534           ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
535 
536   uint32_t Index = IndexAndList.first;
537   auto &List = *IndexAndList.second;
538 
539   // Under fission, ranges are specified by constant offsets relative to the
540   // CU's DW_AT_GNU_ranges_base.
541   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
542   // fission until we support the forms using the .debug_addr section
543   // (DW_RLE_startx_endx etc.).
544   if (DD->getDwarfVersion() >= 5)
545     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
546   else {
547     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
548     const MCSymbol *RangeSectionSym =
549         TLOF.getDwarfRangesSection()->getBeginSymbol();
550     if (isDwoUnit())
551       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
552                       RangeSectionSym);
553     else
554       addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
555                       RangeSectionSym);
556   }
557 }
558 
559 void DwarfCompileUnit::attachRangesOrLowHighPC(
560     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
561   if (Ranges.size() == 1 || !DD->useRangesSection()) {
562     const RangeSpan &Front = Ranges.front();
563     const RangeSpan &Back = Ranges.back();
564     attachLowHighPC(Die, Front.Begin, Back.End);
565   } else
566     addScopeRangeList(Die, std::move(Ranges));
567 }
568 
569 void DwarfCompileUnit::attachRangesOrLowHighPC(
570     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
571   SmallVector<RangeSpan, 2> List;
572   List.reserve(Ranges.size());
573   for (const InsnRange &R : Ranges) {
574     auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
575     auto *EndLabel = DD->getLabelAfterInsn(R.second);
576 
577     const auto *BeginMBB = R.first->getParent();
578     const auto *EndMBB = R.second->getParent();
579 
580     const auto *MBB = BeginMBB;
581     // Basic block sections allows basic block subsets to be placed in unique
582     // sections. For each section, the begin and end label must be added to the
583     // list. If there is more than one range, debug ranges must be used.
584     // Otherwise, low/high PC can be used.
585     // FIXME: Debug Info Emission depends on block order and this assumes that
586     // the order of blocks will be frozen beyond this point.
587     do {
588       if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
589         auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
590         List.push_back(
591             {MBB->sameSection(BeginMBB) ? BeginLabel
592                                         : MBBSectionRange.BeginLabel,
593              MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
594       }
595       if (MBB->sameSection(EndMBB))
596         break;
597       MBB = MBB->getNextNode();
598     } while (true);
599   }
600   attachRangesOrLowHighPC(Die, std::move(List));
601 }
602 
603 // This scope represents inlined body of a function. Construct DIE to
604 // represent this concrete inlined copy of the function.
605 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
606   assert(Scope->getScopeNode());
607   auto *DS = Scope->getScopeNode();
608   auto *InlinedSP = getDISubprogram(DS);
609   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
610   // was inlined from another compile unit.
611   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
612   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
613 
614   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
615   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
616 
617   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
618 
619   // Add the call site information to the DIE.
620   const DILocation *IA = Scope->getInlinedAt();
621   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
622           getOrCreateSourceID(IA->getFile()));
623   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
624   if (IA->getColumn())
625     addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
626   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
627     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
628             IA->getDiscriminator());
629 
630   // Add name to the name table, we do this here because we're guaranteed
631   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
632   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
633 
634   return ScopeDIE;
635 }
636 
637 // Construct new DW_TAG_lexical_block for this scope and attach
638 // DW_AT_low_pc/DW_AT_high_pc labels.
639 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
640   if (DD->isLexicalScopeDIENull(Scope))
641     return nullptr;
642 
643   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
644   if (Scope->isAbstractScope())
645     return ScopeDIE;
646 
647   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
648 
649   return ScopeDIE;
650 }
651 
652 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
653 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
654   auto D = constructVariableDIEImpl(DV, Abstract);
655   DV.setDIE(*D);
656   return D;
657 }
658 
659 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
660                                          const LexicalScope &Scope) {
661   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
662   insertDIE(DL.getLabel(), LabelDie);
663   DL.setDIE(*LabelDie);
664 
665   if (Scope.isAbstractScope())
666     applyLabelAttributes(DL, *LabelDie);
667 
668   return LabelDie;
669 }
670 
671 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
672                                                 bool Abstract) {
673   // Define variable debug information entry.
674   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
675   insertDIE(DV.getVariable(), VariableDie);
676 
677   if (Abstract) {
678     applyVariableAttributes(DV, *VariableDie);
679     return VariableDie;
680   }
681 
682   // Add variable address.
683 
684   unsigned Index = DV.getDebugLocListIndex();
685   if (Index != ~0U) {
686     addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
687     auto TagOffset = DV.getDebugLocListTagOffset();
688     if (TagOffset)
689       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
690               *TagOffset);
691     return VariableDie;
692   }
693 
694   // Check if variable has a single location description.
695   if (auto *DVal = DV.getValueLoc()) {
696     if (DVal->isLocation())
697       addVariableAddress(DV, *VariableDie, DVal->getLoc());
698     else if (DVal->isInt()) {
699       auto *Expr = DV.getSingleExpression();
700       if (Expr && Expr->getNumElements()) {
701         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
702         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
703         // If there is an expression, emit raw unsigned bytes.
704         DwarfExpr.addFragmentOffset(Expr);
705         DwarfExpr.addUnsignedConstant(DVal->getInt());
706         DwarfExpr.addExpression(Expr);
707         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
708         if (DwarfExpr.TagOffset)
709           addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
710                   dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
711 
712       } else
713         addConstantValue(*VariableDie, DVal->getInt(), DV.getType());
714     } else if (DVal->isConstantFP()) {
715       addConstantFPValue(*VariableDie, DVal->getConstantFP());
716     } else if (DVal->isConstantInt()) {
717       addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType());
718     }
719     return VariableDie;
720   }
721 
722   // .. else use frame index.
723   if (!DV.hasFrameIndexExprs())
724     return VariableDie;
725 
726   Optional<unsigned> NVPTXAddressSpace;
727   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
728   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
729   for (auto &Fragment : DV.getFrameIndexExprs()) {
730     Register FrameReg;
731     const DIExpression *Expr = Fragment.Expr;
732     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
733     StackOffset Offset =
734         TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
735     DwarfExpr.addFragmentOffset(Expr);
736 
737     assert(!Offset.getScalable() &&
738            "Frame offsets with a scalable component are not supported");
739 
740     SmallVector<uint64_t, 8> Ops;
741     DIExpression::appendOffset(Ops, Offset.getFixed());
742     // According to
743     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
744     // cuda-gdb requires DW_AT_address_class for all variables to be able to
745     // correctly interpret address space of the variable address.
746     // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
747     // sequence for the NVPTX + gdb target.
748     unsigned LocalNVPTXAddressSpace;
749     if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
750       const DIExpression *NewExpr =
751           DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
752       if (NewExpr != Expr) {
753         Expr = NewExpr;
754         NVPTXAddressSpace = LocalNVPTXAddressSpace;
755       }
756     }
757     if (Expr)
758       Ops.append(Expr->elements_begin(), Expr->elements_end());
759     DIExpressionCursor Cursor(Ops);
760     DwarfExpr.setMemoryLocationKind();
761     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
762       addOpAddress(*Loc, FrameSymbol);
763     else
764       DwarfExpr.addMachineRegExpression(
765           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
766     DwarfExpr.addExpression(std::move(Cursor));
767   }
768   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
769     // According to
770     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
771     // cuda-gdb requires DW_AT_address_class for all variables to be able to
772     // correctly interpret address space of the variable address.
773     const unsigned NVPTX_ADDR_local_space = 6;
774     addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
775             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
776   }
777   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
778   if (DwarfExpr.TagOffset)
779     addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
780             *DwarfExpr.TagOffset);
781 
782   return VariableDie;
783 }
784 
785 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
786                                             const LexicalScope &Scope,
787                                             DIE *&ObjectPointer) {
788   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
789   if (DV.isObjectPointer())
790     ObjectPointer = Var;
791   return Var;
792 }
793 
794 /// Return all DIVariables that appear in count: expressions.
795 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
796   SmallVector<const DIVariable *, 2> Result;
797   auto *Array = dyn_cast<DICompositeType>(Var->getType());
798   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
799     return Result;
800   if (auto *DLVar = Array->getDataLocation())
801     Result.push_back(DLVar);
802   if (auto *AsVar = Array->getAssociated())
803     Result.push_back(AsVar);
804   if (auto *AlVar = Array->getAllocated())
805     Result.push_back(AlVar);
806   for (auto *El : Array->getElements()) {
807     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
808       if (auto Count = Subrange->getCount())
809         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
810           Result.push_back(Dependency);
811       if (auto LB = Subrange->getLowerBound())
812         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
813           Result.push_back(Dependency);
814       if (auto UB = Subrange->getUpperBound())
815         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
816           Result.push_back(Dependency);
817       if (auto ST = Subrange->getStride())
818         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
819           Result.push_back(Dependency);
820     } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
821       if (auto Count = GenericSubrange->getCount())
822         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
823           Result.push_back(Dependency);
824       if (auto LB = GenericSubrange->getLowerBound())
825         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
826           Result.push_back(Dependency);
827       if (auto UB = GenericSubrange->getUpperBound())
828         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
829           Result.push_back(Dependency);
830       if (auto ST = GenericSubrange->getStride())
831         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
832           Result.push_back(Dependency);
833     }
834   }
835   return Result;
836 }
837 
838 /// Sort local variables so that variables appearing inside of helper
839 /// expressions come first.
840 static SmallVector<DbgVariable *, 8>
841 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
842   SmallVector<DbgVariable *, 8> Result;
843   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
844   // Map back from a DIVariable to its containing DbgVariable.
845   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
846   // Set of DbgVariables in Result.
847   SmallDenseSet<DbgVariable *, 8> Visited;
848   // For cycle detection.
849   SmallDenseSet<DbgVariable *, 8> Visiting;
850 
851   // Initialize the worklist and the DIVariable lookup table.
852   for (auto Var : reverse(Input)) {
853     DbgVar.insert({Var->getVariable(), Var});
854     WorkList.push_back({Var, 0});
855   }
856 
857   // Perform a stable topological sort by doing a DFS.
858   while (!WorkList.empty()) {
859     auto Item = WorkList.back();
860     DbgVariable *Var = Item.getPointer();
861     bool visitedAllDependencies = Item.getInt();
862     WorkList.pop_back();
863 
864     // Dependency is in a different lexical scope or a global.
865     if (!Var)
866       continue;
867 
868     // Already handled.
869     if (Visited.count(Var))
870       continue;
871 
872     // Add to Result if all dependencies are visited.
873     if (visitedAllDependencies) {
874       Visited.insert(Var);
875       Result.push_back(Var);
876       continue;
877     }
878 
879     // Detect cycles.
880     auto Res = Visiting.insert(Var);
881     if (!Res.second) {
882       assert(false && "dependency cycle in local variables");
883       return Result;
884     }
885 
886     // Push dependencies and this node onto the worklist, so that this node is
887     // visited again after all of its dependencies are handled.
888     WorkList.push_back({Var, 1});
889     for (auto *Dependency : dependencies(Var)) {
890       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
891       WorkList.push_back({DbgVar[Dep], 0});
892     }
893   }
894   return Result;
895 }
896 
897 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
898                                               SmallVectorImpl<DIE *> &Children,
899                                               bool *HasNonScopeChildren) {
900   assert(Children.empty());
901   DIE *ObjectPointer = nullptr;
902 
903   // Emit function arguments (order is significant).
904   auto Vars = DU->getScopeVariables().lookup(Scope);
905   for (auto &DV : Vars.Args)
906     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
907 
908   // Emit local variables.
909   auto Locals = sortLocalVars(Vars.Locals);
910   for (DbgVariable *DV : Locals)
911     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
912 
913   // Skip imported directives in gmlt-like data.
914   if (!includeMinimalInlineScopes()) {
915     // There is no need to emit empty lexical block DIE.
916     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
917       Children.push_back(
918           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
919   }
920 
921   if (HasNonScopeChildren)
922     *HasNonScopeChildren = !Children.empty();
923 
924   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
925     Children.push_back(constructLabelDIE(*DL, *Scope));
926 
927   for (LexicalScope *LS : Scope->getChildren())
928     constructScopeDIE(LS, Children);
929 
930   return ObjectPointer;
931 }
932 
933 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
934                                                    LexicalScope *Scope) {
935   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
936 
937   if (Scope) {
938     assert(!Scope->getInlinedAt());
939     assert(!Scope->isAbstractScope());
940     // Collect lexical scope children first.
941     // ObjectPointer might be a local (non-argument) local variable if it's a
942     // block's synthetic this pointer.
943     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
944       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
945   }
946 
947   // If this is a variadic function, add an unspecified parameter.
948   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
949 
950   // If we have a single element of null, it is a function that returns void.
951   // If we have more than one elements and the last one is null, it is a
952   // variadic function.
953   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
954       !includeMinimalInlineScopes())
955     ScopeDIE.addChild(
956         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
957 
958   return ScopeDIE;
959 }
960 
961 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
962                                                  DIE &ScopeDIE) {
963   // We create children when the scope DIE is not null.
964   SmallVector<DIE *, 8> Children;
965   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
966 
967   // Add children
968   for (auto &I : Children)
969     ScopeDIE.addChild(std::move(I));
970 
971   return ObjectPointer;
972 }
973 
974 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
975     LexicalScope *Scope) {
976   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
977   if (AbsDef)
978     return;
979 
980   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
981 
982   DIE *ContextDIE;
983   DwarfCompileUnit *ContextCU = this;
984 
985   if (includeMinimalInlineScopes())
986     ContextDIE = &getUnitDie();
987   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
988   // the important distinction that the debug node is not associated with the
989   // DIE (since the debug node will be associated with the concrete DIE, if
990   // any). It could be refactored to some common utility function.
991   else if (auto *SPDecl = SP->getDeclaration()) {
992     ContextDIE = &getUnitDie();
993     getOrCreateSubprogramDIE(SPDecl);
994   } else {
995     ContextDIE = getOrCreateContextDIE(SP->getScope());
996     // The scope may be shared with a subprogram that has already been
997     // constructed in another CU, in which case we need to construct this
998     // subprogram in the same CU.
999     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
1000   }
1001 
1002   // Passing null as the associated node because the abstract definition
1003   // shouldn't be found by lookup.
1004   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
1005   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
1006 
1007   if (!ContextCU->includeMinimalInlineScopes())
1008     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
1009   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
1010     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
1011 }
1012 
1013 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
1014   return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
1015 }
1016 
1017 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1018   if (!useGNUAnalogForDwarf5Feature())
1019     return Tag;
1020   switch (Tag) {
1021   case dwarf::DW_TAG_call_site:
1022     return dwarf::DW_TAG_GNU_call_site;
1023   case dwarf::DW_TAG_call_site_parameter:
1024     return dwarf::DW_TAG_GNU_call_site_parameter;
1025   default:
1026     llvm_unreachable("DWARF5 tag with no GNU analog");
1027   }
1028 }
1029 
1030 dwarf::Attribute
1031 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1032   if (!useGNUAnalogForDwarf5Feature())
1033     return Attr;
1034   switch (Attr) {
1035   case dwarf::DW_AT_call_all_calls:
1036     return dwarf::DW_AT_GNU_all_call_sites;
1037   case dwarf::DW_AT_call_target:
1038     return dwarf::DW_AT_GNU_call_site_target;
1039   case dwarf::DW_AT_call_origin:
1040     return dwarf::DW_AT_abstract_origin;
1041   case dwarf::DW_AT_call_return_pc:
1042     return dwarf::DW_AT_low_pc;
1043   case dwarf::DW_AT_call_value:
1044     return dwarf::DW_AT_GNU_call_site_value;
1045   case dwarf::DW_AT_call_tail_call:
1046     return dwarf::DW_AT_GNU_tail_call;
1047   default:
1048     llvm_unreachable("DWARF5 attribute with no GNU analog");
1049   }
1050 }
1051 
1052 dwarf::LocationAtom
1053 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1054   if (!useGNUAnalogForDwarf5Feature())
1055     return Loc;
1056   switch (Loc) {
1057   case dwarf::DW_OP_entry_value:
1058     return dwarf::DW_OP_GNU_entry_value;
1059   default:
1060     llvm_unreachable("DWARF5 location atom with no GNU analog");
1061   }
1062 }
1063 
1064 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
1065                                                  DIE *CalleeDIE,
1066                                                  bool IsTail,
1067                                                  const MCSymbol *PCAddr,
1068                                                  const MCSymbol *CallAddr,
1069                                                  unsigned CallReg) {
1070   // Insert a call site entry DIE within ScopeDIE.
1071   DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
1072                                      ScopeDIE, nullptr);
1073 
1074   if (CallReg) {
1075     // Indirect call.
1076     addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
1077                MachineLocation(CallReg));
1078   } else {
1079     assert(CalleeDIE && "No DIE for call site entry origin");
1080     addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
1081                 *CalleeDIE);
1082   }
1083 
1084   if (IsTail) {
1085     // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1086     addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
1087 
1088     // Attach the address of the branch instruction to allow the debugger to
1089     // show where the tail call occurred. This attribute has no GNU analog.
1090     //
1091     // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1092     // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1093     // site entries to figure out the PC of tail-calling branch instructions.
1094     // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1095     // don't emit it here.
1096     //
1097     // There's no need to tie non-GDB debuggers to this non-standardness, as it
1098     // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1099     // the standard DW_AT_call_pc info.
1100     if (!useGNUAnalogForDwarf5Feature())
1101       addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
1102   }
1103 
1104   // Attach the return PC to allow the debugger to disambiguate call paths
1105   // from one function to another.
1106   //
1107   // The return PC is only really needed when the call /isn't/ a tail call, but
1108   // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1109   // the DW_AT_call_pc emission logic for an explanation).
1110   if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1111     assert(PCAddr && "Missing return PC information for a call");
1112     addLabelAddress(CallSiteDIE,
1113                     getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
1114   }
1115 
1116   return CallSiteDIE;
1117 }
1118 
1119 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
1120     DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1121   for (const auto &Param : Params) {
1122     unsigned Register = Param.getRegister();
1123     auto CallSiteDieParam =
1124         DIE::get(DIEValueAllocator,
1125                  getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
1126     insertDIE(CallSiteDieParam);
1127     addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
1128                MachineLocation(Register));
1129 
1130     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1131     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1132     DwarfExpr.setCallSiteParamValueFlag();
1133 
1134     DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
1135 
1136     addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1137              DwarfExpr.finalize());
1138 
1139     CallSiteDIE.addChild(CallSiteDieParam);
1140   }
1141 }
1142 
1143 DIE *DwarfCompileUnit::constructImportedEntityDIE(
1144     const DIImportedEntity *Module) {
1145   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
1146   insertDIE(Module, IMDie);
1147   DIE *EntityDie;
1148   auto *Entity = Module->getEntity();
1149   if (auto *NS = dyn_cast<DINamespace>(Entity))
1150     EntityDie = getOrCreateNameSpace(NS);
1151   else if (auto *M = dyn_cast<DIModule>(Entity))
1152     EntityDie = getOrCreateModule(M);
1153   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1154     EntityDie = getOrCreateSubprogramDIE(SP);
1155   else if (auto *T = dyn_cast<DIType>(Entity))
1156     EntityDie = getOrCreateTypeDIE(T);
1157   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1158     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1159   else
1160     EntityDie = getDIE(Entity);
1161   assert(EntityDie);
1162   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1163   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1164   StringRef Name = Module->getName();
1165   if (!Name.empty())
1166     addString(*IMDie, dwarf::DW_AT_name, Name);
1167 
1168   return IMDie;
1169 }
1170 
1171 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1172   DIE *D = getDIE(SP);
1173   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1174     if (D)
1175       // If this subprogram has an abstract definition, reference that
1176       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1177   } else {
1178     assert(D || includeMinimalInlineScopes());
1179     if (D)
1180       // And attach the attributes
1181       applySubprogramAttributesToDefinition(SP, *D);
1182   }
1183 }
1184 
1185 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1186   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1187 
1188   auto *Die = Entity->getDIE();
1189   /// Label may be used to generate DW_AT_low_pc, so put it outside
1190   /// if/else block.
1191   const DbgLabel *Label = nullptr;
1192   if (AbsEntity && AbsEntity->getDIE()) {
1193     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1194     Label = dyn_cast<const DbgLabel>(Entity);
1195   } else {
1196     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1197       applyVariableAttributes(*Var, *Die);
1198     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1199       applyLabelAttributes(*Label, *Die);
1200     else
1201       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1202   }
1203 
1204   if (Label)
1205     if (const auto *Sym = Label->getSymbol())
1206       addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1207 }
1208 
1209 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1210   auto &AbstractEntities = getAbstractEntities();
1211   auto I = AbstractEntities.find(Node);
1212   if (I != AbstractEntities.end())
1213     return I->second.get();
1214   return nullptr;
1215 }
1216 
1217 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1218                                             LexicalScope *Scope) {
1219   assert(Scope && Scope->isAbstractScope());
1220   auto &Entity = getAbstractEntities()[Node];
1221   if (isa<const DILocalVariable>(Node)) {
1222     Entity = std::make_unique<DbgVariable>(
1223                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
1224     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1225   } else if (isa<const DILabel>(Node)) {
1226     Entity = std::make_unique<DbgLabel>(
1227                         cast<const DILabel>(Node), nullptr /* IA */);
1228     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1229   }
1230 }
1231 
1232 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1233   // Don't bother labeling the .dwo unit, as its offset isn't used.
1234   if (!Skeleton && !DD->useSectionsAsReferences()) {
1235     LabelBegin = Asm->createTempSymbol("cu_begin");
1236     Asm->OutStreamer->emitLabel(LabelBegin);
1237   }
1238 
1239   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1240                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1241                                                       : dwarf::DW_UT_compile;
1242   DwarfUnit::emitCommonHeader(UseOffsets, UT);
1243   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1244     Asm->emitInt64(getDWOId());
1245 }
1246 
1247 bool DwarfCompileUnit::hasDwarfPubSections() const {
1248   switch (CUNode->getNameTableKind()) {
1249   case DICompileUnit::DebugNameTableKind::None:
1250     return false;
1251     // Opting in to GNU Pubnames/types overrides the default to ensure these are
1252     // generated for things like Gold's gdb_index generation.
1253   case DICompileUnit::DebugNameTableKind::GNU:
1254     return true;
1255   case DICompileUnit::DebugNameTableKind::Default:
1256     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1257            !CUNode->isDebugDirectivesOnly() &&
1258            DD->getAccelTableKind() != AccelTableKind::Apple &&
1259            DD->getDwarfVersion() < 5;
1260   }
1261   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1262 }
1263 
1264 /// addGlobalName - Add a new global name to the compile unit.
1265 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1266                                      const DIScope *Context) {
1267   if (!hasDwarfPubSections())
1268     return;
1269   std::string FullName = getParentContextString(Context) + Name.str();
1270   GlobalNames[FullName] = &Die;
1271 }
1272 
1273 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1274                                                 const DIScope *Context) {
1275   if (!hasDwarfPubSections())
1276     return;
1277   std::string FullName = getParentContextString(Context) + Name.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   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1283 }
1284 
1285 /// Add a new global type to the unit.
1286 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1287                                      const DIScope *Context) {
1288   if (!hasDwarfPubSections())
1289     return;
1290   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1291   GlobalTypes[FullName] = &Die;
1292 }
1293 
1294 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1295                                              const DIScope *Context) {
1296   if (!hasDwarfPubSections())
1297     return;
1298   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1299   // Insert, allowing the entry to remain as-is if it's already present
1300   // This way the CU-level type DIE is preferred over the "can't describe this
1301   // type as a unit offset because it's not really in the CU at all, it's only
1302   // in a type unit"
1303   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1304 }
1305 
1306 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1307                                           MachineLocation Location) {
1308   if (DV.hasComplexAddress())
1309     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1310   else
1311     addAddress(Die, dwarf::DW_AT_location, Location);
1312 }
1313 
1314 /// Add an address attribute to a die based on the location provided.
1315 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1316                                   const MachineLocation &Location) {
1317   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1318   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1319   if (Location.isIndirect())
1320     DwarfExpr.setMemoryLocationKind();
1321 
1322   DIExpressionCursor Cursor({});
1323   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1324   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1325     return;
1326   DwarfExpr.addExpression(std::move(Cursor));
1327 
1328   // Now attach the location information to the DIE.
1329   addBlock(Die, Attribute, DwarfExpr.finalize());
1330 
1331   if (DwarfExpr.TagOffset)
1332     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1333             *DwarfExpr.TagOffset);
1334 }
1335 
1336 /// Start with the address based on the location provided, and generate the
1337 /// DWARF information necessary to find the actual variable given the extra
1338 /// address information encoded in the DbgVariable, starting from the starting
1339 /// location.  Add the DWARF information to the die.
1340 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1341                                          dwarf::Attribute Attribute,
1342                                          const MachineLocation &Location) {
1343   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1344   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1345   const DIExpression *DIExpr = DV.getSingleExpression();
1346   DwarfExpr.addFragmentOffset(DIExpr);
1347   DwarfExpr.setLocation(Location, DIExpr);
1348 
1349   DIExpressionCursor Cursor(DIExpr);
1350 
1351   if (DIExpr->isEntryValue())
1352     DwarfExpr.beginEntryValueExpression(Cursor);
1353 
1354   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1355   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1356     return;
1357   DwarfExpr.addExpression(std::move(Cursor));
1358 
1359   // Now attach the location information to the DIE.
1360   addBlock(Die, Attribute, DwarfExpr.finalize());
1361 
1362   if (DwarfExpr.TagOffset)
1363     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1364             *DwarfExpr.TagOffset);
1365 }
1366 
1367 /// Add a Dwarf loclistptr attribute data and value.
1368 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1369                                        unsigned Index) {
1370   dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1371                          ? dwarf::DW_FORM_loclistx
1372                          : DD->getDwarfSectionOffsetForm();
1373   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
1374 }
1375 
1376 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1377                                                DIE &VariableDie) {
1378   StringRef Name = Var.getName();
1379   if (!Name.empty())
1380     addString(VariableDie, dwarf::DW_AT_name, Name);
1381   const auto *DIVar = Var.getVariable();
1382   if (DIVar)
1383     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1384       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1385               AlignInBytes);
1386 
1387   addSourceLine(VariableDie, DIVar);
1388   addType(VariableDie, Var.getType());
1389   if (Var.isArtificial())
1390     addFlag(VariableDie, dwarf::DW_AT_artificial);
1391 }
1392 
1393 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1394                                             DIE &LabelDie) {
1395   StringRef Name = Label.getName();
1396   if (!Name.empty())
1397     addString(LabelDie, dwarf::DW_AT_name, Name);
1398   const auto *DILabel = Label.getLabel();
1399   addSourceLine(LabelDie, DILabel);
1400 }
1401 
1402 /// Add a Dwarf expression attribute data and value.
1403 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1404                                const MCExpr *Expr) {
1405   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1406 }
1407 
1408 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1409     const DISubprogram *SP, DIE &SPDie) {
1410   auto *SPDecl = SP->getDeclaration();
1411   auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1412   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1413   addGlobalName(SP->getName(), SPDie, Context);
1414 }
1415 
1416 bool DwarfCompileUnit::isDwoUnit() const {
1417   return DD->useSplitDwarf() && Skeleton;
1418 }
1419 
1420 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1421   constructTypeDIE(D, CTy);
1422 }
1423 
1424 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1425   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1426          (DD->useSplitDwarf() && !Skeleton);
1427 }
1428 
1429 void DwarfCompileUnit::addAddrTableBase() {
1430   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1431   MCSymbol *Label = DD->getAddressPool().getLabel();
1432   addSectionLabel(getUnitDie(),
1433                   DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1434                                              : dwarf::DW_AT_GNU_addr_base,
1435                   Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1436 }
1437 
1438 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1439   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1440                new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1441 }
1442 
1443 void DwarfCompileUnit::createBaseTypeDIEs() {
1444   // Insert the base_type DIEs directly after the CU so that their offsets will
1445   // fit in the fixed size ULEB128 used inside the location expressions.
1446   // Maintain order by iterating backwards and inserting to the front of CU
1447   // child list.
1448   for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1449     DIE &Die = getUnitDie().addChildFront(
1450       DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1451     SmallString<32> Str;
1452     addString(Die, dwarf::DW_AT_name,
1453               Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1454                     "_" + Twine(Btr.BitSize)).toStringRef(Str));
1455     addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1456     addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
1457 
1458     Btr.Die = &Die;
1459   }
1460 }
1461