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