[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / llvm / lib / CodeGen / AsmPrinter / DwarfCompileUnit.cpp
blobb26960cdebb895fbe68f2dafbffc146fb277adb5
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.
11 //===----------------------------------------------------------------------===//
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/BinaryFormat/Dwarf.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/CodeGen/DIE.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstr.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>
42 using namespace llvm;
44 static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
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;
54 return dwarf::DW_TAG_compile_unit;
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");
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 if ((Skeleton || !DD->useSplitDwarf()) && Label)
70 DD->addArangeLabel(SymbolCU(this, Label));
72 // Don't use the address pool in non-fission or in the skeleton unit itself.
73 if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
74 return addLocalLabelAddress(Die, Attribute, Label);
76 bool UseAddrOffsetFormOrExpressions =
77 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
79 const MCSymbol *Base = nullptr;
80 if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
81 Base = DD->getSectionLabel(&Label->getSection());
83 if (!Base || Base == Label) {
84 unsigned idx = DD->getAddressPool().getIndex(Label);
85 addAttribute(Die, Attribute,
86 DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
87 : dwarf::DW_FORM_GNU_addr_index,
88 DIEInteger(idx));
89 return;
92 // Could be extended to work with DWARFv4 Split DWARF if that's important for
93 // someone. In that case DW_FORM_data would be used.
94 assert(DD->getDwarfVersion() >= 5 &&
95 "Addr+offset expressions are only valuable when using debug_addr (to "
96 "reduce relocations) available in DWARFv5 or higher");
97 if (DD->useAddrOffsetExpressions()) {
98 auto *Loc = new (DIEValueAllocator) DIEBlock();
99 addPoolOpAddress(*Loc, Label);
100 addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
101 } else
102 addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
103 new (DIEValueAllocator) DIEAddrOffset(
104 DD->getAddressPool().getIndex(Base), Label, Base));
107 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
108 dwarf::Attribute Attribute,
109 const MCSymbol *Label) {
110 if (Label)
111 addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
112 else
113 addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
116 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
117 // If we print assembly, we can't separate .file entries according to
118 // compile units. Thus all files will belong to the default compile unit.
120 // FIXME: add a better feature test than hasRawTextSupport. Even better,
121 // extend .file to support this.
122 unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
123 if (!File)
124 return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
125 CUID);
127 if (LastFile != File) {
128 LastFile = File;
129 LastFileID = Asm->OutStreamer->emitDwarfFileDirective(
130 0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
131 File->getSource(), CUID);
133 return LastFileID;
136 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
137 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
138 // Check for pre-existence.
139 if (DIE *Die = getDIE(GV))
140 return Die;
142 assert(GV);
144 auto *GVContext = GV->getScope();
145 const DIType *GTy = GV->getType();
147 auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
148 DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
149 : getOrCreateContextDIE(GVContext);
151 // Add to map.
152 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
153 DIScope *DeclContext;
154 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
155 DeclContext = SDMDecl->getScope();
156 assert(SDMDecl->isStaticMember() && "Expected static member decl");
157 assert(GV->isDefinition());
158 // We need the declaration DIE that is in the static member's class.
159 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
160 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
161 // If the global variable's type is different from the one in the class
162 // member type, assume that it's more specific and also emit it.
163 if (GTy != SDMDecl->getBaseType())
164 addType(*VariableDIE, GTy);
165 } else {
166 DeclContext = GV->getScope();
167 // Add name and type.
168 StringRef DisplayName = GV->getDisplayName();
169 if (!DisplayName.empty())
170 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
171 if (GTy)
172 addType(*VariableDIE, GTy);
174 // Add scoping info.
175 if (!GV->isLocalToUnit())
176 addFlag(*VariableDIE, dwarf::DW_AT_external);
178 // Add line number info.
179 addSourceLine(*VariableDIE, GV);
182 if (!GV->isDefinition())
183 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
184 else
185 addGlobalName(GV->getName(), *VariableDIE, DeclContext);
187 addAnnotation(*VariableDIE, GV->getAnnotations());
189 if (uint32_t AlignInBytes = GV->getAlignInBytes())
190 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
191 AlignInBytes);
193 if (MDTuple *TP = GV->getTemplateParams())
194 addTemplateParams(*VariableDIE, DINodeArray(TP));
196 // Add location.
197 addLocationAttribute(VariableDIE, GV, GlobalExprs);
199 return VariableDIE;
202 void DwarfCompileUnit::addLocationAttribute(
203 DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
204 bool addToAccelTable = false;
205 DIELoc *Loc = nullptr;
206 Optional<unsigned> NVPTXAddressSpace;
207 std::unique_ptr<DIEDwarfExpression> DwarfExpr;
208 for (const auto &GE : GlobalExprs) {
209 const GlobalVariable *Global = GE.Var;
210 const DIExpression *Expr = GE.Expr;
212 // For compatibility with DWARF 3 and earlier,
213 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
214 // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
215 // DW_AT_const_value(X).
216 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
217 addToAccelTable = true;
218 addConstantValue(
219 *VariableDIE,
220 DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
221 *Expr->isConstant(),
222 Expr->getElement(1));
223 break;
226 // We cannot describe the location of dllimport'd variables: the
227 // computation of their address requires loads from the IAT.
228 if (Global && Global->hasDLLImportStorageClass())
229 continue;
231 // Nothing to describe without address or constant.
232 if (!Global && (!Expr || !Expr->isConstant()))
233 continue;
235 if (Global && Global->isThreadLocal() &&
236 !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
237 continue;
239 if (!Loc) {
240 addToAccelTable = true;
241 Loc = new (DIEValueAllocator) DIELoc;
242 DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
245 if (Expr) {
246 // According to
247 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
248 // cuda-gdb requires DW_AT_address_class for all variables to be able to
249 // correctly interpret address space of the variable address.
250 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
251 // sequence for the NVPTX + gdb target.
252 unsigned LocalNVPTXAddressSpace;
253 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
254 const DIExpression *NewExpr =
255 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
256 if (NewExpr != Expr) {
257 Expr = NewExpr;
258 NVPTXAddressSpace = LocalNVPTXAddressSpace;
261 DwarfExpr->addFragmentOffset(Expr);
264 if (Global) {
265 const MCSymbol *Sym = Asm->getSymbol(Global);
266 // 16-bit platforms like MSP430 and AVR take this path, so sink this
267 // assert to platforms that use it.
268 auto GetPointerSizedFormAndOp = [this]() {
269 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
270 assert((PointerSize == 4 || PointerSize == 8) &&
271 "Add support for other sizes if necessary");
272 struct FormAndOp {
273 dwarf::Form Form;
274 dwarf::LocationAtom Op;
276 return PointerSize == 4
277 ? FormAndOp{dwarf::DW_FORM_data4, dwarf::DW_OP_const4u}
278 : FormAndOp{dwarf::DW_FORM_data8, dwarf::DW_OP_const8u};
280 if (Global->isThreadLocal()) {
281 if (Asm->TM.useEmulatedTLS()) {
282 // TODO: add debug info for emulated thread local mode.
283 } else {
284 // FIXME: Make this work with -gsplit-dwarf.
285 // Based on GCC's support for TLS:
286 if (!DD->useSplitDwarf()) {
287 auto FormAndOp = GetPointerSizedFormAndOp();
288 // 1) Start with a constNu of the appropriate pointer size
289 addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
290 // 2) containing the (relocated) offset of the TLS variable
291 // within the module's TLS block.
292 addExpr(*Loc, FormAndOp.Form,
293 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
294 } else {
295 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
296 addUInt(*Loc, dwarf::DW_FORM_udata,
297 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
299 // 3) followed by an OP to make the debugger do a TLS lookup.
300 addUInt(*Loc, dwarf::DW_FORM_data1,
301 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
302 : dwarf::DW_OP_form_tls_address);
304 } else if ((Asm->TM.getRelocationModel() == Reloc::RWPI ||
305 Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) &&
306 !Asm->getObjFileLowering()
307 .getKindForGlobal(Global, Asm->TM)
308 .isReadOnly()) {
309 auto FormAndOp = GetPointerSizedFormAndOp();
310 // Constant
311 addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
312 // Relocation offset
313 addExpr(*Loc, FormAndOp.Form,
314 Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
315 // Base register
316 Register BaseReg = Asm->getObjFileLowering().getStaticBase();
317 BaseReg = Asm->TM.getMCRegisterInfo()->getDwarfRegNum(BaseReg, false);
318 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + BaseReg);
319 // Offset from base register
320 addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
321 // Operation
322 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
323 } else {
324 DD->addArangeLabel(SymbolCU(this, Sym));
325 addOpAddress(*Loc, Sym);
328 // Global variables attached to symbols are memory locations.
329 // It would be better if this were unconditional, but malformed input that
330 // mixes non-fragments and fragments for the same variable is too expensive
331 // to detect in the verifier.
332 if (DwarfExpr->isUnknownLocation())
333 DwarfExpr->setMemoryLocationKind();
334 DwarfExpr->addExpression(Expr);
336 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
337 // According to
338 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
339 // cuda-gdb requires DW_AT_address_class for all variables to be able to
340 // correctly interpret address space of the variable address.
341 const unsigned NVPTX_ADDR_global_space = 5;
342 addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
343 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
345 if (Loc)
346 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
348 if (DD->useAllLinkageNames())
349 addLinkageName(*VariableDIE, GV->getLinkageName());
351 if (addToAccelTable) {
352 DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
354 // If the linkage name is different than the name, go ahead and output
355 // that as well into the name table.
356 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
357 DD->useAllLinkageNames())
358 DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
362 DIE *DwarfCompileUnit::getOrCreateCommonBlock(
363 const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
364 // Check for pre-existence.
365 if (DIE *NDie = getDIE(CB))
366 return NDie;
367 DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
368 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
369 StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
370 addString(NDie, dwarf::DW_AT_name, Name);
371 addGlobalName(Name, NDie, CB->getScope());
372 if (CB->getFile())
373 addSourceLine(NDie, CB->getLineNo(), CB->getFile());
374 if (DIGlobalVariable *V = CB->getDecl())
375 getCU().addLocationAttribute(&NDie, V, GlobalExprs);
376 return &NDie;
379 void DwarfCompileUnit::addRange(RangeSpan Range) {
380 DD->insertSectionLabel(Range.Begin);
382 auto *PrevCU = DD->getPrevCU();
383 bool SameAsPrevCU = this == PrevCU;
384 DD->setPrevCU(this);
385 // If we have no current ranges just add the range and return, otherwise,
386 // check the current section and CU against the previous section and CU we
387 // emitted into and the subprogram was contained within. If these are the
388 // same then extend our current range, otherwise add this as a new range.
389 if (CURanges.empty() || !SameAsPrevCU ||
390 (&CURanges.back().End->getSection() !=
391 &Range.End->getSection())) {
392 // Before a new range is added, always terminate the prior line table.
393 if (PrevCU)
394 DD->terminateLineTable(PrevCU);
395 CURanges.push_back(Range);
396 return;
399 CURanges.back().End = Range.End;
402 void DwarfCompileUnit::initStmtList() {
403 if (CUNode->isDebugDirectivesOnly())
404 return;
406 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
407 if (DD->useSectionsAsReferences()) {
408 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
409 } else {
410 LineTableStartSym =
411 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
414 // DW_AT_stmt_list is a offset of line number information for this
415 // compile unit in debug_line section. For split dwarf this is
416 // left in the skeleton CU and so not included.
417 // The line table entries are not always emitted in assembly, so it
418 // is not okay to use line_table_start here.
419 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
420 TLOF.getDwarfLineSection()->getBeginSymbol());
423 void DwarfCompileUnit::applyStmtList(DIE &D) {
424 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
425 addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
426 TLOF.getDwarfLineSection()->getBeginSymbol());
429 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
430 const MCSymbol *End) {
431 assert(Begin && "Begin label should not be null!");
432 assert(End && "End label should not be null!");
433 assert(Begin->isDefined() && "Invalid starting label");
434 assert(End->isDefined() && "Invalid end label");
436 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
437 if (DD->getDwarfVersion() < 4)
438 addLabelAddress(D, dwarf::DW_AT_high_pc, End);
439 else
440 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
443 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
444 // and DW_AT_high_pc attributes. If there are global variables in this
445 // scope then create and insert DIEs for these variables.
446 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
447 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
449 SmallVector<RangeSpan, 2> BB_List;
450 // If basic block sections are on, ranges for each basic block section has
451 // to be emitted separately.
452 for (const auto &R : Asm->MBBSectionRanges)
453 BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
455 attachRangesOrLowHighPC(*SPDie, BB_List);
457 if (DD->useAppleExtensionAttributes() &&
458 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
459 *DD->getCurrentFunction()))
460 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
462 // Only include DW_AT_frame_base in full debug info
463 if (!includeMinimalInlineScopes()) {
464 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
465 TargetFrameLowering::DwarfFrameBase FrameBase =
466 TFI->getDwarfFrameBase(*Asm->MF);
467 switch (FrameBase.Kind) {
468 case TargetFrameLowering::DwarfFrameBase::Register: {
469 if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
470 MachineLocation Location(FrameBase.Location.Reg);
471 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
473 break;
475 case TargetFrameLowering::DwarfFrameBase::CFA: {
476 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
477 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
478 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
479 break;
481 case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
482 // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
483 // don't want to depend on target specific headers in this code?
484 const unsigned TI_GLOBAL_RELOC = 3;
485 if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
486 // These need to be relocatable.
487 assert(FrameBase.Location.WasmLoc.Index == 0); // Only SP so far.
488 auto SPSym = cast<MCSymbolWasm>(
489 Asm->GetExternalSymbolSymbol("__stack_pointer"));
490 // FIXME: this repeats what WebAssemblyMCInstLower::
491 // GetExternalSymbolSymbol does, since if there's no code that
492 // refers to this symbol, we have to set it here.
493 SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
494 SPSym->setGlobalType(wasm::WasmGlobalType{
495 uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
496 Triple::wasm64
497 ? wasm::WASM_TYPE_I64
498 : wasm::WASM_TYPE_I32),
499 true});
500 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
501 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
502 addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
503 if (!isDwoUnit()) {
504 addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
505 } else {
506 // FIXME: when writing dwo, we need to avoid relocations. Probably
507 // the "right" solution is to treat globals the way func and data
508 // symbols are (with entries in .debug_addr).
509 // For now, since we only ever use index 0, this should work as-is.
510 addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
512 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
513 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
514 } else {
515 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
516 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
517 DIExpressionCursor Cursor({});
518 DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
519 FrameBase.Location.WasmLoc.Index);
520 DwarfExpr.addExpression(std::move(Cursor));
521 addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
523 break;
528 // Add name to the name table, we do this here because we're guaranteed
529 // to have concrete versions of our DW_TAG_subprogram nodes.
530 DD->addSubprogramNames(*CUNode, SP, *SPDie);
532 return *SPDie;
535 // Construct a DIE for this scope.
536 void DwarfCompileUnit::constructScopeDIE(LexicalScope *Scope,
537 DIE &ParentScopeDIE) {
538 if (!Scope || !Scope->getScopeNode())
539 return;
541 auto *DS = Scope->getScopeNode();
543 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
544 "Only handle inlined subprograms here, use "
545 "constructSubprogramScopeDIE for non-inlined "
546 "subprograms");
548 // Emit inlined subprograms.
549 if (Scope->getParent() && isa<DISubprogram>(DS)) {
550 DIE *ScopeDIE = constructInlinedScopeDIE(Scope);
551 if (!ScopeDIE)
552 return;
554 ParentScopeDIE.addChild(ScopeDIE);
555 createAndAddScopeChildren(Scope, *ScopeDIE);
556 return;
559 // Early exit when we know the scope DIE is going to be null.
560 if (DD->isLexicalScopeDIENull(Scope))
561 return;
563 // Emit lexical blocks.
564 DIE *ScopeDIE = constructLexicalScopeDIE(Scope);
565 assert(ScopeDIE && "Scope DIE should not be null.");
567 ParentScopeDIE.addChild(ScopeDIE);
568 createAndAddScopeChildren(Scope, *ScopeDIE);
571 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
572 SmallVector<RangeSpan, 2> Range) {
574 HasRangeLists = true;
576 // Add the range list to the set of ranges to be emitted.
577 auto IndexAndList =
578 (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
579 ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
581 uint32_t Index = IndexAndList.first;
582 auto &List = *IndexAndList.second;
584 // Under fission, ranges are specified by constant offsets relative to the
585 // CU's DW_AT_GNU_ranges_base.
586 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
587 // fission until we support the forms using the .debug_addr section
588 // (DW_RLE_startx_endx etc.).
589 if (DD->getDwarfVersion() >= 5)
590 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
591 else {
592 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
593 const MCSymbol *RangeSectionSym =
594 TLOF.getDwarfRangesSection()->getBeginSymbol();
595 if (isDwoUnit())
596 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
597 RangeSectionSym);
598 else
599 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
600 RangeSectionSym);
604 void DwarfCompileUnit::attachRangesOrLowHighPC(
605 DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
606 assert(!Ranges.empty());
607 if (!DD->useRangesSection() ||
608 (Ranges.size() == 1 &&
609 (!DD->alwaysUseRanges() ||
610 DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
611 Ranges.front().Begin))) {
612 const RangeSpan &Front = Ranges.front();
613 const RangeSpan &Back = Ranges.back();
614 attachLowHighPC(Die, Front.Begin, Back.End);
615 } else
616 addScopeRangeList(Die, std::move(Ranges));
619 void DwarfCompileUnit::attachRangesOrLowHighPC(
620 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
621 SmallVector<RangeSpan, 2> List;
622 List.reserve(Ranges.size());
623 for (const InsnRange &R : Ranges) {
624 auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
625 auto *EndLabel = DD->getLabelAfterInsn(R.second);
627 const auto *BeginMBB = R.first->getParent();
628 const auto *EndMBB = R.second->getParent();
630 const auto *MBB = BeginMBB;
631 // Basic block sections allows basic block subsets to be placed in unique
632 // sections. For each section, the begin and end label must be added to the
633 // list. If there is more than one range, debug ranges must be used.
634 // Otherwise, low/high PC can be used.
635 // FIXME: Debug Info Emission depends on block order and this assumes that
636 // the order of blocks will be frozen beyond this point.
637 do {
638 if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
639 auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
640 List.push_back(
641 {MBB->sameSection(BeginMBB) ? BeginLabel
642 : MBBSectionRange.BeginLabel,
643 MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
645 if (MBB->sameSection(EndMBB))
646 break;
647 MBB = MBB->getNextNode();
648 } while (true);
650 attachRangesOrLowHighPC(Die, std::move(List));
653 // This scope represents inlined body of a function. Construct DIE to
654 // represent this concrete inlined copy of the function.
655 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
656 assert(Scope->getScopeNode());
657 auto *DS = Scope->getScopeNode();
658 auto *InlinedSP = getDISubprogram(DS);
659 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
660 // was inlined from another compile unit.
661 DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
662 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
664 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
665 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
667 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
669 // Add the call site information to the DIE.
670 const DILocation *IA = Scope->getInlinedAt();
671 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
672 getOrCreateSourceID(IA->getFile()));
673 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
674 if (IA->getColumn())
675 addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
676 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
677 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
678 IA->getDiscriminator());
680 // Add name to the name table, we do this here because we're guaranteed
681 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
682 DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
684 return ScopeDIE;
687 // Construct new DW_TAG_lexical_block for this scope and attach
688 // DW_AT_low_pc/DW_AT_high_pc labels.
689 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
690 if (DD->isLexicalScopeDIENull(Scope))
691 return nullptr;
693 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
694 if (Scope->isAbstractScope())
695 return ScopeDIE;
697 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
699 return ScopeDIE;
702 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
703 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
704 auto D = constructVariableDIEImpl(DV, Abstract);
705 DV.setDIE(*D);
706 return D;
709 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
710 const LexicalScope &Scope) {
711 auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
712 insertDIE(DL.getLabel(), LabelDie);
713 DL.setDIE(*LabelDie);
715 if (Scope.isAbstractScope())
716 applyLabelAttributes(DL, *LabelDie);
718 return LabelDie;
721 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
722 bool Abstract) {
723 // Define variable debug information entry.
724 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
725 insertDIE(DV.getVariable(), VariableDie);
727 if (Abstract) {
728 applyVariableAttributes(DV, *VariableDie);
729 return VariableDie;
732 // Add variable address.
734 unsigned Index = DV.getDebugLocListIndex();
735 if (Index != ~0U) {
736 addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
737 auto TagOffset = DV.getDebugLocListTagOffset();
738 if (TagOffset)
739 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
740 *TagOffset);
741 return VariableDie;
744 // Check if variable has a single location description.
745 if (auto *DVal = DV.getValueLoc()) {
746 if (!DVal->isVariadic()) {
747 const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
748 if (Entry->isLocation()) {
749 addVariableAddress(DV, *VariableDie, Entry->getLoc());
750 } else if (Entry->isInt()) {
751 auto *Expr = DV.getSingleExpression();
752 if (Expr && Expr->getNumElements()) {
753 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
754 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
755 // If there is an expression, emit raw unsigned bytes.
756 DwarfExpr.addFragmentOffset(Expr);
757 DwarfExpr.addUnsignedConstant(Entry->getInt());
758 DwarfExpr.addExpression(Expr);
759 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
760 if (DwarfExpr.TagOffset)
761 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
762 dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
763 } else
764 addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
765 } else if (Entry->isConstantFP()) {
766 addConstantFPValue(*VariableDie, Entry->getConstantFP());
767 } else if (Entry->isConstantInt()) {
768 addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
769 } else if (Entry->isTargetIndexLocation()) {
770 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
771 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
772 const DIBasicType *BT = dyn_cast<DIBasicType>(
773 static_cast<const Metadata *>(DV.getVariable()->getType()));
774 DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
775 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
777 return VariableDie;
779 // If any of the location entries are registers with the value 0, then the
780 // location is undefined.
781 if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
782 return Entry.isLocation() && !Entry.getLoc().getReg();
784 return VariableDie;
785 const DIExpression *Expr = DV.getSingleExpression();
786 assert(Expr && "Variadic Debug Value must have an Expression.");
787 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
788 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
789 DwarfExpr.addFragmentOffset(Expr);
790 DIExpressionCursor Cursor(Expr);
791 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
793 auto AddEntry = [&](const DbgValueLocEntry &Entry,
794 DIExpressionCursor &Cursor) {
795 if (Entry.isLocation()) {
796 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
797 Entry.getLoc().getReg()))
798 return false;
799 } else if (Entry.isInt()) {
800 // If there is an expression, emit raw unsigned bytes.
801 DwarfExpr.addUnsignedConstant(Entry.getInt());
802 } else if (Entry.isConstantFP()) {
803 // DwarfExpression does not support arguments wider than 64 bits
804 // (see PR52584).
805 // TODO: Consider chunking expressions containing overly wide
806 // arguments into separate pointer-sized fragment expressions.
807 APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
808 if (RawBytes.getBitWidth() > 64)
809 return false;
810 DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
811 } else if (Entry.isConstantInt()) {
812 APInt RawBytes = Entry.getConstantInt()->getValue();
813 if (RawBytes.getBitWidth() > 64)
814 return false;
815 DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
816 } else if (Entry.isTargetIndexLocation()) {
817 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
818 // TODO TargetIndexLocation is a target-independent. Currently only the
819 // WebAssembly-specific encoding is supported.
820 assert(Asm->TM.getTargetTriple().isWasm());
821 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
822 } else {
823 llvm_unreachable("Unsupported Entry type.");
825 return true;
828 if (!DwarfExpr.addExpression(
829 std::move(Cursor),
830 [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
831 return AddEntry(DVal->getLocEntries()[Idx], Cursor);
833 return VariableDie;
835 // Now attach the location information to the DIE.
836 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
837 if (DwarfExpr.TagOffset)
838 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
839 *DwarfExpr.TagOffset);
841 return VariableDie;
844 // .. else use frame index.
845 if (!DV.hasFrameIndexExprs())
846 return VariableDie;
848 Optional<unsigned> NVPTXAddressSpace;
849 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
850 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
851 for (const auto &Fragment : DV.getFrameIndexExprs()) {
852 Register FrameReg;
853 const DIExpression *Expr = Fragment.Expr;
854 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
855 StackOffset Offset =
856 TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
857 DwarfExpr.addFragmentOffset(Expr);
859 auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
860 SmallVector<uint64_t, 8> Ops;
861 TRI->getOffsetOpcodes(Offset, Ops);
863 // According to
864 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
865 // cuda-gdb requires DW_AT_address_class for all variables to be able to
866 // correctly interpret address space of the variable address.
867 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
868 // sequence for the NVPTX + gdb target.
869 unsigned LocalNVPTXAddressSpace;
870 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
871 const DIExpression *NewExpr =
872 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
873 if (NewExpr != Expr) {
874 Expr = NewExpr;
875 NVPTXAddressSpace = LocalNVPTXAddressSpace;
878 if (Expr)
879 Ops.append(Expr->elements_begin(), Expr->elements_end());
880 DIExpressionCursor Cursor(Ops);
881 DwarfExpr.setMemoryLocationKind();
882 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
883 addOpAddress(*Loc, FrameSymbol);
884 else
885 DwarfExpr.addMachineRegExpression(
886 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
887 DwarfExpr.addExpression(std::move(Cursor));
889 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
890 // According to
891 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
892 // cuda-gdb requires DW_AT_address_class for all variables to be able to
893 // correctly interpret address space of the variable address.
894 const unsigned NVPTX_ADDR_local_space = 6;
895 addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
896 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
898 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
899 if (DwarfExpr.TagOffset)
900 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
901 *DwarfExpr.TagOffset);
903 return VariableDie;
906 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
907 const LexicalScope &Scope,
908 DIE *&ObjectPointer) {
909 auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
910 if (DV.isObjectPointer())
911 ObjectPointer = Var;
912 return Var;
915 /// Return all DIVariables that appear in count: expressions.
916 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
917 SmallVector<const DIVariable *, 2> Result;
918 auto *Array = dyn_cast<DICompositeType>(Var->getType());
919 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
920 return Result;
921 if (auto *DLVar = Array->getDataLocation())
922 Result.push_back(DLVar);
923 if (auto *AsVar = Array->getAssociated())
924 Result.push_back(AsVar);
925 if (auto *AlVar = Array->getAllocated())
926 Result.push_back(AlVar);
927 for (auto *El : Array->getElements()) {
928 if (auto *Subrange = dyn_cast<DISubrange>(El)) {
929 if (auto Count = Subrange->getCount())
930 if (auto *Dependency = Count.dyn_cast<DIVariable *>())
931 Result.push_back(Dependency);
932 if (auto LB = Subrange->getLowerBound())
933 if (auto *Dependency = LB.dyn_cast<DIVariable *>())
934 Result.push_back(Dependency);
935 if (auto UB = Subrange->getUpperBound())
936 if (auto *Dependency = UB.dyn_cast<DIVariable *>())
937 Result.push_back(Dependency);
938 if (auto ST = Subrange->getStride())
939 if (auto *Dependency = ST.dyn_cast<DIVariable *>())
940 Result.push_back(Dependency);
941 } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
942 if (auto Count = GenericSubrange->getCount())
943 if (auto *Dependency = Count.dyn_cast<DIVariable *>())
944 Result.push_back(Dependency);
945 if (auto LB = GenericSubrange->getLowerBound())
946 if (auto *Dependency = LB.dyn_cast<DIVariable *>())
947 Result.push_back(Dependency);
948 if (auto UB = GenericSubrange->getUpperBound())
949 if (auto *Dependency = UB.dyn_cast<DIVariable *>())
950 Result.push_back(Dependency);
951 if (auto ST = GenericSubrange->getStride())
952 if (auto *Dependency = ST.dyn_cast<DIVariable *>())
953 Result.push_back(Dependency);
956 return Result;
959 /// Sort local variables so that variables appearing inside of helper
960 /// expressions come first.
961 static SmallVector<DbgVariable *, 8>
962 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
963 SmallVector<DbgVariable *, 8> Result;
964 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
965 // Map back from a DIVariable to its containing DbgVariable.
966 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
967 // Set of DbgVariables in Result.
968 SmallDenseSet<DbgVariable *, 8> Visited;
969 // For cycle detection.
970 SmallDenseSet<DbgVariable *, 8> Visiting;
972 // Initialize the worklist and the DIVariable lookup table.
973 for (auto *Var : reverse(Input)) {
974 DbgVar.insert({Var->getVariable(), Var});
975 WorkList.push_back({Var, 0});
978 // Perform a stable topological sort by doing a DFS.
979 while (!WorkList.empty()) {
980 auto Item = WorkList.back();
981 DbgVariable *Var = Item.getPointer();
982 bool visitedAllDependencies = Item.getInt();
983 WorkList.pop_back();
985 assert(Var);
987 // Already handled.
988 if (Visited.count(Var))
989 continue;
991 // Add to Result if all dependencies are visited.
992 if (visitedAllDependencies) {
993 Visited.insert(Var);
994 Result.push_back(Var);
995 continue;
998 // Detect cycles.
999 auto Res = Visiting.insert(Var);
1000 if (!Res.second) {
1001 assert(false && "dependency cycle in local variables");
1002 return Result;
1005 // Push dependencies and this node onto the worklist, so that this node is
1006 // visited again after all of its dependencies are handled.
1007 WorkList.push_back({Var, 1});
1008 for (const auto *Dependency : dependencies(Var)) {
1009 // Don't add dependency if it is in a different lexical scope or a global.
1010 if (const auto *Dep = dyn_cast<const DILocalVariable>(Dependency))
1011 if (DbgVariable *Var = DbgVar.lookup(Dep))
1012 WorkList.push_back({Var, 0});
1015 return Result;
1018 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
1019 LexicalScope *Scope) {
1020 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
1022 if (Scope) {
1023 assert(!Scope->getInlinedAt());
1024 assert(!Scope->isAbstractScope());
1025 // Collect lexical scope children first.
1026 // ObjectPointer might be a local (non-argument) local variable if it's a
1027 // block's synthetic this pointer.
1028 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1029 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
1032 // If this is a variadic function, add an unspecified parameter.
1033 DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
1035 // If we have a single element of null, it is a function that returns void.
1036 // If we have more than one elements and the last one is null, it is a
1037 // variadic function.
1038 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1039 !includeMinimalInlineScopes())
1040 ScopeDIE.addChild(
1041 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
1043 return ScopeDIE;
1046 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
1047 DIE &ScopeDIE) {
1048 DIE *ObjectPointer = nullptr;
1050 // Emit function arguments (order is significant).
1051 auto Vars = DU->getScopeVariables().lookup(Scope);
1052 for (auto &DV : Vars.Args)
1053 ScopeDIE.addChild(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
1055 // Emit local variables.
1056 auto Locals = sortLocalVars(Vars.Locals);
1057 for (DbgVariable *DV : Locals)
1058 ScopeDIE.addChild(constructVariableDIE(*DV, *Scope, ObjectPointer));
1060 // Emit imported entities (skipped in gmlt-like data).
1061 if (!includeMinimalInlineScopes()) {
1062 for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
1063 ScopeDIE.addChild(constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
1066 // Emit labels.
1067 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
1068 ScopeDIE.addChild(constructLabelDIE(*DL, *Scope));
1070 // Emit inner lexical scopes.
1071 auto needToEmitLexicalScope = [this](LexicalScope *LS) {
1072 if (isa<DISubprogram>(LS->getScopeNode()))
1073 return true;
1074 auto Vars = DU->getScopeVariables().lookup(LS);
1075 if (!Vars.Args.empty() || !Vars.Locals.empty())
1076 return true;
1077 if (!includeMinimalInlineScopes() &&
1078 !ImportedEntities[LS->getScopeNode()].empty())
1079 return true;
1080 return false;
1082 for (LexicalScope *LS : Scope->getChildren()) {
1083 // If the lexical block doesn't have non-scope children, skip
1084 // its emission and put its children directly to the parent scope.
1085 if (needToEmitLexicalScope(LS))
1086 constructScopeDIE(LS, ScopeDIE);
1087 else
1088 createAndAddScopeChildren(LS, ScopeDIE);
1091 return ObjectPointer;
1094 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
1095 LexicalScope *Scope) {
1096 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
1097 if (AbsDef)
1098 return;
1100 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
1102 DIE *ContextDIE;
1103 DwarfCompileUnit *ContextCU = this;
1105 if (includeMinimalInlineScopes())
1106 ContextDIE = &getUnitDie();
1107 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
1108 // the important distinction that the debug node is not associated with the
1109 // DIE (since the debug node will be associated with the concrete DIE, if
1110 // any). It could be refactored to some common utility function.
1111 else if (auto *SPDecl = SP->getDeclaration()) {
1112 ContextDIE = &getUnitDie();
1113 getOrCreateSubprogramDIE(SPDecl);
1114 } else {
1115 ContextDIE = getOrCreateContextDIE(SP->getScope());
1116 // The scope may be shared with a subprogram that has already been
1117 // constructed in another CU, in which case we need to construct this
1118 // subprogram in the same CU.
1119 ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
1122 // Passing null as the associated node because the abstract definition
1123 // shouldn't be found by lookup.
1124 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
1125 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
1126 ContextCU->addSInt(*AbsDef, dwarf::DW_AT_inline,
1127 DD->getDwarfVersion() <= 4 ? Optional<dwarf::Form>()
1128 : dwarf::DW_FORM_implicit_const,
1129 dwarf::DW_INL_inlined);
1130 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
1131 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
1134 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
1135 return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
1138 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1139 if (!useGNUAnalogForDwarf5Feature())
1140 return Tag;
1141 switch (Tag) {
1142 case dwarf::DW_TAG_call_site:
1143 return dwarf::DW_TAG_GNU_call_site;
1144 case dwarf::DW_TAG_call_site_parameter:
1145 return dwarf::DW_TAG_GNU_call_site_parameter;
1146 default:
1147 llvm_unreachable("DWARF5 tag with no GNU analog");
1151 dwarf::Attribute
1152 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1153 if (!useGNUAnalogForDwarf5Feature())
1154 return Attr;
1155 switch (Attr) {
1156 case dwarf::DW_AT_call_all_calls:
1157 return dwarf::DW_AT_GNU_all_call_sites;
1158 case dwarf::DW_AT_call_target:
1159 return dwarf::DW_AT_GNU_call_site_target;
1160 case dwarf::DW_AT_call_origin:
1161 return dwarf::DW_AT_abstract_origin;
1162 case dwarf::DW_AT_call_return_pc:
1163 return dwarf::DW_AT_low_pc;
1164 case dwarf::DW_AT_call_value:
1165 return dwarf::DW_AT_GNU_call_site_value;
1166 case dwarf::DW_AT_call_tail_call:
1167 return dwarf::DW_AT_GNU_tail_call;
1168 default:
1169 llvm_unreachable("DWARF5 attribute with no GNU analog");
1173 dwarf::LocationAtom
1174 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1175 if (!useGNUAnalogForDwarf5Feature())
1176 return Loc;
1177 switch (Loc) {
1178 case dwarf::DW_OP_entry_value:
1179 return dwarf::DW_OP_GNU_entry_value;
1180 default:
1181 llvm_unreachable("DWARF5 location atom with no GNU analog");
1185 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
1186 const DISubprogram *CalleeSP,
1187 bool IsTail,
1188 const MCSymbol *PCAddr,
1189 const MCSymbol *CallAddr,
1190 unsigned CallReg) {
1191 // Insert a call site entry DIE within ScopeDIE.
1192 DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
1193 ScopeDIE, nullptr);
1195 if (CallReg) {
1196 // Indirect call.
1197 addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
1198 MachineLocation(CallReg));
1199 } else {
1200 DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
1201 assert(CalleeDIE && "Could not create DIE for call site entry origin");
1202 addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
1203 *CalleeDIE);
1206 if (IsTail) {
1207 // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1208 addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
1210 // Attach the address of the branch instruction to allow the debugger to
1211 // show where the tail call occurred. This attribute has no GNU analog.
1213 // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1214 // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1215 // site entries to figure out the PC of tail-calling branch instructions.
1216 // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1217 // don't emit it here.
1219 // There's no need to tie non-GDB debuggers to this non-standardness, as it
1220 // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1221 // the standard DW_AT_call_pc info.
1222 if (!useGNUAnalogForDwarf5Feature())
1223 addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
1226 // Attach the return PC to allow the debugger to disambiguate call paths
1227 // from one function to another.
1229 // The return PC is only really needed when the call /isn't/ a tail call, but
1230 // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1231 // the DW_AT_call_pc emission logic for an explanation).
1232 if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1233 assert(PCAddr && "Missing return PC information for a call");
1234 addLabelAddress(CallSiteDIE,
1235 getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
1238 return CallSiteDIE;
1241 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
1242 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1243 for (const auto &Param : Params) {
1244 unsigned Register = Param.getRegister();
1245 auto CallSiteDieParam =
1246 DIE::get(DIEValueAllocator,
1247 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
1248 insertDIE(CallSiteDieParam);
1249 addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
1250 MachineLocation(Register));
1252 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1253 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1254 DwarfExpr.setCallSiteParamValueFlag();
1256 DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
1258 addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1259 DwarfExpr.finalize());
1261 CallSiteDIE.addChild(CallSiteDieParam);
1265 DIE *DwarfCompileUnit::constructImportedEntityDIE(
1266 const DIImportedEntity *Module) {
1267 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
1268 insertDIE(Module, IMDie);
1269 DIE *EntityDie;
1270 auto *Entity = Module->getEntity();
1271 if (auto *NS = dyn_cast<DINamespace>(Entity))
1272 EntityDie = getOrCreateNameSpace(NS);
1273 else if (auto *M = dyn_cast<DIModule>(Entity))
1274 EntityDie = getOrCreateModule(M);
1275 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1276 EntityDie = getOrCreateSubprogramDIE(SP);
1277 else if (auto *T = dyn_cast<DIType>(Entity))
1278 EntityDie = getOrCreateTypeDIE(T);
1279 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1280 EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1281 else
1282 EntityDie = getDIE(Entity);
1283 assert(EntityDie);
1284 addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1285 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1286 StringRef Name = Module->getName();
1287 if (!Name.empty())
1288 addString(*IMDie, dwarf::DW_AT_name, Name);
1290 // This is for imported module with renamed entities (such as variables and
1291 // subprograms).
1292 DINodeArray Elements = Module->getElements();
1293 for (const auto *Element : Elements) {
1294 if (!Element)
1295 continue;
1296 IMDie->addChild(
1297 constructImportedEntityDIE(cast<DIImportedEntity>(Element)));
1300 return IMDie;
1303 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1304 DIE *D = getDIE(SP);
1305 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1306 if (D)
1307 // If this subprogram has an abstract definition, reference that
1308 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1309 } else {
1310 assert(D || includeMinimalInlineScopes());
1311 if (D)
1312 // And attach the attributes
1313 applySubprogramAttributesToDefinition(SP, *D);
1317 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1318 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1320 auto *Die = Entity->getDIE();
1321 /// Label may be used to generate DW_AT_low_pc, so put it outside
1322 /// if/else block.
1323 const DbgLabel *Label = nullptr;
1324 if (AbsEntity && AbsEntity->getDIE()) {
1325 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1326 Label = dyn_cast<const DbgLabel>(Entity);
1327 } else {
1328 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1329 applyVariableAttributes(*Var, *Die);
1330 else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1331 applyLabelAttributes(*Label, *Die);
1332 else
1333 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1336 if (Label)
1337 if (const auto *Sym = Label->getSymbol())
1338 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1341 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1342 auto &AbstractEntities = getAbstractEntities();
1343 auto I = AbstractEntities.find(Node);
1344 if (I != AbstractEntities.end())
1345 return I->second.get();
1346 return nullptr;
1349 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1350 LexicalScope *Scope) {
1351 assert(Scope && Scope->isAbstractScope());
1352 auto &Entity = getAbstractEntities()[Node];
1353 if (isa<const DILocalVariable>(Node)) {
1354 Entity = std::make_unique<DbgVariable>(
1355 cast<const DILocalVariable>(Node), nullptr /* IA */);;
1356 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1357 } else if (isa<const DILabel>(Node)) {
1358 Entity = std::make_unique<DbgLabel>(
1359 cast<const DILabel>(Node), nullptr /* IA */);
1360 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1364 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1365 // Don't bother labeling the .dwo unit, as its offset isn't used.
1366 if (!Skeleton && !DD->useSectionsAsReferences()) {
1367 LabelBegin = Asm->createTempSymbol("cu_begin");
1368 Asm->OutStreamer->emitLabel(LabelBegin);
1371 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1372 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1373 : dwarf::DW_UT_compile;
1374 DwarfUnit::emitCommonHeader(UseOffsets, UT);
1375 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1376 Asm->emitInt64(getDWOId());
1379 bool DwarfCompileUnit::hasDwarfPubSections() const {
1380 switch (CUNode->getNameTableKind()) {
1381 case DICompileUnit::DebugNameTableKind::None:
1382 return false;
1383 // Opting in to GNU Pubnames/types overrides the default to ensure these are
1384 // generated for things like Gold's gdb_index generation.
1385 case DICompileUnit::DebugNameTableKind::GNU:
1386 return true;
1387 case DICompileUnit::DebugNameTableKind::Default:
1388 return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1389 !CUNode->isDebugDirectivesOnly() &&
1390 DD->getAccelTableKind() != AccelTableKind::Apple &&
1391 DD->getDwarfVersion() < 5;
1393 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1396 /// addGlobalName - Add a new global name to the compile unit.
1397 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1398 const DIScope *Context) {
1399 if (!hasDwarfPubSections())
1400 return;
1401 std::string FullName = getParentContextString(Context) + Name.str();
1402 GlobalNames[FullName] = &Die;
1405 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1406 const DIScope *Context) {
1407 if (!hasDwarfPubSections())
1408 return;
1409 std::string FullName = getParentContextString(Context) + Name.str();
1410 // Insert, allowing the entry to remain as-is if it's already present
1411 // This way the CU-level type DIE is preferred over the "can't describe this
1412 // type as a unit offset because it's not really in the CU at all, it's only
1413 // in a type unit"
1414 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1417 /// Add a new global type to the unit.
1418 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1419 const DIScope *Context) {
1420 if (!hasDwarfPubSections())
1421 return;
1422 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1423 GlobalTypes[FullName] = &Die;
1426 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1427 const DIScope *Context) {
1428 if (!hasDwarfPubSections())
1429 return;
1430 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1431 // Insert, allowing the entry to remain as-is if it's already present
1432 // This way the CU-level type DIE is preferred over the "can't describe this
1433 // type as a unit offset because it's not really in the CU at all, it's only
1434 // in a type unit"
1435 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1438 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1439 MachineLocation Location) {
1440 if (DV.hasComplexAddress())
1441 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1442 else
1443 addAddress(Die, dwarf::DW_AT_location, Location);
1446 /// Add an address attribute to a die based on the location provided.
1447 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1448 const MachineLocation &Location) {
1449 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1450 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1451 if (Location.isIndirect())
1452 DwarfExpr.setMemoryLocationKind();
1454 DIExpressionCursor Cursor({});
1455 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1456 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1457 return;
1458 DwarfExpr.addExpression(std::move(Cursor));
1460 // Now attach the location information to the DIE.
1461 addBlock(Die, Attribute, DwarfExpr.finalize());
1463 if (DwarfExpr.TagOffset)
1464 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1465 *DwarfExpr.TagOffset);
1468 /// Start with the address based on the location provided, and generate the
1469 /// DWARF information necessary to find the actual variable given the extra
1470 /// address information encoded in the DbgVariable, starting from the starting
1471 /// location. Add the DWARF information to the die.
1472 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1473 dwarf::Attribute Attribute,
1474 const MachineLocation &Location) {
1475 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1476 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1477 const DIExpression *DIExpr = DV.getSingleExpression();
1478 DwarfExpr.addFragmentOffset(DIExpr);
1479 DwarfExpr.setLocation(Location, DIExpr);
1481 DIExpressionCursor Cursor(DIExpr);
1483 if (DIExpr->isEntryValue())
1484 DwarfExpr.beginEntryValueExpression(Cursor);
1486 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1487 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1488 return;
1489 DwarfExpr.addExpression(std::move(Cursor));
1491 // Now attach the location information to the DIE.
1492 addBlock(Die, Attribute, DwarfExpr.finalize());
1494 if (DwarfExpr.TagOffset)
1495 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1496 *DwarfExpr.TagOffset);
1499 /// Add a Dwarf loclistptr attribute data and value.
1500 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1501 unsigned Index) {
1502 dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1503 ? dwarf::DW_FORM_loclistx
1504 : DD->getDwarfSectionOffsetForm();
1505 addAttribute(Die, Attribute, Form, DIELocList(Index));
1508 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1509 DIE &VariableDie) {
1510 StringRef Name = Var.getName();
1511 if (!Name.empty())
1512 addString(VariableDie, dwarf::DW_AT_name, Name);
1513 const auto *DIVar = Var.getVariable();
1514 if (DIVar) {
1515 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1516 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1517 AlignInBytes);
1518 addAnnotation(VariableDie, DIVar->getAnnotations());
1521 addSourceLine(VariableDie, DIVar);
1522 addType(VariableDie, Var.getType());
1523 if (Var.isArtificial())
1524 addFlag(VariableDie, dwarf::DW_AT_artificial);
1527 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1528 DIE &LabelDie) {
1529 StringRef Name = Label.getName();
1530 if (!Name.empty())
1531 addString(LabelDie, dwarf::DW_AT_name, Name);
1532 const auto *DILabel = Label.getLabel();
1533 addSourceLine(LabelDie, DILabel);
1536 /// Add a Dwarf expression attribute data and value.
1537 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1538 const MCExpr *Expr) {
1539 addAttribute(Die, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1542 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1543 const DISubprogram *SP, DIE &SPDie) {
1544 auto *SPDecl = SP->getDeclaration();
1545 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1546 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1547 addGlobalName(SP->getName(), SPDie, Context);
1550 bool DwarfCompileUnit::isDwoUnit() const {
1551 return DD->useSplitDwarf() && Skeleton;
1554 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1555 constructTypeDIE(D, CTy);
1558 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1559 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1560 (DD->useSplitDwarf() && !Skeleton);
1563 void DwarfCompileUnit::addAddrTableBase() {
1564 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1565 MCSymbol *Label = DD->getAddressPool().getLabel();
1566 addSectionLabel(getUnitDie(),
1567 DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1568 : dwarf::DW_AT_GNU_addr_base,
1569 Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1572 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1573 addAttribute(Die, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1574 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1577 void DwarfCompileUnit::createBaseTypeDIEs() {
1578 // Insert the base_type DIEs directly after the CU so that their offsets will
1579 // fit in the fixed size ULEB128 used inside the location expressions.
1580 // Maintain order by iterating backwards and inserting to the front of CU
1581 // child list.
1582 for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1583 DIE &Die = getUnitDie().addChildFront(
1584 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1585 SmallString<32> Str;
1586 addString(Die, dwarf::DW_AT_name,
1587 Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1588 "_" + Twine(Btr.BitSize)).toStringRef(Str));
1589 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1590 // Round up to smallest number of bytes that contains this number of bits.
1591 addUInt(Die, dwarf::DW_AT_byte_size, None, divideCeil(Btr.BitSize, 8));
1593 Btr.Die = &Die;