1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for constructing a dwarf compile unit. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "DwarfCompileUnit.h" 15 #include "AddressPool.h" 16 #include "DwarfDebug.h" 17 #include "DwarfExpression.h" 18 #include "DwarfUnit.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/BinaryFormat/Dwarf.h" 24 #include "llvm/CodeGen/AsmPrinter.h" 25 #include "llvm/CodeGen/DIE.h" 26 #include "llvm/CodeGen/LexicalScopes.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineInstr.h" 29 #include "llvm/CodeGen/MachineOperand.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/DebugInfoMetadata.h" 33 #include "llvm/IR/GlobalVariable.h" 34 #include "llvm/MC/MachineLocation.h" 35 #include "llvm/MC/MCSection.h" 36 #include "llvm/MC/MCStreamer.h" 37 #include "llvm/MC/MCSymbol.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Target/TargetFrameLowering.h" 40 #include "llvm/Target/TargetLoweringObjectFile.h" 41 #include "llvm/Target/TargetMachine.h" 42 #include "llvm/Target/TargetOptions.h" 43 #include "llvm/Target/TargetRegisterInfo.h" 44 #include "llvm/Target/TargetSubtargetInfo.h" 45 #include <algorithm> 46 #include <cassert> 47 #include <cstdint> 48 #include <iterator> 49 #include <memory> 50 #include <string> 51 #include <utility> 52 53 using namespace llvm; 54 55 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, 56 AsmPrinter *A, DwarfDebug *DW, 57 DwarfFile *DWU) 58 : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID) { 59 insertDIE(Node, &getUnitDie()); 60 MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin"); 61 } 62 63 /// addLabelAddress - Add a dwarf label attribute data and value using 64 /// DW_FORM_addr or DW_FORM_GNU_addr_index. 65 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute, 66 const MCSymbol *Label) { 67 // Don't use the address pool in non-fission or in the skeleton unit itself. 68 // FIXME: Once GDB supports this, it's probably worthwhile using the address 69 // pool from the skeleton - maybe even in non-fission (possibly fewer 70 // relocations by sharing them in the pool, but we have other ideas about how 71 // to reduce the number of relocations as well/instead). 72 if (!DD->useSplitDwarf() || !Skeleton) 73 return addLocalLabelAddress(Die, Attribute, Label); 74 75 if (Label) 76 DD->addArangeLabel(SymbolCU(this, Label)); 77 78 unsigned idx = DD->getAddressPool().getIndex(Label); 79 Die.addValue(DIEValueAllocator, Attribute, 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(StringRef FileName, 98 StringRef DirName) { 99 // If we print assembly, we can't separate .file entries according to 100 // compile units. Thus all files will belong to the default compile unit. 101 102 // FIXME: add a better feature test than hasRawTextSupport. Even better, 103 // extend .file to support this. 104 return Asm->OutStreamer->EmitDwarfFileDirective( 105 0, DirName, FileName, 106 Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID()); 107 } 108 109 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE( 110 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) { 111 // Check for pre-existence. 112 if (DIE *Die = getDIE(GV)) 113 return Die; 114 115 assert(GV); 116 117 auto *GVContext = GV->getScope(); 118 auto *GTy = DD->resolve(GV->getType()); 119 120 // Construct the context before querying for the existence of the DIE in 121 // case such construction creates the DIE. 122 DIE *ContextDIE = getOrCreateContextDIE(GVContext); 123 124 // Add to map. 125 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV); 126 DIScope *DeclContext; 127 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) { 128 DeclContext = resolve(SDMDecl->getScope()); 129 assert(SDMDecl->isStaticMember() && "Expected static member decl"); 130 assert(GV->isDefinition()); 131 // We need the declaration DIE that is in the static member's class. 132 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl); 133 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE); 134 // If the global variable's type is different from the one in the class 135 // member type, assume that it's more specific and also emit it. 136 if (GTy != DD->resolve(SDMDecl->getBaseType())) 137 addType(*VariableDIE, GTy); 138 } else { 139 DeclContext = GV->getScope(); 140 // Add name and type. 141 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName()); 142 addType(*VariableDIE, GTy); 143 144 // Add scoping info. 145 if (!GV->isLocalToUnit()) 146 addFlag(*VariableDIE, dwarf::DW_AT_external); 147 148 // Add line number info. 149 addSourceLine(*VariableDIE, GV); 150 } 151 152 if (!GV->isDefinition()) 153 addFlag(*VariableDIE, dwarf::DW_AT_declaration); 154 else 155 addGlobalName(GV->getName(), *VariableDIE, DeclContext); 156 157 if (uint32_t AlignInBytes = GV->getAlignInBytes()) 158 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 159 AlignInBytes); 160 161 // Add location. 162 bool addToAccelTable = false; 163 DIELoc *Loc = nullptr; 164 std::unique_ptr<DIEDwarfExpression> DwarfExpr; 165 for (const auto &GE : GlobalExprs) { 166 const GlobalVariable *Global = GE.Var; 167 const DIExpression *Expr = GE.Expr; 168 169 // For compatibility with DWARF 3 and earlier, 170 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes 171 // DW_AT_const_value(X). 172 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) { 173 addToAccelTable = true; 174 addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1)); 175 break; 176 } 177 178 // We cannot describe the location of dllimport'd variables: the 179 // computation of their address requires loads from the IAT. 180 if (Global && Global->hasDLLImportStorageClass()) 181 continue; 182 183 // Nothing to describe without address or constant. 184 if (!Global && (!Expr || !Expr->isConstant())) 185 continue; 186 187 if (!Loc) { 188 addToAccelTable = true; 189 Loc = new (DIEValueAllocator) DIELoc; 190 DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc); 191 } 192 193 if (Global) { 194 const MCSymbol *Sym = Asm->getSymbol(Global); 195 if (Global->isThreadLocal()) { 196 if (Asm->TM.Options.EmulatedTLS) { 197 // TODO: add debug info for emulated thread local mode. 198 } else { 199 // FIXME: Make this work with -gsplit-dwarf. 200 unsigned PointerSize = Asm->getDataLayout().getPointerSize(); 201 assert((PointerSize == 4 || PointerSize == 8) && 202 "Add support for other sizes if necessary"); 203 // Based on GCC's support for TLS: 204 if (!DD->useSplitDwarf()) { 205 // 1) Start with a constNu of the appropriate pointer size 206 addUInt(*Loc, dwarf::DW_FORM_data1, 207 PointerSize == 4 ? dwarf::DW_OP_const4u 208 : dwarf::DW_OP_const8u); 209 // 2) containing the (relocated) offset of the TLS variable 210 // within the module's TLS block. 211 addExpr(*Loc, dwarf::DW_FORM_udata, 212 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym)); 213 } else { 214 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index); 215 addUInt(*Loc, dwarf::DW_FORM_udata, 216 DD->getAddressPool().getIndex(Sym, /* TLS */ true)); 217 } 218 // 3) followed by an OP to make the debugger do a TLS lookup. 219 addUInt(*Loc, dwarf::DW_FORM_data1, 220 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address 221 : dwarf::DW_OP_form_tls_address); 222 } 223 } else { 224 DD->addArangeLabel(SymbolCU(this, Sym)); 225 addOpAddress(*Loc, Sym); 226 } 227 } 228 if (Expr) { 229 DwarfExpr->addFragmentOffset(Expr); 230 DwarfExpr->addExpression(Expr); 231 } 232 } 233 if (Loc) 234 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize()); 235 236 if (DD->useAllLinkageNames()) 237 addLinkageName(*VariableDIE, GV->getLinkageName()); 238 239 if (addToAccelTable) { 240 DD->addAccelName(GV->getName(), *VariableDIE); 241 242 // If the linkage name is different than the name, go ahead and output 243 // that as well into the name table. 244 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName()) 245 DD->addAccelName(GV->getLinkageName(), *VariableDIE); 246 } 247 248 return VariableDIE; 249 } 250 251 void DwarfCompileUnit::addRange(RangeSpan Range) { 252 bool SameAsPrevCU = this == DD->getPrevCU(); 253 DD->setPrevCU(this); 254 // If we have no current ranges just add the range and return, otherwise, 255 // check the current section and CU against the previous section and CU we 256 // emitted into and the subprogram was contained within. If these are the 257 // same then extend our current range, otherwise add this as a new range. 258 if (CURanges.empty() || !SameAsPrevCU || 259 (&CURanges.back().getEnd()->getSection() != 260 &Range.getEnd()->getSection())) { 261 CURanges.push_back(Range); 262 return; 263 } 264 265 CURanges.back().setEnd(Range.getEnd()); 266 } 267 268 void DwarfCompileUnit::initStmtList() { 269 // Define start line table label for each Compile Unit. 270 MCSymbol *LineTableStartSym = 271 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID()); 272 273 // DW_AT_stmt_list is a offset of line number information for this 274 // compile unit in debug_line section. For split dwarf this is 275 // left in the skeleton CU and so not included. 276 // The line table entries are not always emitted in assembly, so it 277 // is not okay to use line_table_start here. 278 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 279 StmtListValue = 280 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym, 281 TLOF.getDwarfLineSection()->getBeginSymbol()); 282 } 283 284 void DwarfCompileUnit::applyStmtList(DIE &D) { 285 D.addValue(DIEValueAllocator, *StmtListValue); 286 } 287 288 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin, 289 const MCSymbol *End) { 290 assert(Begin && "Begin label should not be null!"); 291 assert(End && "End label should not be null!"); 292 assert(Begin->isDefined() && "Invalid starting label"); 293 assert(End->isDefined() && "Invalid end label"); 294 295 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin); 296 if (DD->getDwarfVersion() < 4) 297 addLabelAddress(D, dwarf::DW_AT_high_pc, End); 298 else 299 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin); 300 } 301 302 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc 303 // and DW_AT_high_pc attributes. If there are global variables in this 304 // scope then create and insert DIEs for these variables. 305 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) { 306 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes()); 307 308 attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd()); 309 if (DD->useAppleExtensionAttributes() && 310 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim( 311 *DD->getCurrentFunction())) 312 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr); 313 314 // Only include DW_AT_frame_base in full debug info 315 if (!includeMinimalInlineScopes()) { 316 const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo(); 317 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 318 if (RI->isPhysicalRegister(Location.getReg())) 319 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location); 320 } 321 322 // Add name to the name table, we do this here because we're guaranteed 323 // to have concrete versions of our DW_TAG_subprogram nodes. 324 DD->addSubprogramNames(SP, *SPDie); 325 326 return *SPDie; 327 } 328 329 // Construct a DIE for this scope. 330 void DwarfCompileUnit::constructScopeDIE( 331 LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) { 332 if (!Scope || !Scope->getScopeNode()) 333 return; 334 335 auto *DS = Scope->getScopeNode(); 336 337 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && 338 "Only handle inlined subprograms here, use " 339 "constructSubprogramScopeDIE for non-inlined " 340 "subprograms"); 341 342 SmallVector<DIE *, 8> Children; 343 344 // We try to create the scope DIE first, then the children DIEs. This will 345 // avoid creating un-used children then removing them later when we find out 346 // the scope DIE is null. 347 DIE *ScopeDIE; 348 if (Scope->getParent() && isa<DISubprogram>(DS)) { 349 ScopeDIE = constructInlinedScopeDIE(Scope); 350 if (!ScopeDIE) 351 return; 352 // We create children when the scope DIE is not null. 353 createScopeChildrenDIE(Scope, Children); 354 } else { 355 // Early exit when we know the scope DIE is going to be null. 356 if (DD->isLexicalScopeDIENull(Scope)) 357 return; 358 359 bool HasNonScopeChildren = false; 360 361 // We create children here when we know the scope DIE is not going to be 362 // null and the children will be added to the scope DIE. 363 createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren); 364 365 // If there are only other scopes as children, put them directly in the 366 // parent instead, as this scope would serve no purpose. 367 if (!HasNonScopeChildren) { 368 FinalChildren.insert(FinalChildren.end(), 369 std::make_move_iterator(Children.begin()), 370 std::make_move_iterator(Children.end())); 371 return; 372 } 373 ScopeDIE = constructLexicalScopeDIE(Scope); 374 assert(ScopeDIE && "Scope DIE should not be null."); 375 } 376 377 // Add children 378 for (auto &I : Children) 379 ScopeDIE->addChild(std::move(I)); 380 381 FinalChildren.push_back(std::move(ScopeDIE)); 382 } 383 384 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE, 385 SmallVector<RangeSpan, 2> Range) { 386 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 387 388 // Emit offset in .debug_range as a relocatable label. emitDIE will handle 389 // emitting it appropriately. 390 const MCSymbol *RangeSectionSym = 391 TLOF.getDwarfRangesSection()->getBeginSymbol(); 392 393 RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range)); 394 395 // Under fission, ranges are specified by constant offsets relative to the 396 // CU's DW_AT_GNU_ranges_base. 397 if (isDwoUnit()) 398 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 399 RangeSectionSym); 400 else 401 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 402 RangeSectionSym); 403 404 // Add the range list to the set of ranges to be emitted. 405 (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List)); 406 } 407 408 void DwarfCompileUnit::attachRangesOrLowHighPC( 409 DIE &Die, SmallVector<RangeSpan, 2> Ranges) { 410 if (Ranges.size() == 1) { 411 const auto &single = Ranges.front(); 412 attachLowHighPC(Die, single.getStart(), single.getEnd()); 413 } else 414 addScopeRangeList(Die, std::move(Ranges)); 415 } 416 417 void DwarfCompileUnit::attachRangesOrLowHighPC( 418 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) { 419 SmallVector<RangeSpan, 2> List; 420 List.reserve(Ranges.size()); 421 for (const InsnRange &R : Ranges) 422 List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first), 423 DD->getLabelAfterInsn(R.second))); 424 attachRangesOrLowHighPC(Die, std::move(List)); 425 } 426 427 // This scope represents inlined body of a function. Construct DIE to 428 // represent this concrete inlined copy of the function. 429 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) { 430 assert(Scope->getScopeNode()); 431 auto *DS = Scope->getScopeNode(); 432 auto *InlinedSP = getDISubprogram(DS); 433 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 434 // was inlined from another compile unit. 435 DIE *OriginDIE = getAbstractSPDies()[InlinedSP]; 436 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram."); 437 438 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine); 439 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE); 440 441 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 442 443 // Add the call site information to the DIE. 444 const DILocation *IA = Scope->getInlinedAt(); 445 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None, 446 getOrCreateSourceID(IA->getFilename(), IA->getDirectory())); 447 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine()); 448 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4) 449 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None, 450 IA->getDiscriminator()); 451 452 // Add name to the name table, we do this here because we're guaranteed 453 // to have concrete versions of our DW_TAG_inlined_subprogram nodes. 454 DD->addSubprogramNames(InlinedSP, *ScopeDIE); 455 456 return ScopeDIE; 457 } 458 459 // Construct new DW_TAG_lexical_block for this scope and attach 460 // DW_AT_low_pc/DW_AT_high_pc labels. 461 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) { 462 if (DD->isLexicalScopeDIENull(Scope)) 463 return nullptr; 464 465 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block); 466 if (Scope->isAbstractScope()) 467 return ScopeDIE; 468 469 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 470 471 return ScopeDIE; 472 } 473 474 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 475 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) { 476 auto D = constructVariableDIEImpl(DV, Abstract); 477 DV.setDIE(*D); 478 return D; 479 } 480 481 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV, 482 bool Abstract) { 483 // Define variable debug information entry. 484 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag()); 485 486 if (Abstract) { 487 applyVariableAttributes(DV, *VariableDie); 488 return VariableDie; 489 } 490 491 // Add variable address. 492 493 unsigned Offset = DV.getDebugLocListIndex(); 494 if (Offset != ~0U) { 495 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset); 496 return VariableDie; 497 } 498 499 // Check if variable is described by a DBG_VALUE instruction. 500 if (const MachineInstr *DVInsn = DV.getMInsn()) { 501 assert(DVInsn->getNumOperands() == 4); 502 if (DVInsn->getOperand(0).isReg()) { 503 auto RegOp = DVInsn->getOperand(0); 504 auto Op1 = DVInsn->getOperand(1); 505 // If the second operand is an immediate, this is an indirect value. 506 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 507 MachineLocation Location(RegOp.getReg(), Op1.isImm()); 508 addVariableAddress(DV, *VariableDie, Location); 509 } else if (DVInsn->getOperand(0).isImm()) { 510 // This variable is described by a single constant. 511 // Check whether it has a DIExpression. 512 auto *Expr = DV.getSingleExpression(); 513 if (Expr && Expr->getNumElements()) { 514 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 515 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 516 // If there is an expression, emit raw unsigned bytes. 517 DwarfExpr.addFragmentOffset(Expr); 518 DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm()); 519 DwarfExpr.addExpression(Expr); 520 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 521 } else 522 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType()); 523 } else if (DVInsn->getOperand(0).isFPImm()) 524 addConstantFPValue(*VariableDie, DVInsn->getOperand(0)); 525 else if (DVInsn->getOperand(0).isCImm()) 526 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(), 527 DV.getType()); 528 529 return VariableDie; 530 } 531 532 // .. else use frame index. 533 if (!DV.hasFrameIndexExprs()) 534 return VariableDie; 535 536 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 537 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 538 for (auto &Fragment : DV.getFrameIndexExprs()) { 539 unsigned FrameReg = 0; 540 const DIExpression *Expr = Fragment.Expr; 541 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering(); 542 int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg); 543 DwarfExpr.addFragmentOffset(Expr); 544 SmallVector<uint64_t, 8> Ops; 545 Ops.push_back(dwarf::DW_OP_plus_uconst); 546 Ops.push_back(Offset); 547 Ops.append(Expr->elements_begin(), Expr->elements_end()); 548 DIExpressionCursor Cursor(Ops); 549 DwarfExpr.setMemoryLocationKind(); 550 DwarfExpr.addMachineRegExpression( 551 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg); 552 DwarfExpr.addExpression(std::move(Cursor)); 553 } 554 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 555 556 return VariableDie; 557 } 558 559 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, 560 const LexicalScope &Scope, 561 DIE *&ObjectPointer) { 562 auto Var = constructVariableDIE(DV, Scope.isAbstractScope()); 563 if (DV.isObjectPointer()) 564 ObjectPointer = Var; 565 return Var; 566 } 567 568 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope, 569 SmallVectorImpl<DIE *> &Children, 570 bool *HasNonScopeChildren) { 571 assert(Children.empty()); 572 DIE *ObjectPointer = nullptr; 573 574 for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope)) 575 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer)); 576 577 // Skip imported directives in gmlt-like data. 578 if (!includeMinimalInlineScopes()) { 579 // There is no need to emit empty lexical block DIE. 580 for (const auto *IE : ImportedEntities[Scope->getScopeNode()]) 581 Children.push_back( 582 constructImportedEntityDIE(cast<DIImportedEntity>(IE))); 583 } 584 585 if (HasNonScopeChildren) 586 *HasNonScopeChildren = !Children.empty(); 587 588 for (LexicalScope *LS : Scope->getChildren()) 589 constructScopeDIE(LS, Children); 590 591 return ObjectPointer; 592 } 593 594 void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) { 595 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub); 596 597 if (Scope) { 598 assert(!Scope->getInlinedAt()); 599 assert(!Scope->isAbstractScope()); 600 // Collect lexical scope children first. 601 // ObjectPointer might be a local (non-argument) local variable if it's a 602 // block's synthetic this pointer. 603 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE)) 604 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer); 605 } 606 607 // If this is a variadic function, add an unspecified parameter. 608 DITypeRefArray FnArgs = Sub->getType()->getTypeArray(); 609 610 // If we have a single element of null, it is a function that returns void. 611 // If we have more than one elements and the last one is null, it is a 612 // variadic function. 613 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] && 614 !includeMinimalInlineScopes()) 615 ScopeDIE.addChild( 616 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters)); 617 } 618 619 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, 620 DIE &ScopeDIE) { 621 // We create children when the scope DIE is not null. 622 SmallVector<DIE *, 8> Children; 623 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children); 624 625 // Add children 626 for (auto &I : Children) 627 ScopeDIE.addChild(std::move(I)); 628 629 return ObjectPointer; 630 } 631 632 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE( 633 LexicalScope *Scope) { 634 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()]; 635 if (AbsDef) 636 return; 637 638 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 639 640 DIE *ContextDIE; 641 642 if (includeMinimalInlineScopes()) 643 ContextDIE = &getUnitDie(); 644 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with 645 // the important distinction that the debug node is not associated with the 646 // DIE (since the debug node will be associated with the concrete DIE, if 647 // any). It could be refactored to some common utility function. 648 else if (auto *SPDecl = SP->getDeclaration()) { 649 ContextDIE = &getUnitDie(); 650 getOrCreateSubprogramDIE(SPDecl); 651 } else 652 ContextDIE = getOrCreateContextDIE(resolve(SP->getScope())); 653 654 // Passing null as the associated node because the abstract definition 655 // shouldn't be found by lookup. 656 AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr); 657 applySubprogramAttributesToDefinition(SP, *AbsDef); 658 659 if (!includeMinimalInlineScopes()) 660 addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 661 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef)) 662 addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer); 663 } 664 665 DIE *DwarfCompileUnit::constructImportedEntityDIE( 666 const DIImportedEntity *Module) { 667 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag()); 668 insertDIE(Module, IMDie); 669 DIE *EntityDie; 670 auto *Entity = resolve(Module->getEntity()); 671 if (auto *NS = dyn_cast<DINamespace>(Entity)) 672 EntityDie = getOrCreateNameSpace(NS); 673 else if (auto *M = dyn_cast<DIModule>(Entity)) 674 EntityDie = getOrCreateModule(M); 675 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 676 EntityDie = getOrCreateSubprogramDIE(SP); 677 else if (auto *T = dyn_cast<DIType>(Entity)) 678 EntityDie = getOrCreateTypeDIE(T); 679 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity)) 680 EntityDie = getOrCreateGlobalVariableDIE(GV, {}); 681 else 682 EntityDie = getDIE(Entity); 683 assert(EntityDie); 684 auto *File = Module->getFile(); 685 addSourceLine(*IMDie, Module->getLine(), File ? File->getFilename() : "", 686 File ? File->getDirectory() : ""); 687 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie); 688 StringRef Name = Module->getName(); 689 if (!Name.empty()) 690 addString(*IMDie, dwarf::DW_AT_name, Name); 691 692 return IMDie; 693 } 694 695 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { 696 DIE *D = getDIE(SP); 697 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) { 698 if (D) 699 // If this subprogram has an abstract definition, reference that 700 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); 701 } else { 702 assert(D || includeMinimalInlineScopes()); 703 if (D) 704 // And attach the attributes 705 applySubprogramAttributesToDefinition(SP, *D); 706 } 707 } 708 709 void DwarfCompileUnit::finishVariableDefinition(const DbgVariable &Var) { 710 DbgVariable *AbsVar = getExistingAbstractVariable( 711 InlinedVariable(Var.getVariable(), Var.getInlinedAt())); 712 auto *VariableDie = Var.getDIE(); 713 if (AbsVar && AbsVar->getDIE()) { 714 addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin, 715 *AbsVar->getDIE()); 716 } else 717 applyVariableAttributes(Var, *VariableDie); 718 } 719 720 DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(InlinedVariable IV) { 721 const DILocalVariable *Cleansed; 722 return getExistingAbstractVariable(IV, Cleansed); 723 } 724 725 // Find abstract variable, if any, associated with Var. 726 DbgVariable *DwarfCompileUnit::getExistingAbstractVariable( 727 InlinedVariable IV, const DILocalVariable *&Cleansed) { 728 // More then one inlined variable corresponds to one abstract variable. 729 Cleansed = IV.first; 730 auto &AbstractVariables = getAbstractVariables(); 731 auto I = AbstractVariables.find(Cleansed); 732 if (I != AbstractVariables.end()) 733 return I->second.get(); 734 return nullptr; 735 } 736 737 void DwarfCompileUnit::createAbstractVariable(const DILocalVariable *Var, 738 LexicalScope *Scope) { 739 assert(Scope && Scope->isAbstractScope()); 740 auto AbsDbgVariable = llvm::make_unique<DbgVariable>(Var, /* IA */ nullptr); 741 DU->addScopeVariable(Scope, AbsDbgVariable.get()); 742 getAbstractVariables()[Var] = std::move(AbsDbgVariable); 743 } 744 745 void DwarfCompileUnit::emitHeader(bool UseOffsets) { 746 // Don't bother labeling the .dwo unit, as its offset isn't used. 747 if (!Skeleton) { 748 LabelBegin = Asm->createTempSymbol("cu_begin"); 749 Asm->OutStreamer->EmitLabel(LabelBegin); 750 } 751 752 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile 753 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton 754 : dwarf::DW_UT_compile; 755 DwarfUnit::emitCommonHeader(UseOffsets, UT); 756 } 757 758 bool DwarfCompileUnit::hasDwarfPubSections() const { 759 // Opting in to GNU Pubnames/types overrides the default to ensure these are 760 // generated for things like Gold's gdb_index generation. 761 if (CUNode->getGnuPubnames()) 762 return true; 763 764 return DD->tuneForGDB() && !includeMinimalInlineScopes(); 765 } 766 767 /// addGlobalName - Add a new global name to the compile unit. 768 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die, 769 const DIScope *Context) { 770 if (!hasDwarfPubSections()) 771 return; 772 std::string FullName = getParentContextString(Context) + Name.str(); 773 GlobalNames[FullName] = &Die; 774 } 775 776 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name, 777 const DIScope *Context) { 778 if (!hasDwarfPubSections()) 779 return; 780 std::string FullName = getParentContextString(Context) + Name.str(); 781 // Insert, allowing the entry to remain as-is if it's already present 782 // This way the CU-level type DIE is preferred over the "can't describe this 783 // type as a unit offset because it's not really in the CU at all, it's only 784 // in a type unit" 785 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie())); 786 } 787 788 /// Add a new global type to the unit. 789 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die, 790 const DIScope *Context) { 791 if (!hasDwarfPubSections()) 792 return; 793 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 794 GlobalTypes[FullName] = &Die; 795 } 796 797 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty, 798 const DIScope *Context) { 799 if (!hasDwarfPubSections()) 800 return; 801 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 802 // Insert, allowing the entry to remain as-is if it's already present 803 // This way the CU-level type DIE is preferred over the "can't describe this 804 // type as a unit offset because it's not really in the CU at all, it's only 805 // in a type unit" 806 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie())); 807 } 808 809 /// addVariableAddress - Add DW_AT_location attribute for a 810 /// DbgVariable based on provided MachineLocation. 811 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die, 812 MachineLocation Location) { 813 // addBlockByrefAddress is obsolete and will be removed soon. 814 // The clang frontend always generates block byref variables with a 815 // complex expression that encodes exactly what addBlockByrefAddress 816 // would do. 817 assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) && 818 "block byref variable without a complex expression"); 819 if (DV.hasComplexAddress()) 820 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 821 else if (DV.isBlockByrefVariable()) 822 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location); 823 else 824 addAddress(Die, dwarf::DW_AT_location, Location); 825 } 826 827 /// Add an address attribute to a die based on the location provided. 828 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute, 829 const MachineLocation &Location) { 830 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 831 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 832 if (Location.isIndirect()) 833 DwarfExpr.setMemoryLocationKind(); 834 835 DIExpressionCursor Cursor({}); 836 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 837 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 838 return; 839 DwarfExpr.addExpression(std::move(Cursor)); 840 841 // Now attach the location information to the DIE. 842 addBlock(Die, Attribute, DwarfExpr.finalize()); 843 } 844 845 /// Start with the address based on the location provided, and generate the 846 /// DWARF information necessary to find the actual variable given the extra 847 /// address information encoded in the DbgVariable, starting from the starting 848 /// location. Add the DWARF information to the die. 849 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die, 850 dwarf::Attribute Attribute, 851 const MachineLocation &Location) { 852 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 853 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 854 const DIExpression *DIExpr = DV.getSingleExpression(); 855 DwarfExpr.addFragmentOffset(DIExpr); 856 if (Location.isIndirect()) 857 DwarfExpr.setMemoryLocationKind(); 858 859 DIExpressionCursor Cursor(DIExpr); 860 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 861 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 862 return; 863 DwarfExpr.addExpression(std::move(Cursor)); 864 865 // Now attach the location information to the DIE. 866 addBlock(Die, Attribute, DwarfExpr.finalize()); 867 } 868 869 /// Add a Dwarf loclistptr attribute data and value. 870 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute, 871 unsigned Index) { 872 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 873 : dwarf::DW_FORM_data4; 874 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index)); 875 } 876 877 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var, 878 DIE &VariableDie) { 879 StringRef Name = Var.getName(); 880 if (!Name.empty()) 881 addString(VariableDie, dwarf::DW_AT_name, Name); 882 const auto *DIVar = Var.getVariable(); 883 if (DIVar) 884 if (uint32_t AlignInBytes = DIVar->getAlignInBytes()) 885 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 886 AlignInBytes); 887 888 addSourceLine(VariableDie, DIVar); 889 addType(VariableDie, Var.getType()); 890 if (Var.isArtificial()) 891 addFlag(VariableDie, dwarf::DW_AT_artificial); 892 } 893 894 /// Add a Dwarf expression attribute data and value. 895 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form, 896 const MCExpr *Expr) { 897 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr)); 898 } 899 900 void DwarfCompileUnit::applySubprogramAttributesToDefinition( 901 const DISubprogram *SP, DIE &SPDie) { 902 auto *SPDecl = SP->getDeclaration(); 903 auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope()); 904 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes()); 905 addGlobalName(SP->getName(), SPDie, Context); 906 } 907 908 bool DwarfCompileUnit::isDwoUnit() const { 909 return DD->useSplitDwarf() && Skeleton; 910 } 911 912 bool DwarfCompileUnit::includeMinimalInlineScopes() const { 913 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly || 914 (DD->useSplitDwarf() && !Skeleton); 915 } 916