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