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 TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
551 int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
552 DwarfExpr.addFragmentOffset(Fragment.Expr);
553 SmallVector<uint64_t, 8> Ops;
554 Ops.push_back(dwarf::DW_OP_plus);
555 Ops.push_back(Offset);
556 Ops.push_back(dwarf::DW_OP_deref);
557 Ops.append(Fragment.Expr->elements_begin(), Fragment.Expr->elements_end());
558 DIExpressionCursor Expr(Ops);
559 DwarfExpr.addMachineRegExpression(
560 *Asm->MF->getSubtarget().getRegisterInfo(), Expr, FrameReg);
561 DwarfExpr.addExpression(std::move(Expr));
563 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
568 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
569 const LexicalScope &Scope,
570 DIE *&ObjectPointer) {
571 auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
572 if (DV.isObjectPointer())
577 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
578 SmallVectorImpl<DIE *> &Children,
579 unsigned *ChildScopeCount) {
580 DIE *ObjectPointer = nullptr;
582 for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
583 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
585 unsigned ChildCountWithoutScopes = Children.size();
587 for (LexicalScope *LS : Scope->getChildren())
588 constructScopeDIE(LS, Children);
591 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
593 return ObjectPointer;
596 void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) {
597 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
600 assert(!Scope->getInlinedAt());
601 assert(!Scope->isAbstractScope());
602 // Collect lexical scope children first.
603 // ObjectPointer might be a local (non-argument) local variable if it's a
604 // block's synthetic this pointer.
605 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
606 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
609 // If this is a variadic function, add an unspecified parameter.
610 DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
612 // If we have a single element of null, it is a function that returns void.
613 // If we have more than one elements and the last one is null, it is a
614 // variadic function.
615 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
616 !includeMinimalInlineScopes())
618 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
621 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
623 // We create children when the scope DIE is not null.
624 SmallVector<DIE *, 8> Children;
625 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
628 for (auto &I : Children)
629 ScopeDIE.addChild(std::move(I));
631 return ObjectPointer;
634 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
635 LexicalScope *Scope) {
636 DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
640 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
644 if (includeMinimalInlineScopes())
645 ContextDIE = &getUnitDie();
646 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
647 // the important distinction that the debug node is not associated with the
648 // DIE (since the debug node will be associated with the concrete DIE, if
649 // any). It could be refactored to some common utility function.
650 else if (auto *SPDecl = SP->getDeclaration()) {
651 ContextDIE = &getUnitDie();
652 getOrCreateSubprogramDIE(SPDecl);
654 ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
656 // Passing null as the associated node because the abstract definition
657 // shouldn't be found by lookup.
658 AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
659 applySubprogramAttributesToDefinition(SP, *AbsDef);
661 if (!includeMinimalInlineScopes())
662 addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
663 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
664 addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
667 DIE *DwarfCompileUnit::constructImportedEntityDIE(
668 const DIImportedEntity *Module) {
669 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
670 insertDIE(Module, IMDie);
672 auto *Entity = resolve(Module->getEntity());
673 if (auto *NS = dyn_cast<DINamespace>(Entity))
674 EntityDie = getOrCreateNameSpace(NS);
675 else if (auto *M = dyn_cast<DIModule>(Entity))
676 EntityDie = getOrCreateModule(M);
677 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
678 EntityDie = getOrCreateSubprogramDIE(SP);
679 else if (auto *T = dyn_cast<DIType>(Entity))
680 EntityDie = getOrCreateTypeDIE(T);
681 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
682 EntityDie = getOrCreateGlobalVariableDIE(GV, {});
684 EntityDie = getDIE(Entity);
686 addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
687 Module->getScope()->getDirectory());
688 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
689 StringRef Name = Module->getName();
691 addString(*IMDie, dwarf::DW_AT_name, Name);
696 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
698 if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
700 // If this subprogram has an abstract definition, reference that
701 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
703 assert(D || includeMinimalInlineScopes());
705 // And attach the attributes
706 applySubprogramAttributesToDefinition(SP, *D);
710 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
711 // Don't bother labeling the .dwo unit, as its offset isn't used.
713 LabelBegin = Asm->createTempSymbol("cu_begin");
714 Asm->OutStreamer->EmitLabel(LabelBegin);
717 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
718 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
719 : dwarf::DW_UT_compile;
720 DwarfUnit::emitCommonHeader(UseOffsets, UT);
723 /// addGlobalName - Add a new global name to the compile unit.
724 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
725 const DIScope *Context) {
726 if (includeMinimalInlineScopes())
728 std::string FullName = getParentContextString(Context) + Name.str();
729 GlobalNames[FullName] = &Die;
732 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
733 const DIScope *Context) {
734 if (includeMinimalInlineScopes())
736 std::string FullName = getParentContextString(Context) + Name.str();
737 // Insert, allowing the entry to remain as-is if it's already present
738 // This way the CU-level type DIE is preferred over the "can't describe this
739 // type as a unit offset because it's not really in the CU at all, it's only
741 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
744 /// Add a new global type to the unit.
745 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
746 const DIScope *Context) {
747 if (includeMinimalInlineScopes())
749 std::string FullName = getParentContextString(Context) + Ty->getName().str();
750 GlobalTypes[FullName] = &Die;
753 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
754 const DIScope *Context) {
755 if (includeMinimalInlineScopes())
757 std::string FullName = getParentContextString(Context) + Ty->getName().str();
758 // Insert, allowing the entry to remain as-is if it's already present
759 // This way the CU-level type DIE is preferred over the "can't describe this
760 // type as a unit offset because it's not really in the CU at all, it's only
762 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
765 /// addVariableAddress - Add DW_AT_location attribute for a
766 /// DbgVariable based on provided MachineLocation.
767 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
768 MachineLocation Location) {
769 if (DV.hasComplexAddress())
770 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
771 else if (DV.isBlockByrefVariable())
772 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
774 addAddress(Die, dwarf::DW_AT_location, Location);
777 /// Add an address attribute to a die based on the location provided.
778 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
779 const MachineLocation &Location) {
780 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
781 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
783 SmallVector<uint64_t, 8> Ops;
784 if (Location.isIndirect()) {
785 Ops.push_back(dwarf::DW_OP_plus);
786 Ops.push_back(Location.getOffset());
787 Ops.push_back(dwarf::DW_OP_deref);
789 DIExpressionCursor Cursor(Ops);
790 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
791 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
793 DwarfExpr.addExpression(std::move(Cursor));
795 // Now attach the location information to the DIE.
796 addBlock(Die, Attribute, DwarfExpr.finalize());
799 /// Start with the address based on the location provided, and generate the
800 /// DWARF information necessary to find the actual variable given the extra
801 /// address information encoded in the DbgVariable, starting from the starting
802 /// location. Add the DWARF information to the die.
803 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
804 dwarf::Attribute Attribute,
805 const MachineLocation &Location) {
806 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
807 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
808 const DIExpression *DIExpr = DV.getSingleExpression();
809 DwarfExpr.addFragmentOffset(DIExpr);
811 SmallVector<uint64_t, 8> Ops;
812 if (Location.isIndirect()) {
813 Ops.push_back(dwarf::DW_OP_plus);
814 Ops.push_back(Location.getOffset());
815 Ops.push_back(dwarf::DW_OP_deref);
817 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
818 DIExpressionCursor Cursor(Ops);
819 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
820 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
822 DwarfExpr.addExpression(std::move(Cursor));
824 // Now attach the location information to the DIE.
825 addBlock(Die, Attribute, DwarfExpr.finalize());
828 /// Add a Dwarf loclistptr attribute data and value.
829 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
831 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
832 : dwarf::DW_FORM_data4;
833 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
836 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
838 StringRef Name = Var.getName();
840 addString(VariableDie, dwarf::DW_AT_name, Name);
841 const auto *DIVar = Var.getVariable();
843 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
844 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
847 addSourceLine(VariableDie, DIVar);
848 addType(VariableDie, Var.getType());
849 if (Var.isArtificial())
850 addFlag(VariableDie, dwarf::DW_AT_artificial);
853 /// Add a Dwarf expression attribute data and value.
854 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
855 const MCExpr *Expr) {
856 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
859 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
860 const DISubprogram *SP, DIE &SPDie) {
861 auto *SPDecl = SP->getDeclaration();
862 auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
863 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
864 addGlobalName(SP->getName(), SPDie, Context);
867 bool DwarfCompileUnit::isDwoUnit() const {
868 return DD->useSplitDwarf() && Skeleton;
871 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
872 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
873 (DD->useSplitDwarf() && !Skeleton);
875 } // end llvm namespace