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