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 ConstantFP *CF = 198 dyn_cast_or_null<ConstantFP>(GV->getVariable())) { 199 addConstantFPValue(*VariableDIE, CF); 200 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getVariable())) { 201 auto *Ptr = cast<GlobalValue>(CE->getOperand(0)); 202 if (!Ptr->hasDLLImportStorageClass()) { 203 addToAccelTable = true; 204 // GV is a merged global. 205 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 206 MCSymbol *Sym = Asm->getSymbol(Ptr); 207 DD->addArangeLabel(SymbolCU(this, Sym)); 208 addOpAddress(*Loc, Sym); 209 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 210 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end()); 211 addUInt(*Loc, dwarf::DW_FORM_udata, 212 Asm->getDataLayout().getIndexedOffsetInType(Ptr->getValueType(), 213 Idx)); 214 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 215 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc); 216 } 217 } 218 219 if (addToAccelTable) { 220 DD->addAccelName(GV->getName(), *VariableDIE); 221 222 // If the linkage name is different than the name, go ahead and output 223 // that as well into the name table. 224 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName()) 225 DD->addAccelName(GV->getLinkageName(), *VariableDIE); 226 } 227 228 return VariableDIE; 229 } 230 231 void DwarfCompileUnit::addRange(RangeSpan Range) { 232 bool SameAsPrevCU = this == DD->getPrevCU(); 233 DD->setPrevCU(this); 234 // If we have no current ranges just add the range and return, otherwise, 235 // check the current section and CU against the previous section and CU we 236 // emitted into and the subprogram was contained within. If these are the 237 // same then extend our current range, otherwise add this as a new range. 238 if (CURanges.empty() || !SameAsPrevCU || 239 (&CURanges.back().getEnd()->getSection() != 240 &Range.getEnd()->getSection())) { 241 CURanges.push_back(Range); 242 return; 243 } 244 245 CURanges.back().setEnd(Range.getEnd()); 246 } 247 248 DIE::value_iterator 249 DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute, 250 const MCSymbol *Label, const MCSymbol *Sec) { 251 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) 252 return addLabel(Die, Attribute, 253 DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 254 : dwarf::DW_FORM_data4, 255 Label); 256 return addSectionDelta(Die, Attribute, Label, Sec); 257 } 258 259 void DwarfCompileUnit::initStmtList() { 260 // Define start line table label for each Compile Unit. 261 MCSymbol *LineTableStartSym = 262 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID()); 263 264 // DW_AT_stmt_list is a offset of line number information for this 265 // compile unit in debug_line section. For split dwarf this is 266 // left in the skeleton CU and so not included. 267 // The line table entries are not always emitted in assembly, so it 268 // is not okay to use line_table_start here. 269 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 270 StmtListValue = 271 addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym, 272 TLOF.getDwarfLineSection()->getBeginSymbol()); 273 } 274 275 void DwarfCompileUnit::applyStmtList(DIE &D) { 276 D.addValue(DIEValueAllocator, *StmtListValue); 277 } 278 279 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin, 280 const MCSymbol *End) { 281 assert(Begin && "Begin label should not be null!"); 282 assert(End && "End label should not be null!"); 283 assert(Begin->isDefined() && "Invalid starting label"); 284 assert(End->isDefined() && "Invalid end label"); 285 286 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin); 287 if (DD->getDwarfVersion() < 4) 288 addLabelAddress(D, dwarf::DW_AT_high_pc, End); 289 else 290 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin); 291 } 292 293 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc 294 // and DW_AT_high_pc attributes. If there are global variables in this 295 // scope then create and insert DIEs for these variables. 296 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) { 297 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes()); 298 299 attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd()); 300 if (DD->useAppleExtensionAttributes() && 301 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim( 302 *DD->getCurrentFunction())) 303 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr); 304 305 // Only include DW_AT_frame_base in full debug info 306 if (!includeMinimalInlineScopes()) { 307 const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo(); 308 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 309 if (RI->isPhysicalRegister(Location.getReg())) 310 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location); 311 } 312 313 // Add name to the name table, we do this here because we're guaranteed 314 // to have concrete versions of our DW_TAG_subprogram nodes. 315 DD->addSubprogramNames(SP, *SPDie); 316 317 return *SPDie; 318 } 319 320 // Construct a DIE for this scope. 321 void DwarfCompileUnit::constructScopeDIE( 322 LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) { 323 if (!Scope || !Scope->getScopeNode()) 324 return; 325 326 auto *DS = Scope->getScopeNode(); 327 328 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && 329 "Only handle inlined subprograms here, use " 330 "constructSubprogramScopeDIE for non-inlined " 331 "subprograms"); 332 333 SmallVector<DIE *, 8> Children; 334 335 // We try to create the scope DIE first, then the children DIEs. This will 336 // avoid creating un-used children then removing them later when we find out 337 // the scope DIE is null. 338 DIE *ScopeDIE; 339 if (Scope->getParent() && isa<DISubprogram>(DS)) { 340 ScopeDIE = constructInlinedScopeDIE(Scope); 341 if (!ScopeDIE) 342 return; 343 // We create children when the scope DIE is not null. 344 createScopeChildrenDIE(Scope, Children); 345 } else { 346 // Early exit when we know the scope DIE is going to be null. 347 if (DD->isLexicalScopeDIENull(Scope)) 348 return; 349 350 unsigned ChildScopeCount; 351 352 // We create children here when we know the scope DIE is not going to be 353 // null and the children will be added to the scope DIE. 354 createScopeChildrenDIE(Scope, Children, &ChildScopeCount); 355 356 // Skip imported directives in gmlt-like data. 357 if (!includeMinimalInlineScopes()) { 358 // There is no need to emit empty lexical block DIE. 359 for (const auto *IE : ImportedEntities[DS]) 360 Children.push_back( 361 constructImportedEntityDIE(cast<DIImportedEntity>(IE))); 362 } 363 364 // If there are only other scopes as children, put them directly in the 365 // parent instead, as this scope would serve no purpose. 366 if (Children.size() == ChildScopeCount) { 367 FinalChildren.insert(FinalChildren.end(), 368 std::make_move_iterator(Children.begin()), 369 std::make_move_iterator(Children.end())); 370 return; 371 } 372 ScopeDIE = constructLexicalScopeDIE(Scope); 373 assert(ScopeDIE && "Scope DIE should not be null."); 374 } 375 376 // Add children 377 for (auto &I : Children) 378 ScopeDIE->addChild(std::move(I)); 379 380 FinalChildren.push_back(std::move(ScopeDIE)); 381 } 382 383 DIE::value_iterator 384 DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute, 385 const MCSymbol *Hi, const MCSymbol *Lo) { 386 return Die.addValue(DIEValueAllocator, Attribute, 387 DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 388 : dwarf::DW_FORM_data4, 389 new (DIEValueAllocator) DIEDelta(Hi, Lo)); 390 } 391 392 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE, 393 SmallVector<RangeSpan, 2> Range) { 394 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 395 396 // Emit offset in .debug_range as a relocatable label. emitDIE will handle 397 // emitting it appropriately. 398 const MCSymbol *RangeSectionSym = 399 TLOF.getDwarfRangesSection()->getBeginSymbol(); 400 401 RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range)); 402 403 // Under fission, ranges are specified by constant offsets relative to the 404 // CU's DW_AT_GNU_ranges_base. 405 if (isDwoUnit()) 406 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 407 RangeSectionSym); 408 else 409 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 410 RangeSectionSym); 411 412 // Add the range list to the set of ranges to be emitted. 413 (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List)); 414 } 415 416 void DwarfCompileUnit::attachRangesOrLowHighPC( 417 DIE &Die, SmallVector<RangeSpan, 2> Ranges) { 418 if (Ranges.size() == 1) { 419 const auto &single = Ranges.front(); 420 attachLowHighPC(Die, single.getStart(), single.getEnd()); 421 } else 422 addScopeRangeList(Die, std::move(Ranges)); 423 } 424 425 void DwarfCompileUnit::attachRangesOrLowHighPC( 426 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) { 427 SmallVector<RangeSpan, 2> List; 428 List.reserve(Ranges.size()); 429 for (const InsnRange &R : Ranges) 430 List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first), 431 DD->getLabelAfterInsn(R.second))); 432 attachRangesOrLowHighPC(Die, std::move(List)); 433 } 434 435 // This scope represents inlined body of a function. Construct DIE to 436 // represent this concrete inlined copy of the function. 437 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) { 438 assert(Scope->getScopeNode()); 439 auto *DS = Scope->getScopeNode(); 440 auto *InlinedSP = getDISubprogram(DS); 441 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 442 // was inlined from another compile unit. 443 DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP]; 444 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram."); 445 446 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine); 447 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE); 448 449 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 450 451 // Add the call site information to the DIE. 452 const DILocation *IA = Scope->getInlinedAt(); 453 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None, 454 getOrCreateSourceID(IA->getFilename(), IA->getDirectory())); 455 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine()); 456 if (IA->getDiscriminator()) 457 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None, 458 IA->getDiscriminator()); 459 460 // Add name to the name table, we do this here because we're guaranteed 461 // to have concrete versions of our DW_TAG_inlined_subprogram nodes. 462 DD->addSubprogramNames(InlinedSP, *ScopeDIE); 463 464 return ScopeDIE; 465 } 466 467 // Construct new DW_TAG_lexical_block for this scope and attach 468 // DW_AT_low_pc/DW_AT_high_pc labels. 469 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) { 470 if (DD->isLexicalScopeDIENull(Scope)) 471 return nullptr; 472 473 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block); 474 if (Scope->isAbstractScope()) 475 return ScopeDIE; 476 477 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 478 479 return ScopeDIE; 480 } 481 482 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 483 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) { 484 auto D = constructVariableDIEImpl(DV, Abstract); 485 DV.setDIE(*D); 486 return D; 487 } 488 489 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV, 490 bool Abstract) { 491 // Define variable debug information entry. 492 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag()); 493 494 if (Abstract) { 495 applyVariableAttributes(DV, *VariableDie); 496 return VariableDie; 497 } 498 499 // Add variable address. 500 501 unsigned Offset = DV.getDebugLocListIndex(); 502 if (Offset != ~0U) { 503 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset); 504 return VariableDie; 505 } 506 507 // Check if variable is described by a DBG_VALUE instruction. 508 if (const MachineInstr *DVInsn = DV.getMInsn()) { 509 assert(DVInsn->getNumOperands() == 4); 510 if (DVInsn->getOperand(0).isReg()) { 511 const MachineOperand RegOp = DVInsn->getOperand(0); 512 // If the second operand is an immediate, this is an indirect value. 513 if (DVInsn->getOperand(1).isImm()) { 514 MachineLocation Location(RegOp.getReg(), 515 DVInsn->getOperand(1).getImm()); 516 addVariableAddress(DV, *VariableDie, Location); 517 } else if (RegOp.getReg()) 518 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg())); 519 } else if (DVInsn->getOperand(0).isImm()) { 520 // This variable is described by a single constant. 521 // Check whether it has a DIExpression. 522 auto *Expr = DV.getSingleExpression(); 523 if (Expr && Expr->getNumElements()) { 524 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 525 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 526 // If there is an expression, emit raw unsigned bytes. 527 DwarfExpr.AddUnsignedConstant(DVInsn->getOperand(0).getImm()); 528 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end()); 529 addBlock(*VariableDie, dwarf::DW_AT_location, Loc); 530 } else 531 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType()); 532 } else if (DVInsn->getOperand(0).isFPImm()) 533 addConstantFPValue(*VariableDie, DVInsn->getOperand(0)); 534 else if (DVInsn->getOperand(0).isCImm()) 535 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(), 536 DV.getType()); 537 538 return VariableDie; 539 } 540 541 // .. else use frame index. 542 if (DV.getFrameIndex().empty()) 543 return VariableDie; 544 545 auto Expr = DV.getExpression().begin(); 546 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 547 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 548 for (auto FI : DV.getFrameIndex()) { 549 unsigned FrameReg = 0; 550 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering(); 551 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg); 552 assert(Expr != DV.getExpression().end() && "Wrong number of expressions"); 553 DwarfExpr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(), 554 FrameReg, Offset); 555 DwarfExpr.AddExpression((*Expr)->expr_op_begin(), (*Expr)->expr_op_end()); 556 ++Expr; 557 } 558 addBlock(*VariableDie, dwarf::DW_AT_location, Loc); 559 560 return VariableDie; 561 } 562 563 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, 564 const LexicalScope &Scope, 565 DIE *&ObjectPointer) { 566 auto Var = constructVariableDIE(DV, Scope.isAbstractScope()); 567 if (DV.isObjectPointer()) 568 ObjectPointer = Var; 569 return Var; 570 } 571 572 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope, 573 SmallVectorImpl<DIE *> &Children, 574 unsigned *ChildScopeCount) { 575 DIE *ObjectPointer = nullptr; 576 577 for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope)) 578 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer)); 579 580 unsigned ChildCountWithoutScopes = Children.size(); 581 582 for (LexicalScope *LS : Scope->getChildren()) 583 constructScopeDIE(LS, Children); 584 585 if (ChildScopeCount) 586 *ChildScopeCount = Children.size() - ChildCountWithoutScopes; 587 588 return ObjectPointer; 589 } 590 591 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) { 592 assert(Scope && Scope->getScopeNode()); 593 assert(!Scope->getInlinedAt()); 594 assert(!Scope->isAbstractScope()); 595 auto *Sub = cast<DISubprogram>(Scope->getScopeNode()); 596 597 DD->getProcessedSPNodes().insert(Sub); 598 599 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub); 600 601 // If this is a variadic function, add an unspecified parameter. 602 DITypeRefArray FnArgs = Sub->getType()->getTypeArray(); 603 604 // Collect lexical scope children first. 605 // ObjectPointer might be a local (non-argument) local variable if it's a 606 // block's synthetic this pointer. 607 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE)) 608 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer); 609 610 // If we have a single element of null, it is a function that returns void. 611 // If we have more than one elements and the last one is null, it is a 612 // variadic function. 613 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] && 614 !includeMinimalInlineScopes()) 615 ScopeDIE.addChild( 616 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters)); 617 } 618 619 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, 620 DIE &ScopeDIE) { 621 // We create children when the scope DIE is not null. 622 SmallVector<DIE *, 8> Children; 623 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children); 624 625 // Add children 626 for (auto &I : Children) 627 ScopeDIE.addChild(std::move(I)); 628 629 return ObjectPointer; 630 } 631 632 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE( 633 LexicalScope *Scope) { 634 DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()]; 635 if (AbsDef) 636 return; 637 638 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 639 640 DIE *ContextDIE; 641 642 if (includeMinimalInlineScopes()) 643 ContextDIE = &getUnitDie(); 644 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with 645 // the important distinction that the debug node is not associated with the 646 // DIE (since the debug node will be associated with the concrete DIE, if 647 // any). It could be refactored to some common utility function. 648 else if (auto *SPDecl = SP->getDeclaration()) { 649 ContextDIE = &getUnitDie(); 650 getOrCreateSubprogramDIE(SPDecl); 651 } else 652 ContextDIE = getOrCreateContextDIE(resolve(SP->getScope())); 653 654 // Passing null as the associated node because the abstract definition 655 // shouldn't be found by lookup. 656 AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr); 657 applySubprogramAttributesToDefinition(SP, *AbsDef); 658 659 if (!includeMinimalInlineScopes()) 660 addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 661 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef)) 662 addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer); 663 } 664 665 DIE *DwarfCompileUnit::constructImportedEntityDIE( 666 const DIImportedEntity *Module) { 667 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag()); 668 insertDIE(Module, IMDie); 669 DIE *EntityDie; 670 auto *Entity = resolve(Module->getEntity()); 671 if (auto *NS = dyn_cast<DINamespace>(Entity)) 672 EntityDie = getOrCreateNameSpace(NS); 673 else if (auto *M = dyn_cast<DIModule>(Entity)) 674 EntityDie = getOrCreateModule(M); 675 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 676 EntityDie = getOrCreateSubprogramDIE(SP); 677 else if (auto *T = dyn_cast<DIType>(Entity)) 678 EntityDie = getOrCreateTypeDIE(T); 679 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity)) 680 EntityDie = getOrCreateGlobalVariableDIE(GV); 681 else 682 EntityDie = getDIE(Entity); 683 assert(EntityDie); 684 addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(), 685 Module->getScope()->getDirectory()); 686 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie); 687 StringRef Name = Module->getName(); 688 if (!Name.empty()) 689 addString(*IMDie, dwarf::DW_AT_name, Name); 690 691 return IMDie; 692 } 693 694 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { 695 DIE *D = getDIE(SP); 696 if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) { 697 if (D) 698 // If this subprogram has an abstract definition, reference that 699 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); 700 } else { 701 if (!D && !includeMinimalInlineScopes()) 702 // Lazily construct the subprogram if we didn't see either concrete or 703 // inlined versions during codegen. (except in -gmlt ^ where we want 704 // to omit these entirely) 705 D = getOrCreateSubprogramDIE(SP); 706 if (D) 707 // And attach the attributes 708 applySubprogramAttributesToDefinition(SP, *D); 709 } 710 } 711 712 void DwarfCompileUnit::emitHeader(bool UseOffsets) { 713 // Don't bother labeling the .dwo unit, as its offset isn't used. 714 if (!Skeleton) { 715 LabelBegin = Asm->createTempSymbol("cu_begin"); 716 Asm->OutStreamer->EmitLabel(LabelBegin); 717 } 718 719 DwarfUnit::emitHeader(UseOffsets); 720 } 721 722 /// addGlobalName - Add a new global name to the compile unit. 723 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die, 724 const DIScope *Context) { 725 if (includeMinimalInlineScopes()) 726 return; 727 std::string FullName = getParentContextString(Context) + Name.str(); 728 GlobalNames[FullName] = &Die; 729 } 730 731 /// Add a new global type to the unit. 732 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die, 733 const DIScope *Context) { 734 if (includeMinimalInlineScopes()) 735 return; 736 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 737 GlobalTypes[FullName] = &Die; 738 } 739 740 /// addVariableAddress - Add DW_AT_location attribute for a 741 /// DbgVariable based on provided MachineLocation. 742 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die, 743 MachineLocation Location) { 744 if (DV.hasComplexAddress()) 745 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 746 else if (DV.isBlockByrefVariable()) 747 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location); 748 else 749 addAddress(Die, dwarf::DW_AT_location, Location); 750 } 751 752 /// Add an address attribute to a die based on the location provided. 753 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute, 754 const MachineLocation &Location) { 755 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 756 757 bool validReg; 758 if (Location.isReg()) 759 validReg = addRegisterOpPiece(*Loc, Location.getReg()); 760 else 761 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset()); 762 763 if (!validReg) 764 return; 765 766 // Now attach the location information to the DIE. 767 addBlock(Die, Attribute, Loc); 768 } 769 770 /// Start with the address based on the location provided, and generate the 771 /// DWARF information necessary to find the actual variable given the extra 772 /// address information encoded in the DbgVariable, starting from the starting 773 /// location. Add the DWARF information to the die. 774 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die, 775 dwarf::Attribute Attribute, 776 const MachineLocation &Location) { 777 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 778 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 779 const DIExpression *Expr = DV.getSingleExpression(); 780 bool ValidReg; 781 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 782 if (Location.getOffset()) { 783 ValidReg = DwarfExpr.AddMachineRegIndirect(TRI, Location.getReg(), 784 Location.getOffset()); 785 if (ValidReg) 786 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end()); 787 } else 788 ValidReg = DwarfExpr.AddMachineRegExpression(TRI, Expr, Location.getReg()); 789 790 // Now attach the location information to the DIE. 791 if (ValidReg) 792 addBlock(Die, Attribute, Loc); 793 } 794 795 /// Add a Dwarf loclistptr attribute data and value. 796 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute, 797 unsigned Index) { 798 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 799 : dwarf::DW_FORM_data4; 800 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index)); 801 } 802 803 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var, 804 DIE &VariableDie) { 805 StringRef Name = Var.getName(); 806 if (!Name.empty()) 807 addString(VariableDie, dwarf::DW_AT_name, Name); 808 addSourceLine(VariableDie, Var.getVariable()); 809 addType(VariableDie, Var.getType()); 810 if (Var.isArtificial()) 811 addFlag(VariableDie, dwarf::DW_AT_artificial); 812 } 813 814 /// Add a Dwarf expression attribute data and value. 815 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form, 816 const MCExpr *Expr) { 817 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr)); 818 } 819 820 void DwarfCompileUnit::applySubprogramAttributesToDefinition( 821 const DISubprogram *SP, DIE &SPDie) { 822 auto *SPDecl = SP->getDeclaration(); 823 auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope()); 824 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes()); 825 addGlobalName(SP->getName(), SPDie, Context); 826 } 827 828 bool DwarfCompileUnit::isDwoUnit() const { 829 return DD->useSplitDwarf() && Skeleton; 830 } 831 832 bool DwarfCompileUnit::includeMinimalInlineScopes() const { 833 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly || 834 (DD->useSplitDwarf() && !Skeleton); 835 } 836 } // end llvm namespace 837