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