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