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