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