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