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