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