1 //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfCompileUnit.h"
15 #include "DwarfExpression.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/GlobalValue.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Target/TargetFrameLowering.h"
25 #include "llvm/Target/TargetLoweringObjectFile.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetSubtargetInfo.h"
32 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
33 AsmPrinter *A, DwarfDebug *DW,
35 : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID),
36 Skeleton(nullptr), BaseAddress(nullptr) {
37 insertDIE(Node, &getUnitDie());
38 MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
41 /// addLabelAddress - Add a dwarf label attribute data and value using
42 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
44 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
45 const MCSymbol *Label) {
47 // Don't use the address pool in non-fission or in the skeleton unit itself.
48 // FIXME: Once GDB supports this, it's probably worthwhile using the address
49 // pool from the skeleton - maybe even in non-fission (possibly fewer
50 // relocations by sharing them in the pool, but we have other ideas about how
51 // to reduce the number of relocations as well/instead).
52 if (!DD->useSplitDwarf() || !Skeleton)
53 return addLocalLabelAddress(Die, Attribute, Label);
56 DD->addArangeLabel(SymbolCU(this, Label));
58 unsigned idx = DD->getAddressPool().getIndex(Label);
59 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
63 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
64 dwarf::Attribute Attribute,
65 const MCSymbol *Label) {
67 DD->addArangeLabel(SymbolCU(this, Label));
70 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
73 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
77 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
79 // If we print assembly, we can't separate .file entries according to
80 // compile units. Thus all files will belong to the default compile unit.
82 // FIXME: add a better feature test than hasRawTextSupport. Even better,
83 // extend .file to support this.
84 return Asm->OutStreamer->EmitDwarfFileDirective(
86 Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
89 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
90 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
91 // Check for pre-existence.
92 if (DIE *Die = getDIE(GV))
97 auto *GVContext = GV->getScope();
98 auto *GTy = DD->resolve(GV->getType());
100 // Construct the context before querying for the existence of the DIE in
101 // case such construction creates the DIE.
102 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
105 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
106 DIScope *DeclContext;
107 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
108 DeclContext = resolve(SDMDecl->getScope());
109 assert(SDMDecl->isStaticMember() && "Expected static member decl");
110 assert(GV->isDefinition());
111 // We need the declaration DIE that is in the static member's class.
112 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
113 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
114 // If the global variable's type is different from the one in the class
115 // member type, assume that it's more specific and also emit it.
116 if (GTy != DD->resolve(SDMDecl->getBaseType()))
117 addType(*VariableDIE, GTy);
119 DeclContext = GV->getScope();
120 // Add name and type.
121 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
122 addType(*VariableDIE, GTy);
125 if (!GV->isLocalToUnit())
126 addFlag(*VariableDIE, dwarf::DW_AT_external);
128 // Add line number info.
129 addSourceLine(*VariableDIE, GV);
132 if (!GV->isDefinition())
133 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
135 addGlobalName(GV->getName(), *VariableDIE, DeclContext);
137 if (uint32_t AlignInBytes = GV->getAlignInBytes())
138 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
142 bool addToAccelTable = false;
143 DIELoc *Loc = nullptr;
144 std::unique_ptr<DIEDwarfExpression> DwarfExpr;
145 for (const auto &GE : GlobalExprs) {
146 const GlobalVariable *Global = GE.Var;
147 const DIExpression *Expr = GE.Expr;
149 // For compatibility with DWARF 3 and earlier,
150 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
151 // DW_AT_const_value(X).
152 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
153 addToAccelTable = true;
154 addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
158 // We cannot describe the location of dllimport'd variables: the
159 // computation of their address requires loads from the IAT.
160 if (Global && Global->hasDLLImportStorageClass())
163 // Nothing to describe without address or constant.
164 if (!Global && (!Expr || !Expr->isConstant()))
168 addToAccelTable = true;
169 Loc = new (DIEValueAllocator) DIELoc;
170 DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
174 const MCSymbol *Sym = Asm->getSymbol(Global);
175 if (Global->isThreadLocal()) {
176 if (Asm->TM.Options.EmulatedTLS) {
177 // TODO: add debug info for emulated thread local mode.
179 // FIXME: Make this work with -gsplit-dwarf.
180 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
181 assert((PointerSize == 4 || PointerSize == 8) &&
182 "Add support for other sizes if necessary");
183 // Based on GCC's support for TLS:
184 if (!DD->useSplitDwarf()) {
185 // 1) Start with a constNu of the appropriate pointer size
186 addUInt(*Loc, dwarf::DW_FORM_data1,
187 PointerSize == 4 ? dwarf::DW_OP_const4u
188 : dwarf::DW_OP_const8u);
189 // 2) containing the (relocated) offset of the TLS variable
190 // within the module's TLS block.
191 addExpr(*Loc, dwarf::DW_FORM_udata,
192 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
194 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
195 addUInt(*Loc, dwarf::DW_FORM_udata,
196 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
198 // 3) followed by an OP to make the debugger do a TLS lookup.
199 addUInt(*Loc, dwarf::DW_FORM_data1,
200 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
201 : dwarf::DW_OP_form_tls_address);
204 DD->addArangeLabel(SymbolCU(this, Sym));
205 addOpAddress(*Loc, Sym);
209 DwarfExpr->addFragmentOffset(Expr);
210 DwarfExpr->addExpression(Expr);
214 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
216 if (DD->useAllLinkageNames())
217 addLinkageName(*VariableDIE, GV->getLinkageName());
219 if (addToAccelTable) {
220 DD->addAccelName(GV->getName(), *VariableDIE);
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);
231 void DwarfCompileUnit::addRange(RangeSpan Range) {
232 bool SameAsPrevCU = this == DD->getPrevCU();
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);
245 CURanges.back().setEnd(Range.getEnd());
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,
256 return addSectionDelta(Die, Attribute, Label, Sec);
259 void DwarfCompileUnit::initStmtList() {
260 // Define start line table label for each Compile Unit.
261 MCSymbol *LineTableStartSym =
262 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
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();
271 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
272 TLOF.getDwarfLineSection()->getBeginSymbol());
275 void DwarfCompileUnit::applyStmtList(DIE &D) {
276 D.addValue(DIEValueAllocator, *StmtListValue);
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");
286 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
287 if (DD->getDwarfVersion() < 4)
288 addLabelAddress(D, dwarf::DW_AT_high_pc, End);
290 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
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());
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);
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);
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);
320 // Construct a DIE for this scope.
321 void DwarfCompileUnit::constructScopeDIE(
322 LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
323 if (!Scope || !Scope->getScopeNode())
326 auto *DS = Scope->getScopeNode();
328 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
329 "Only handle inlined subprograms here, use "
330 "constructSubprogramScopeDIE for non-inlined "
333 SmallVector<DIE *, 8> Children;
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.
339 if (Scope->getParent() && isa<DISubprogram>(DS)) {
340 ScopeDIE = constructInlinedScopeDIE(Scope);
343 // We create children when the scope DIE is not null.
344 createScopeChildrenDIE(Scope, Children);
346 // Early exit when we know the scope DIE is going to be null.
347 if (DD->isLexicalScopeDIENull(Scope))
350 unsigned ChildScopeCount;
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);
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])
361 constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
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()));
372 ScopeDIE = constructLexicalScopeDIE(Scope);
373 assert(ScopeDIE && "Scope DIE should not be null.");
377 for (auto &I : Children)
378 ScopeDIE->addChild(std::move(I));
380 FinalChildren.push_back(std::move(ScopeDIE));
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));
392 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
393 SmallVector<RangeSpan, 2> Range) {
394 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
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();
401 RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
403 // Under fission, ranges are specified by constant offsets relative to the
404 // CU's DW_AT_GNU_ranges_base.
406 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
409 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
412 // Add the range list to the set of ranges to be emitted.
413 (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
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());
422 addScopeRangeList(Die, std::move(Ranges));
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));
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.");
446 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
447 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
449 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
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() && DD->getDwarfVersion() >= 4)
457 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
458 IA->getDiscriminator());
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);
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))
473 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
474 if (Scope->isAbstractScope())
477 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
482 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
483 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
484 auto D = constructVariableDIEImpl(DV, Abstract);
489 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
491 // Define variable debug information entry.
492 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
495 applyVariableAttributes(DV, *VariableDie);
499 // Add variable address.
501 unsigned Offset = DV.getDebugLocListIndex();
503 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
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.addFragmentOffset(Expr);
528 DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm());
529 DwarfExpr.addExpression(Expr);
530 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
532 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
533 } else if (DVInsn->getOperand(0).isFPImm())
534 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
535 else if (DVInsn->getOperand(0).isCImm())
536 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
542 // .. else use frame index.
543 if (!DV.hasFrameIndexExprs())
546 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
547 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
548 for (auto &Fragment : DV.getFrameIndexExprs()) {
549 unsigned FrameReg = 0;
550 const DIExpression *Expr = Fragment.Expr;
551 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
552 int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
553 DwarfExpr.addFragmentOffset(Expr);
554 SmallVector<uint64_t, 8> Ops;
555 Ops.push_back(dwarf::DW_OP_plus);
556 Ops.push_back(Offset);
557 Ops.append(Expr->elements_begin(), Expr->elements_end());
558 DIExpressionCursor Cursor(Ops);
559 DwarfExpr.setMemoryLocationKind();
560 DwarfExpr.addMachineRegExpression(
561 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
562 DwarfExpr.addExpression(std::move(Cursor));
564 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
569 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
570 const LexicalScope &Scope,
571 DIE *&ObjectPointer) {
572 auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
573 if (DV.isObjectPointer())
578 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
579 SmallVectorImpl<DIE *> &Children,
580 unsigned *ChildScopeCount) {
581 DIE *ObjectPointer = nullptr;
583 for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
584 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
586 unsigned ChildCountWithoutScopes = Children.size();
588 for (LexicalScope *LS : Scope->getChildren())
589 constructScopeDIE(LS, Children);
592 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
594 return ObjectPointer;
597 void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) {
598 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
601 assert(!Scope->getInlinedAt());
602 assert(!Scope->isAbstractScope());
603 // Collect lexical scope children first.
604 // ObjectPointer might be a local (non-argument) local variable if it's a
605 // block's synthetic this pointer.
606 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
607 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
610 // If this is a variadic function, add an unspecified parameter.
611 DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
613 // If we have a single element of null, it is a function that returns void.
614 // If we have more than one elements and the last one is null, it is a
615 // variadic function.
616 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
617 !includeMinimalInlineScopes())
619 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
622 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
624 // We create children when the scope DIE is not null.
625 SmallVector<DIE *, 8> Children;
626 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
629 for (auto &I : Children)
630 ScopeDIE.addChild(std::move(I));
632 return ObjectPointer;
635 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
636 LexicalScope *Scope) {
637 DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
641 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
645 if (includeMinimalInlineScopes())
646 ContextDIE = &getUnitDie();
647 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
648 // the important distinction that the debug node is not associated with the
649 // DIE (since the debug node will be associated with the concrete DIE, if
650 // any). It could be refactored to some common utility function.
651 else if (auto *SPDecl = SP->getDeclaration()) {
652 ContextDIE = &getUnitDie();
653 getOrCreateSubprogramDIE(SPDecl);
655 ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
657 // Passing null as the associated node because the abstract definition
658 // shouldn't be found by lookup.
659 AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
660 applySubprogramAttributesToDefinition(SP, *AbsDef);
662 if (!includeMinimalInlineScopes())
663 addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
664 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
665 addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
668 DIE *DwarfCompileUnit::constructImportedEntityDIE(
669 const DIImportedEntity *Module) {
670 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
671 insertDIE(Module, IMDie);
673 auto *Entity = resolve(Module->getEntity());
674 if (auto *NS = dyn_cast<DINamespace>(Entity))
675 EntityDie = getOrCreateNameSpace(NS);
676 else if (auto *M = dyn_cast<DIModule>(Entity))
677 EntityDie = getOrCreateModule(M);
678 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
679 EntityDie = getOrCreateSubprogramDIE(SP);
680 else if (auto *T = dyn_cast<DIType>(Entity))
681 EntityDie = getOrCreateTypeDIE(T);
682 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
683 EntityDie = getOrCreateGlobalVariableDIE(GV, {});
685 EntityDie = getDIE(Entity);
687 addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
688 Module->getScope()->getDirectory());
689 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
690 StringRef Name = Module->getName();
692 addString(*IMDie, dwarf::DW_AT_name, Name);
697 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
699 if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
701 // If this subprogram has an abstract definition, reference that
702 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
704 assert(D || includeMinimalInlineScopes());
706 // And attach the attributes
707 applySubprogramAttributesToDefinition(SP, *D);
711 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
712 // Don't bother labeling the .dwo unit, as its offset isn't used.
714 LabelBegin = Asm->createTempSymbol("cu_begin");
715 Asm->OutStreamer->EmitLabel(LabelBegin);
718 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
719 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
720 : dwarf::DW_UT_compile;
721 DwarfUnit::emitCommonHeader(UseOffsets, UT);
724 /// addGlobalName - Add a new global name to the compile unit.
725 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
726 const DIScope *Context) {
727 if (includeMinimalInlineScopes())
729 std::string FullName = getParentContextString(Context) + Name.str();
730 GlobalNames[FullName] = &Die;
733 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
734 const DIScope *Context) {
735 if (includeMinimalInlineScopes())
737 std::string FullName = getParentContextString(Context) + Name.str();
738 // Insert, allowing the entry to remain as-is if it's already present
739 // This way the CU-level type DIE is preferred over the "can't describe this
740 // type as a unit offset because it's not really in the CU at all, it's only
742 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
745 /// Add a new global type to the unit.
746 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
747 const DIScope *Context) {
748 if (includeMinimalInlineScopes())
750 std::string FullName = getParentContextString(Context) + Ty->getName().str();
751 GlobalTypes[FullName] = &Die;
754 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
755 const DIScope *Context) {
756 if (includeMinimalInlineScopes())
758 std::string FullName = getParentContextString(Context) + Ty->getName().str();
759 // Insert, allowing the entry to remain as-is if it's already present
760 // This way the CU-level type DIE is preferred over the "can't describe this
761 // type as a unit offset because it's not really in the CU at all, it's only
763 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
766 /// addVariableAddress - Add DW_AT_location attribute for a
767 /// DbgVariable based on provided MachineLocation.
768 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
769 MachineLocation Location) {
770 if (DV.hasComplexAddress())
771 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
772 else if (DV.isBlockByrefVariable())
773 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
775 addAddress(Die, dwarf::DW_AT_location, Location);
778 /// Add an address attribute to a die based on the location provided.
779 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
780 const MachineLocation &Location) {
781 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
782 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
783 if (Location.isIndirect())
784 DwarfExpr.setMemoryLocationKind();
786 SmallVector<uint64_t, 8> Ops;
787 if (Location.isIndirect() && Location.getOffset()) {
788 Ops.push_back(dwarf::DW_OP_plus);
789 Ops.push_back(Location.getOffset());
791 DIExpressionCursor Cursor(Ops);
792 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
793 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
795 DwarfExpr.addExpression(std::move(Cursor));
797 // Now attach the location information to the DIE.
798 addBlock(Die, Attribute, DwarfExpr.finalize());
801 /// Start with the address based on the location provided, and generate the
802 /// DWARF information necessary to find the actual variable given the extra
803 /// address information encoded in the DbgVariable, starting from the starting
804 /// location. Add the DWARF information to the die.
805 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
806 dwarf::Attribute Attribute,
807 const MachineLocation &Location) {
808 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
809 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
810 const DIExpression *DIExpr = DV.getSingleExpression();
811 DwarfExpr.addFragmentOffset(DIExpr);
812 if (Location.isIndirect())
813 DwarfExpr.setMemoryLocationKind();
815 SmallVector<uint64_t, 8> Ops;
816 if (Location.isIndirect() && Location.getOffset()) {
817 Ops.push_back(dwarf::DW_OP_plus);
818 Ops.push_back(Location.getOffset());
820 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
821 DIExpressionCursor Cursor(Ops);
822 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
823 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
825 DwarfExpr.addExpression(std::move(Cursor));
827 // Now attach the location information to the DIE.
828 addBlock(Die, Attribute, DwarfExpr.finalize());
831 /// Add a Dwarf loclistptr attribute data and value.
832 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
834 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
835 : dwarf::DW_FORM_data4;
836 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
839 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
841 StringRef Name = Var.getName();
843 addString(VariableDie, dwarf::DW_AT_name, Name);
844 const auto *DIVar = Var.getVariable();
846 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
847 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
850 addSourceLine(VariableDie, DIVar);
851 addType(VariableDie, Var.getType());
852 if (Var.isArtificial())
853 addFlag(VariableDie, dwarf::DW_AT_artificial);
856 /// Add a Dwarf expression attribute data and value.
857 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
858 const MCExpr *Expr) {
859 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
862 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
863 const DISubprogram *SP, DIE &SPDie) {
864 auto *SPDecl = SP->getDeclaration();
865 auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
866 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
867 addGlobalName(SP->getName(), SPDie, Context);
870 bool DwarfCompileUnit::isDwoUnit() const {
871 return DD->useSplitDwarf() && Skeleton;
874 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
875 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
876 (DD->useSplitDwarf() && !Skeleton);
878 } // end llvm namespace