1 #include "DwarfCompileUnit.h" 2 #include "DwarfExpression.h" 3 #include "llvm/CodeGen/MachineFunction.h" 4 #include "llvm/IR/Constants.h" 5 #include "llvm/IR/DataLayout.h" 6 #include "llvm/IR/GlobalValue.h" 7 #include "llvm/IR/GlobalVariable.h" 8 #include "llvm/IR/Instruction.h" 9 #include "llvm/MC/MCAsmInfo.h" 10 #include "llvm/MC/MCStreamer.h" 11 #include "llvm/Target/TargetFrameLowering.h" 12 #include "llvm/Target/TargetLoweringObjectFile.h" 13 #include "llvm/Target/TargetMachine.h" 14 #include "llvm/Target/TargetRegisterInfo.h" 15 #include "llvm/Target/TargetSubtargetInfo.h" 16 17 namespace llvm { 18 19 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, 20 AsmPrinter *A, DwarfDebug *DW, 21 DwarfFile *DWU) 22 : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), 23 Skeleton(nullptr), BaseAddress(nullptr) { 24 insertDIE(Node, &getUnitDie()); 25 } 26 27 /// addLabelAddress - Add a dwarf label attribute data and value using 28 /// DW_FORM_addr or DW_FORM_GNU_addr_index. 29 /// 30 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute, 31 const MCSymbol *Label) { 32 33 // Don't use the address pool in non-fission or in the skeleton unit itself. 34 // FIXME: Once GDB supports this, it's probably worthwhile using the address 35 // pool from the skeleton - maybe even in non-fission (possibly fewer 36 // relocations by sharing them in the pool, but we have other ideas about how 37 // to reduce the number of relocations as well/instead). 38 if (!DD->useSplitDwarf() || !Skeleton) 39 return addLocalLabelAddress(Die, Attribute, Label); 40 41 if (Label) 42 DD->addArangeLabel(SymbolCU(this, Label)); 43 44 unsigned idx = DD->getAddressPool().getIndex(Label); 45 Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, DIEInteger(idx)); 46 } 47 48 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die, 49 dwarf::Attribute Attribute, 50 const MCSymbol *Label) { 51 if (Label) 52 DD->addArangeLabel(SymbolCU(this, Label)); 53 54 if (Label) 55 Die.addValue(Attribute, dwarf::DW_FORM_addr, DIELabel(Label)); 56 else 57 Die.addValue(Attribute, dwarf::DW_FORM_addr, DIEInteger(0)); 58 } 59 60 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, 61 StringRef DirName) { 62 // If we print assembly, we can't separate .file entries according to 63 // compile units. Thus all files will belong to the default compile unit. 64 65 // FIXME: add a better feature test than hasRawTextSupport. Even better, 66 // extend .file to support this. 67 return Asm->OutStreamer->EmitDwarfFileDirective( 68 0, DirName, FileName, 69 Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID()); 70 } 71 72 // Return const expression if value is a GEP to access merged global 73 // constant. e.g. 74 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0) 75 static const ConstantExpr *getMergedGlobalExpr(const Value *V) { 76 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V); 77 if (!CE || CE->getNumOperands() != 3 || 78 CE->getOpcode() != Instruction::GetElementPtr) 79 return nullptr; 80 81 // First operand points to a global struct. 82 Value *Ptr = CE->getOperand(0); 83 if (!isa<GlobalValue>(Ptr) || 84 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType())) 85 return nullptr; 86 87 // Second operand is zero. 88 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1)); 89 if (!CI || !CI->isZero()) 90 return nullptr; 91 92 // Third operand is offset. 93 if (!isa<ConstantInt>(CE->getOperand(2))) 94 return nullptr; 95 96 return CE; 97 } 98 99 /// getOrCreateGlobalVariableDIE - get or create global variable DIE. 100 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE( 101 const DIGlobalVariable *GV) { 102 // Check for pre-existence. 103 if (DIE *Die = getDIE(GV)) 104 return Die; 105 106 assert(GV); 107 108 auto *GVContext = GV->getScope(); 109 auto *GTy = DD->resolve(GV->getType()); 110 111 // Construct the context before querying for the existence of the DIE in 112 // case such construction creates the DIE. 113 DIE *ContextDIE = getOrCreateContextDIE(GVContext); 114 115 // Add to map. 116 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV); 117 DIScope *DeclContext; 118 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) { 119 DeclContext = resolve(SDMDecl->getScope()); 120 assert(SDMDecl->isStaticMember() && "Expected static member decl"); 121 assert(GV->isDefinition()); 122 // We need the declaration DIE that is in the static member's class. 123 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl); 124 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE); 125 } else { 126 DeclContext = GV->getScope(); 127 // Add name and type. 128 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName()); 129 addType(*VariableDIE, GTy); 130 131 // Add scoping info. 132 if (!GV->isLocalToUnit()) 133 addFlag(*VariableDIE, dwarf::DW_AT_external); 134 135 // Add line number info. 136 addSourceLine(*VariableDIE, GV); 137 } 138 139 if (!GV->isDefinition()) 140 addFlag(*VariableDIE, dwarf::DW_AT_declaration); 141 else 142 addGlobalName(GV->getName(), *VariableDIE, DeclContext); 143 144 // Add location. 145 bool addToAccelTable = false; 146 if (auto *Global = dyn_cast_or_null<GlobalVariable>(GV->getVariable())) { 147 addToAccelTable = true; 148 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 149 const MCSymbol *Sym = Asm->getSymbol(Global); 150 if (Global->isThreadLocal()) { 151 // FIXME: Make this work with -gsplit-dwarf. 152 unsigned PointerSize = Asm->getDataLayout().getPointerSize(); 153 assert((PointerSize == 4 || PointerSize == 8) && 154 "Add support for other sizes if necessary"); 155 // Based on GCC's support for TLS: 156 if (!DD->useSplitDwarf()) { 157 // 1) Start with a constNu of the appropriate pointer size 158 addUInt(*Loc, dwarf::DW_FORM_data1, 159 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u); 160 // 2) containing the (relocated) offset of the TLS variable 161 // within the module's TLS block. 162 addExpr(*Loc, dwarf::DW_FORM_udata, 163 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym)); 164 } else { 165 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index); 166 addUInt(*Loc, dwarf::DW_FORM_udata, 167 DD->getAddressPool().getIndex(Sym, /* TLS */ true)); 168 } 169 // 3) followed by an OP to make the debugger do a TLS lookup. 170 addUInt(*Loc, dwarf::DW_FORM_data1, 171 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address 172 : dwarf::DW_OP_form_tls_address); 173 } else { 174 DD->addArangeLabel(SymbolCU(this, Sym)); 175 addOpAddress(*Loc, Sym); 176 } 177 178 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc); 179 addLinkageName(*VariableDIE, GV->getLinkageName()); 180 } else if (const ConstantInt *CI = 181 dyn_cast_or_null<ConstantInt>(GV->getVariable())) { 182 addConstantValue(*VariableDIE, CI, GTy); 183 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getVariable())) { 184 addToAccelTable = true; 185 // GV is a merged global. 186 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 187 Value *Ptr = CE->getOperand(0); 188 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr)); 189 DD->addArangeLabel(SymbolCU(this, Sym)); 190 addOpAddress(*Loc, Sym); 191 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 192 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end()); 193 addUInt(*Loc, dwarf::DW_FORM_udata, 194 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx)); 195 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 196 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc); 197 } 198 199 if (addToAccelTable) { 200 DD->addAccelName(GV->getName(), *VariableDIE); 201 202 // If the linkage name is different than the name, go ahead and output 203 // that as well into the name table. 204 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName()) 205 DD->addAccelName(GV->getLinkageName(), *VariableDIE); 206 } 207 208 return VariableDIE; 209 } 210 211 void DwarfCompileUnit::addRange(RangeSpan Range) { 212 bool SameAsPrevCU = this == DD->getPrevCU(); 213 DD->setPrevCU(this); 214 // If we have no current ranges just add the range and return, otherwise, 215 // check the current section and CU against the previous section and CU we 216 // emitted into and the subprogram was contained within. If these are the 217 // same then extend our current range, otherwise add this as a new range. 218 if (CURanges.empty() || !SameAsPrevCU || 219 (&CURanges.back().getEnd()->getSection() != 220 &Range.getEnd()->getSection())) { 221 CURanges.push_back(Range); 222 return; 223 } 224 225 CURanges.back().setEnd(Range.getEnd()); 226 } 227 228 void DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute, 229 const MCSymbol *Label, 230 const MCSymbol *Sec) { 231 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) 232 addLabel(Die, Attribute, 233 DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 234 : dwarf::DW_FORM_data4, 235 Label); 236 else 237 addSectionDelta(Die, Attribute, Label, Sec); 238 } 239 240 void DwarfCompileUnit::initStmtList() { 241 // Define start line table label for each Compile Unit. 242 MCSymbol *LineTableStartSym = 243 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID()); 244 245 stmtListIndex = std::distance(UnitDie.values_begin(), UnitDie.values_end()); 246 247 // DW_AT_stmt_list is a offset of line number information for this 248 // compile unit in debug_line section. For split dwarf this is 249 // left in the skeleton CU and so not included. 250 // The line table entries are not always emitted in assembly, so it 251 // is not okay to use line_table_start here. 252 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 253 addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym, 254 TLOF.getDwarfLineSection()->getBeginSymbol()); 255 } 256 257 void DwarfCompileUnit::applyStmtList(DIE &D) { 258 D.addValue(UnitDie.values_begin()[stmtListIndex]); 259 } 260 261 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin, 262 const MCSymbol *End) { 263 assert(Begin && "Begin label should not be null!"); 264 assert(End && "End label should not be null!"); 265 assert(Begin->isDefined() && "Invalid starting label"); 266 assert(End->isDefined() && "Invalid end label"); 267 268 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin); 269 if (DD->getDwarfVersion() < 4) 270 addLabelAddress(D, dwarf::DW_AT_high_pc, End); 271 else 272 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin); 273 } 274 275 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc 276 // and DW_AT_high_pc attributes. If there are global variables in this 277 // scope then create and insert DIEs for these variables. 278 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) { 279 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes()); 280 281 attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd()); 282 if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim( 283 *DD->getCurrentFunction())) 284 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr); 285 286 // Only include DW_AT_frame_base in full debug info 287 if (!includeMinimalInlineScopes()) { 288 const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo(); 289 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 290 if (RI->isPhysicalRegister(Location.getReg())) 291 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location); 292 } 293 294 // Add name to the name table, we do this here because we're guaranteed 295 // to have concrete versions of our DW_TAG_subprogram nodes. 296 DD->addSubprogramNames(SP, *SPDie); 297 298 return *SPDie; 299 } 300 301 // Construct a DIE for this scope. 302 void DwarfCompileUnit::constructScopeDIE( 303 LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) { 304 if (!Scope || !Scope->getScopeNode()) 305 return; 306 307 auto *DS = Scope->getScopeNode(); 308 309 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && 310 "Only handle inlined subprograms here, use " 311 "constructSubprogramScopeDIE for non-inlined " 312 "subprograms"); 313 314 SmallVector<std::unique_ptr<DIE>, 8> Children; 315 316 // We try to create the scope DIE first, then the children DIEs. This will 317 // avoid creating un-used children then removing them later when we find out 318 // the scope DIE is null. 319 std::unique_ptr<DIE> ScopeDIE; 320 if (Scope->getParent() && isa<DISubprogram>(DS)) { 321 ScopeDIE = constructInlinedScopeDIE(Scope); 322 if (!ScopeDIE) 323 return; 324 // We create children when the scope DIE is not null. 325 createScopeChildrenDIE(Scope, Children); 326 } else { 327 // Early exit when we know the scope DIE is going to be null. 328 if (DD->isLexicalScopeDIENull(Scope)) 329 return; 330 331 unsigned ChildScopeCount; 332 333 // We create children here when we know the scope DIE is not going to be 334 // null and the children will be added to the scope DIE. 335 createScopeChildrenDIE(Scope, Children, &ChildScopeCount); 336 337 // Skip imported directives in gmlt-like data. 338 if (!includeMinimalInlineScopes()) { 339 // There is no need to emit empty lexical block DIE. 340 for (const auto &E : DD->findImportedEntitiesForScope(DS)) 341 Children.push_back( 342 constructImportedEntityDIE(cast<DIImportedEntity>(E.second))); 343 } 344 345 // If there are only other scopes as children, put them directly in the 346 // parent instead, as this scope would serve no purpose. 347 if (Children.size() == ChildScopeCount) { 348 FinalChildren.insert(FinalChildren.end(), 349 std::make_move_iterator(Children.begin()), 350 std::make_move_iterator(Children.end())); 351 return; 352 } 353 ScopeDIE = constructLexicalScopeDIE(Scope); 354 assert(ScopeDIE && "Scope DIE should not be null."); 355 } 356 357 // Add children 358 for (auto &I : Children) 359 ScopeDIE->addChild(std::move(I)); 360 361 FinalChildren.push_back(std::move(ScopeDIE)); 362 } 363 364 void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute, 365 const MCSymbol *Hi, const MCSymbol *Lo) { 366 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 367 : dwarf::DW_FORM_data4, 368 new (DIEValueAllocator) DIEDelta(Hi, Lo)); 369 } 370 371 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE, 372 SmallVector<RangeSpan, 2> Range) { 373 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 374 375 // Emit offset in .debug_range as a relocatable label. emitDIE will handle 376 // emitting it appropriately. 377 const MCSymbol *RangeSectionSym = 378 TLOF.getDwarfRangesSection()->getBeginSymbol(); 379 380 RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range)); 381 382 // Under fission, ranges are specified by constant offsets relative to the 383 // CU's DW_AT_GNU_ranges_base. 384 if (isDwoUnit()) 385 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 386 RangeSectionSym); 387 else 388 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 389 RangeSectionSym); 390 391 // Add the range list to the set of ranges to be emitted. 392 (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List)); 393 } 394 395 void DwarfCompileUnit::attachRangesOrLowHighPC( 396 DIE &Die, SmallVector<RangeSpan, 2> Ranges) { 397 if (Ranges.size() == 1) { 398 const auto &single = Ranges.front(); 399 attachLowHighPC(Die, single.getStart(), single.getEnd()); 400 } else 401 addScopeRangeList(Die, std::move(Ranges)); 402 } 403 404 void DwarfCompileUnit::attachRangesOrLowHighPC( 405 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) { 406 SmallVector<RangeSpan, 2> List; 407 List.reserve(Ranges.size()); 408 for (const InsnRange &R : Ranges) 409 List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first), 410 DD->getLabelAfterInsn(R.second))); 411 attachRangesOrLowHighPC(Die, std::move(List)); 412 } 413 414 // This scope represents inlined body of a function. Construct DIE to 415 // represent this concrete inlined copy of the function. 416 std::unique_ptr<DIE> 417 DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) { 418 assert(Scope->getScopeNode()); 419 auto *DS = Scope->getScopeNode(); 420 auto *InlinedSP = getDISubprogram(DS); 421 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 422 // was inlined from another compile unit. 423 DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP]; 424 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram."); 425 426 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine); 427 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE); 428 429 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 430 431 // Add the call site information to the DIE. 432 const DILocation *IA = Scope->getInlinedAt(); 433 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None, 434 getOrCreateSourceID(IA->getFilename(), IA->getDirectory())); 435 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine()); 436 437 // Add name to the name table, we do this here because we're guaranteed 438 // to have concrete versions of our DW_TAG_inlined_subprogram nodes. 439 DD->addSubprogramNames(InlinedSP, *ScopeDIE); 440 441 return ScopeDIE; 442 } 443 444 // Construct new DW_TAG_lexical_block for this scope and attach 445 // DW_AT_low_pc/DW_AT_high_pc labels. 446 std::unique_ptr<DIE> 447 DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) { 448 if (DD->isLexicalScopeDIENull(Scope)) 449 return nullptr; 450 451 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block); 452 if (Scope->isAbstractScope()) 453 return ScopeDIE; 454 455 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 456 457 return ScopeDIE; 458 } 459 460 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 461 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, 462 bool Abstract) { 463 auto D = constructVariableDIEImpl(DV, Abstract); 464 DV.setDIE(*D); 465 return D; 466 } 467 468 std::unique_ptr<DIE> 469 DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV, 470 bool Abstract) { 471 // Define variable debug information entry. 472 auto VariableDie = make_unique<DIE>(DV.getTag()); 473 474 if (Abstract) { 475 applyVariableAttributes(DV, *VariableDie); 476 return VariableDie; 477 } 478 479 // Add variable address. 480 481 unsigned Offset = DV.getDebugLocListIndex(); 482 if (Offset != ~0U) { 483 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset); 484 return VariableDie; 485 } 486 487 // Check if variable is described by a DBG_VALUE instruction. 488 if (const MachineInstr *DVInsn = DV.getMInsn()) { 489 assert(DVInsn->getNumOperands() == 4); 490 if (DVInsn->getOperand(0).isReg()) { 491 const MachineOperand RegOp = DVInsn->getOperand(0); 492 // If the second operand is an immediate, this is an indirect value. 493 if (DVInsn->getOperand(1).isImm()) { 494 MachineLocation Location(RegOp.getReg(), 495 DVInsn->getOperand(1).getImm()); 496 addVariableAddress(DV, *VariableDie, Location); 497 } else if (RegOp.getReg()) 498 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg())); 499 } else if (DVInsn->getOperand(0).isImm()) 500 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType()); 501 else if (DVInsn->getOperand(0).isFPImm()) 502 addConstantFPValue(*VariableDie, DVInsn->getOperand(0)); 503 else if (DVInsn->getOperand(0).isCImm()) 504 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(), 505 DV.getType()); 506 507 return VariableDie; 508 } 509 510 // .. else use frame index. 511 if (DV.getFrameIndex().back() == ~0) 512 return VariableDie; 513 514 auto Expr = DV.getExpression().begin(); 515 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 516 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 517 for (auto FI : DV.getFrameIndex()) { 518 unsigned FrameReg = 0; 519 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering(); 520 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg); 521 assert(Expr != DV.getExpression().end() && 522 "Wrong number of expressions"); 523 DwarfExpr.AddMachineRegIndirect(FrameReg, Offset); 524 DwarfExpr.AddExpression((*Expr)->expr_op_begin(), (*Expr)->expr_op_end()); 525 ++Expr; 526 } 527 addBlock(*VariableDie, dwarf::DW_AT_location, Loc); 528 529 return VariableDie; 530 } 531 532 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE( 533 DbgVariable &DV, const LexicalScope &Scope, DIE *&ObjectPointer) { 534 auto Var = constructVariableDIE(DV, Scope.isAbstractScope()); 535 if (DV.isObjectPointer()) 536 ObjectPointer = Var.get(); 537 return Var; 538 } 539 540 DIE *DwarfCompileUnit::createScopeChildrenDIE( 541 LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &Children, 542 unsigned *ChildScopeCount) { 543 DIE *ObjectPointer = nullptr; 544 545 for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope)) 546 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer)); 547 548 unsigned ChildCountWithoutScopes = Children.size(); 549 550 for (LexicalScope *LS : Scope->getChildren()) 551 constructScopeDIE(LS, Children); 552 553 if (ChildScopeCount) 554 *ChildScopeCount = Children.size() - ChildCountWithoutScopes; 555 556 return ObjectPointer; 557 } 558 559 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) { 560 assert(Scope && Scope->getScopeNode()); 561 assert(!Scope->getInlinedAt()); 562 assert(!Scope->isAbstractScope()); 563 auto *Sub = cast<DISubprogram>(Scope->getScopeNode()); 564 565 DD->getProcessedSPNodes().insert(Sub); 566 567 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub); 568 569 // If this is a variadic function, add an unspecified parameter. 570 DITypeRefArray FnArgs = Sub->getType()->getTypeArray(); 571 572 // Collect lexical scope children first. 573 // ObjectPointer might be a local (non-argument) local variable if it's a 574 // block's synthetic this pointer. 575 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE)) 576 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer); 577 578 // If we have a single element of null, it is a function that returns void. 579 // If we have more than one elements and the last one is null, it is a 580 // variadic function. 581 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] && 582 !includeMinimalInlineScopes()) 583 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters)); 584 } 585 586 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, 587 DIE &ScopeDIE) { 588 // We create children when the scope DIE is not null. 589 SmallVector<std::unique_ptr<DIE>, 8> Children; 590 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children); 591 592 // Add children 593 for (auto &I : Children) 594 ScopeDIE.addChild(std::move(I)); 595 596 return ObjectPointer; 597 } 598 599 void 600 DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) { 601 DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()]; 602 if (AbsDef) 603 return; 604 605 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 606 607 DIE *ContextDIE; 608 609 if (includeMinimalInlineScopes()) 610 ContextDIE = &getUnitDie(); 611 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with 612 // the important distinction that the debug node is not associated with the 613 // DIE (since the debug node will be associated with the concrete DIE, if 614 // any). It could be refactored to some common utility function. 615 else if (auto *SPDecl = SP->getDeclaration()) { 616 ContextDIE = &getUnitDie(); 617 getOrCreateSubprogramDIE(SPDecl); 618 } else 619 ContextDIE = getOrCreateContextDIE(resolve(SP->getScope())); 620 621 // Passing null as the associated node because the abstract definition 622 // shouldn't be found by lookup. 623 AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr); 624 applySubprogramAttributesToDefinition(SP, *AbsDef); 625 626 if (!includeMinimalInlineScopes()) 627 addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 628 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef)) 629 addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer); 630 } 631 632 std::unique_ptr<DIE> 633 DwarfCompileUnit::constructImportedEntityDIE(const DIImportedEntity *Module) { 634 std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module->getTag()); 635 insertDIE(Module, IMDie.get()); 636 DIE *EntityDie; 637 auto *Entity = resolve(Module->getEntity()); 638 if (auto *NS = dyn_cast<DINamespace>(Entity)) 639 EntityDie = getOrCreateNameSpace(NS); 640 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 641 EntityDie = getOrCreateSubprogramDIE(SP); 642 else if (auto *T = dyn_cast<DIType>(Entity)) 643 EntityDie = getOrCreateTypeDIE(T); 644 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity)) 645 EntityDie = getOrCreateGlobalVariableDIE(GV); 646 else 647 EntityDie = getDIE(Entity); 648 assert(EntityDie); 649 addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(), 650 Module->getScope()->getDirectory()); 651 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie); 652 StringRef Name = Module->getName(); 653 if (!Name.empty()) 654 addString(*IMDie, dwarf::DW_AT_name, Name); 655 656 return IMDie; 657 } 658 659 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { 660 DIE *D = getDIE(SP); 661 if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) { 662 if (D) 663 // If this subprogram has an abstract definition, reference that 664 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); 665 } else { 666 if (!D && !includeMinimalInlineScopes()) 667 // Lazily construct the subprogram if we didn't see either concrete or 668 // inlined versions during codegen. (except in -gmlt ^ where we want 669 // to omit these entirely) 670 D = getOrCreateSubprogramDIE(SP); 671 if (D) 672 // And attach the attributes 673 applySubprogramAttributesToDefinition(SP, *D); 674 } 675 } 676 void DwarfCompileUnit::collectDeadVariables(const DISubprogram *SP) { 677 assert(SP && "CU's subprogram list contains a non-subprogram"); 678 assert(SP->isDefinition() && 679 "CU's subprogram list contains a subprogram declaration"); 680 auto Variables = SP->getVariables(); 681 if (Variables.size() == 0) 682 return; 683 684 DIE *SPDIE = DU->getAbstractSPDies().lookup(SP); 685 if (!SPDIE) 686 SPDIE = getDIE(SP); 687 assert(SPDIE); 688 for (const DILocalVariable *DV : Variables) { 689 DbgVariable NewVar(DV, /* IA */ nullptr, /* Expr */ nullptr, DD); 690 auto VariableDie = constructVariableDIE(NewVar); 691 applyVariableAttributes(NewVar, *VariableDie); 692 SPDIE->addChild(std::move(VariableDie)); 693 } 694 } 695 696 void DwarfCompileUnit::emitHeader(bool UseOffsets) { 697 // Don't bother labeling the .dwo unit, as its offset isn't used. 698 if (!Skeleton) { 699 LabelBegin = Asm->createTempSymbol("cu_begin"); 700 Asm->OutStreamer->EmitLabel(LabelBegin); 701 } 702 703 DwarfUnit::emitHeader(UseOffsets); 704 } 705 706 /// addGlobalName - Add a new global name to the compile unit. 707 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die, 708 const DIScope *Context) { 709 if (includeMinimalInlineScopes()) 710 return; 711 std::string FullName = getParentContextString(Context) + Name.str(); 712 GlobalNames[FullName] = &Die; 713 } 714 715 /// Add a new global type to the unit. 716 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die, 717 const DIScope *Context) { 718 if (includeMinimalInlineScopes()) 719 return; 720 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 721 GlobalTypes[FullName] = &Die; 722 } 723 724 /// addVariableAddress - Add DW_AT_location attribute for a 725 /// DbgVariable based on provided MachineLocation. 726 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die, 727 MachineLocation Location) { 728 if (DV.variableHasComplexAddress()) 729 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 730 else if (DV.isBlockByrefVariable()) 731 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location); 732 else 733 addAddress(Die, dwarf::DW_AT_location, Location); 734 } 735 736 /// Add an address attribute to a die based on the location provided. 737 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute, 738 const MachineLocation &Location) { 739 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 740 741 bool validReg; 742 if (Location.isReg()) 743 validReg = addRegisterOpPiece(*Loc, Location.getReg()); 744 else 745 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset()); 746 747 if (!validReg) 748 return; 749 750 // Now attach the location information to the DIE. 751 addBlock(Die, Attribute, Loc); 752 } 753 754 /// Start with the address based on the location provided, and generate the 755 /// DWARF information necessary to find the actual variable given the extra 756 /// address information encoded in the DbgVariable, starting from the starting 757 /// location. Add the DWARF information to the die. 758 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die, 759 dwarf::Attribute Attribute, 760 const MachineLocation &Location) { 761 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 762 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 763 assert(DV.getExpression().size() == 1); 764 const DIExpression *Expr = DV.getExpression().back(); 765 bool ValidReg; 766 if (Location.getOffset()) { 767 ValidReg = DwarfExpr.AddMachineRegIndirect(Location.getReg(), 768 Location.getOffset()); 769 if (ValidReg) 770 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end()); 771 } else 772 ValidReg = DwarfExpr.AddMachineRegExpression(Expr, Location.getReg()); 773 774 // Now attach the location information to the DIE. 775 if (ValidReg) 776 addBlock(Die, Attribute, Loc); 777 } 778 779 /// Add a Dwarf loclistptr attribute data and value. 780 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute, 781 unsigned Index) { 782 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 783 : dwarf::DW_FORM_data4; 784 Die.addValue(Attribute, Form, DIELocList(Index)); 785 } 786 787 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var, 788 DIE &VariableDie) { 789 StringRef Name = Var.getName(); 790 if (!Name.empty()) 791 addString(VariableDie, dwarf::DW_AT_name, Name); 792 addSourceLine(VariableDie, Var.getVariable()); 793 addType(VariableDie, Var.getType()); 794 if (Var.isArtificial()) 795 addFlag(VariableDie, dwarf::DW_AT_artificial); 796 } 797 798 /// Add a Dwarf expression attribute data and value. 799 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form, 800 const MCExpr *Expr) { 801 Die.addValue((dwarf::Attribute)0, Form, DIEExpr(Expr)); 802 } 803 804 void DwarfCompileUnit::applySubprogramAttributesToDefinition( 805 const DISubprogram *SP, DIE &SPDie) { 806 auto *SPDecl = SP->getDeclaration(); 807 auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope()); 808 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes()); 809 addGlobalName(SP->getName(), SPDie, Context); 810 } 811 812 bool DwarfCompileUnit::isDwoUnit() const { 813 return DD->useSplitDwarf() && Skeleton; 814 } 815 816 bool DwarfCompileUnit::includeMinimalInlineScopes() const { 817 return getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly || 818 (DD->useSplitDwarf() && !Skeleton); 819 } 820 } // end llvm namespace 821