1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and 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 "DwarfUnit.h"
15 #include "AddressPool.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/MC/MachineLocation.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCDwarf.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
46 #define DEBUG_TYPE "dwarfdebug"
49 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
50 cl::desc("Generate DWARF4 type units."),
53 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
55 : DwarfExpression(AP.getDwarfVersion()), AP(AP), DU(DU),
58 void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
59 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
62 void DIEDwarfExpression::emitSigned(int64_t Value) {
63 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
66 void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
67 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
70 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
71 unsigned MachineReg) {
72 return MachineReg == TRI.getFrameRegister(*AP.MF);
75 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
76 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
77 : DIEUnit(A->getDwarfVersion(), A->MAI->getCodePointerSize(), UnitTag),
78 CUNode(Node), Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) {
81 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
82 DwarfDebug *DW, DwarfFile *DWU,
83 MCDwarfDwoLineTable *SplitLineTable)
84 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
85 SplitLineTable(SplitLineTable) {
87 addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
90 DwarfUnit::~DwarfUnit() {
91 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
92 DIEBlocks[j]->~DIEBlock();
93 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
94 DIELocs[j]->~DIELoc();
97 int64_t DwarfUnit::getDefaultLowerBound() const {
98 switch (getLanguage()) {
102 // The languages below have valid values in all DWARF versions.
103 case dwarf::DW_LANG_C:
104 case dwarf::DW_LANG_C89:
105 case dwarf::DW_LANG_C_plus_plus:
108 case dwarf::DW_LANG_Fortran77:
109 case dwarf::DW_LANG_Fortran90:
112 // The languages below have valid values only if the DWARF version >= 3.
113 case dwarf::DW_LANG_C99:
114 case dwarf::DW_LANG_ObjC:
115 case dwarf::DW_LANG_ObjC_plus_plus:
116 if (DD->getDwarfVersion() >= 3)
120 case dwarf::DW_LANG_Fortran95:
121 if (DD->getDwarfVersion() >= 3)
125 // Starting with DWARF v4, all defined languages have valid values.
126 case dwarf::DW_LANG_D:
127 case dwarf::DW_LANG_Java:
128 case dwarf::DW_LANG_Python:
129 case dwarf::DW_LANG_UPC:
130 if (DD->getDwarfVersion() >= 4)
134 case dwarf::DW_LANG_Ada83:
135 case dwarf::DW_LANG_Ada95:
136 case dwarf::DW_LANG_Cobol74:
137 case dwarf::DW_LANG_Cobol85:
138 case dwarf::DW_LANG_Modula2:
139 case dwarf::DW_LANG_Pascal83:
140 case dwarf::DW_LANG_PLI:
141 if (DD->getDwarfVersion() >= 4)
145 // The languages below are new in DWARF v5.
146 case dwarf::DW_LANG_BLISS:
147 case dwarf::DW_LANG_C11:
148 case dwarf::DW_LANG_C_plus_plus_03:
149 case dwarf::DW_LANG_C_plus_plus_11:
150 case dwarf::DW_LANG_C_plus_plus_14:
151 case dwarf::DW_LANG_Dylan:
152 case dwarf::DW_LANG_Go:
153 case dwarf::DW_LANG_Haskell:
154 case dwarf::DW_LANG_OCaml:
155 case dwarf::DW_LANG_OpenCL:
156 case dwarf::DW_LANG_RenderScript:
157 case dwarf::DW_LANG_Rust:
158 case dwarf::DW_LANG_Swift:
159 if (DD->getDwarfVersion() >= 5)
163 case dwarf::DW_LANG_Fortran03:
164 case dwarf::DW_LANG_Fortran08:
165 case dwarf::DW_LANG_Julia:
166 case dwarf::DW_LANG_Modula3:
167 if (DD->getDwarfVersion() >= 5)
175 /// Check whether the DIE for this MDNode can be shared across CUs.
176 static bool isShareableAcrossCUs(const DINode *D) {
177 // When the MDNode can be part of the type system, the DIE can be shared
179 // Combining type units and cross-CU DIE sharing is lower value (since
180 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
181 // level already) but may be implementable for some value in projects
182 // building multiple independent libraries with LTO and then linking those
184 return (isa<DIType>(D) ||
185 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
186 !GenerateDwarfTypeUnits;
189 DIE *DwarfUnit::getDIE(const DINode *D) const {
190 if (isShareableAcrossCUs(D))
191 return DU->getDIE(D);
192 return MDNodeToDieMap.lookup(D);
195 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
196 if (isShareableAcrossCUs(Desc)) {
197 DU->insertDIE(Desc, D);
200 MDNodeToDieMap.insert(std::make_pair(Desc, D));
203 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
204 if (DD->getDwarfVersion() >= 4)
205 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
208 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
212 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
213 Optional<dwarf::Form> Form, uint64_t Integer) {
215 Form = DIEInteger::BestForm(false, Integer);
216 assert(Form != dwarf::DW_FORM_implicit_const &&
217 "DW_FORM_implicit_const is used only for signed integers");
218 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
221 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
223 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
226 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
227 Optional<dwarf::Form> Form, int64_t Integer) {
229 Form = DIEInteger::BestForm(true, Integer);
230 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
233 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
235 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
238 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
240 Die.addValue(DIEValueAllocator, Attribute,
241 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
242 DIEString(DU->getStringPool().getEntry(*Asm, String)));
245 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
246 dwarf::Attribute Attribute,
248 const MCSymbol *Label) {
249 return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
252 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
253 addLabel(Die, (dwarf::Attribute)0, Form, Label);
256 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
258 if (DD->getDwarfVersion() >= 4)
259 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
261 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
264 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
265 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
266 : getCU().getOrCreateSourceID(FileName, DirName);
269 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
270 if (!DD->useSplitDwarf()) {
271 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
272 addLabel(Die, dwarf::DW_FORM_udata, Sym);
274 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
275 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
276 DD->getAddressPool().getIndex(Sym));
280 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
281 const MCSymbol *Hi, const MCSymbol *Lo) {
282 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
283 new (DIEValueAllocator) DIEDelta(Hi, Lo));
286 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
287 addDIEEntry(Die, Attribute, DIEEntry(Entry));
290 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
291 // Flag the type unit reference as a declaration so that if it contains
292 // members (implicit special members, static data member definitions, member
293 // declarations for definitions in this CU, etc) consumers don't get confused
294 // and think this is a full definition.
295 addFlag(Die, dwarf::DW_AT_declaration);
297 Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
298 dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
301 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
303 const DIEUnit *CU = Die.getUnit();
304 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
306 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
307 CU = getUnitDie().getUnit();
309 EntryCU = getUnitDie().getUnit();
310 Die.addValue(DIEValueAllocator, Attribute,
311 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
315 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
316 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
322 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
323 Loc->ComputeSize(Asm);
324 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
325 Die.addValue(DIEValueAllocator, Attribute,
326 Loc->BestForm(DD->getDwarfVersion()), Loc);
329 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
331 Block->ComputeSize(Asm);
332 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
333 Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
336 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
337 StringRef Directory) {
341 unsigned FileID = getOrCreateSourceID(File, Directory);
342 assert(FileID && "Invalid file id");
343 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
344 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
347 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
350 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
351 V->getScope()->getDirectory());
354 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
357 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
360 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
363 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
366 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
369 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
372 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
375 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
378 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
379 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
380 gives the variable VarName either the struct, or a pointer to the struct, as
381 its type. This is necessary for various behind-the-scenes things the
382 compiler needs to do with by-reference variables in Blocks.
384 However, as far as the original *programmer* is concerned, the variable
385 should still have type 'SomeType', as originally declared.
387 The function getBlockByrefType dives into the __Block_byref_x_VarName
388 struct to find the original type of the variable, which is then assigned to
389 the variable's Debug Information Entry as its real type. So far, so good.
390 However now the debugger will expect the variable VarName to have the type
391 SomeType. So we need the location attribute for the variable to be an
392 expression that explains to the debugger how to navigate through the
393 pointers and struct to find the actual variable of type SomeType.
395 The following function does just that. We start by getting
396 the "normal" location for the variable. This will be the location
397 of either the struct __Block_byref_x_VarName or the pointer to the
398 struct __Block_byref_x_VarName.
400 The struct will look something like:
402 struct __Block_byref_x_VarName {
404 struct __Block_byref_x_VarName *forwarding;
405 ... <various other fields>
407 ... <maybe more fields>
410 If we are given the struct directly (as our starting point) we
411 need to tell the debugger to:
413 1). Add the offset of the forwarding field.
415 2). Follow that pointer to get the real __Block_byref_x_VarName
416 struct to use (the real one may have been copied onto the heap).
418 3). Add the offset for the field VarName, to find the actual variable.
420 If we started with a pointer to the struct, then we need to
421 dereference that pointer first, before the other steps.
422 Translating this into DWARF ops, we will need to append the following
423 to the current location description for the variable:
425 DW_OP_deref -- optional, if we start with a pointer
426 DW_OP_plus_uconst <forward_fld_offset>
428 DW_OP_plus_uconst <varName_fld_offset>
430 That is what this function does. */
432 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
433 dwarf::Attribute Attribute,
434 const MachineLocation &Location) {
435 const DIType *Ty = DV.getType();
436 const DIType *TmpTy = Ty;
437 uint16_t Tag = Ty->getTag();
438 bool isPointer = false;
440 StringRef varName = DV.getName();
442 if (Tag == dwarf::DW_TAG_pointer_type) {
443 auto *DTy = cast<DIDerivedType>(Ty);
444 TmpTy = resolve(DTy->getBaseType());
448 // Find the __forwarding field and the variable field in the __Block_byref
450 DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
451 const DIDerivedType *varField = nullptr;
452 const DIDerivedType *forwardingField = nullptr;
454 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
455 auto *DT = cast<DIDerivedType>(Fields[i]);
456 StringRef fieldName = DT->getName();
457 if (fieldName == "__forwarding")
458 forwardingField = DT;
459 else if (fieldName == varName)
463 // Get the offsets for the forwarding field and the variable field.
464 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
465 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
467 // Decode the original location, and use that as the start of the byref
468 // variable's location.
469 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
470 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
471 if (Location.isIndirect())
472 DwarfExpr.setMemoryLocationKind();
474 SmallVector<uint64_t, 9> Ops;
475 if (Location.isIndirect() && Location.getOffset()) {
476 Ops.push_back(dwarf::DW_OP_plus);
477 Ops.push_back(Location.getOffset());
479 // If we started with a pointer to the __Block_byref... struct, then
480 // the first thing we need to do is dereference the pointer (DW_OP_deref).
482 Ops.push_back(dwarf::DW_OP_deref);
484 // Next add the offset for the '__forwarding' field:
485 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
486 // adding the offset if it's 0.
487 if (forwardingFieldOffset > 0) {
488 Ops.push_back(dwarf::DW_OP_plus);
489 Ops.push_back(forwardingFieldOffset);
492 // Now dereference the __forwarding field to get to the real __Block_byref
493 // struct: DW_OP_deref.
494 Ops.push_back(dwarf::DW_OP_deref);
496 // Now that we've got the real __Block_byref... struct, add the offset
497 // for the variable's field to get to the location of the actual variable:
498 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
499 if (varFieldOffset > 0) {
500 Ops.push_back(dwarf::DW_OP_plus);
501 Ops.push_back(varFieldOffset);
504 DIExpressionCursor Cursor(Ops);
505 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
506 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
508 DwarfExpr.addExpression(std::move(Cursor));
510 // Now attach the location information to the DIE.
511 addBlock(Die, Attribute, DwarfExpr.finalize());
514 /// Return true if type encoding is unsigned.
515 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
516 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
517 // FIXME: Enums without a fixed underlying type have unknown signedness
518 // here, leading to incorrectly emitted constants.
519 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
522 // (Pieces of) aggregate types that get hacked apart by SROA may be
523 // represented by a constant. Encode them as unsigned bytes.
527 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
528 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
529 // Encode pointer constants as unsigned bytes. This is used at least for
530 // null pointer constant emission.
531 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
532 // here, but accept them for now due to a bug in SROA producing bogus
534 if (T == dwarf::DW_TAG_pointer_type ||
535 T == dwarf::DW_TAG_ptr_to_member_type ||
536 T == dwarf::DW_TAG_reference_type ||
537 T == dwarf::DW_TAG_rvalue_reference_type)
539 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
540 T == dwarf::DW_TAG_volatile_type ||
541 T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
542 DITypeRef Deriv = DTy->getBaseType();
543 assert(Deriv && "Expected valid base type");
544 return isUnsignedDIType(DD, DD->resolve(Deriv));
547 auto *BTy = cast<DIBasicType>(Ty);
548 unsigned Encoding = BTy->getEncoding();
549 assert((Encoding == dwarf::DW_ATE_unsigned ||
550 Encoding == dwarf::DW_ATE_unsigned_char ||
551 Encoding == dwarf::DW_ATE_signed ||
552 Encoding == dwarf::DW_ATE_signed_char ||
553 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
554 Encoding == dwarf::DW_ATE_boolean ||
555 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
556 Ty->getName() == "decltype(nullptr)")) &&
557 "Unsupported encoding");
558 return Encoding == dwarf::DW_ATE_unsigned ||
559 Encoding == dwarf::DW_ATE_unsigned_char ||
560 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
561 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
564 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
565 assert(MO.isFPImm() && "Invalid machine operand!");
566 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
567 APFloat FPImm = MO.getFPImm()->getValueAPF();
569 // Get the raw data form of the floating point.
570 const APInt FltVal = FPImm.bitcastToAPInt();
571 const char *FltPtr = (const char *)FltVal.getRawData();
573 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
574 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
575 int Incr = (LittleEndian ? 1 : -1);
576 int Start = (LittleEndian ? 0 : NumBytes - 1);
577 int Stop = (LittleEndian ? NumBytes : -1);
579 // Output the constant to DWARF one byte at a time.
580 for (; Start != Stop; Start += Incr)
581 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
583 addBlock(Die, dwarf::DW_AT_const_value, Block);
586 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
587 // Pass this down to addConstantValue as an unsigned bag of bits.
588 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
591 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
593 addConstantValue(Die, CI->getValue(), Ty);
596 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
598 assert(MO.isImm() && "Invalid machine operand!");
600 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
603 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
604 // FIXME: This is a bit conservative/simple - it emits negative values always
605 // sign extended to 64 bits rather than minimizing the number of bytes.
606 addUInt(Die, dwarf::DW_AT_const_value,
607 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
610 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
611 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
614 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
615 unsigned CIBitWidth = Val.getBitWidth();
616 if (CIBitWidth <= 64) {
617 addConstantValue(Die, Unsigned,
618 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
622 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
624 // Get the raw data form of the large APInt.
625 const uint64_t *Ptr64 = Val.getRawData();
627 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
628 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
630 // Output the constant to DWARF one byte at a time.
631 for (int i = 0; i < NumBytes; i++) {
634 c = Ptr64[i / 8] >> (8 * (i & 7));
636 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
637 addUInt(*Block, dwarf::DW_FORM_data1, c);
640 addBlock(Die, dwarf::DW_AT_const_value, Block);
643 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
644 if (!LinkageName.empty())
646 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
647 : dwarf::DW_AT_MIPS_linkage_name,
648 GlobalValue::getRealLinkageName(LinkageName));
651 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
652 // Add template parameters.
653 for (const auto *Element : TParams) {
654 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
655 constructTemplateTypeParameterDIE(Buffer, TTP);
656 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
657 constructTemplateValueParameterDIE(Buffer, TVP);
661 /// Add thrown types.
662 void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
663 for (const auto *Ty : ThrownTypes) {
664 DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
665 addType(TT, cast<DIType>(Ty));
669 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
670 if (!Context || isa<DIFile>(Context))
671 return &getUnitDie();
672 if (auto *T = dyn_cast<DIType>(Context))
673 return getOrCreateTypeDIE(T);
674 if (auto *NS = dyn_cast<DINamespace>(Context))
675 return getOrCreateNameSpace(NS);
676 if (auto *SP = dyn_cast<DISubprogram>(Context))
677 return getOrCreateSubprogramDIE(SP);
678 if (auto *M = dyn_cast<DIModule>(Context))
679 return getOrCreateModule(M);
680 return getDIE(Context);
683 DIE *DwarfTypeUnit::createTypeDIE(const DICompositeType *Ty) {
684 auto *Context = resolve(Ty->getScope());
685 DIE *ContextDIE = getOrCreateContextDIE(Context);
687 if (DIE *TyDIE = getDIE(Ty))
691 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
693 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
695 updateAcceleratorTables(Context, Ty, TyDIE);
699 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
703 auto *Ty = cast<DIType>(TyNode);
705 // DW_TAG_restrict_type is not supported in DWARF2
706 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
707 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
709 // DW_TAG_atomic_type is not supported in DWARF < 5
710 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
711 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
713 // Construct the context before querying for the existence of the DIE in case
714 // such construction creates the DIE.
715 auto *Context = resolve(Ty->getScope());
716 DIE *ContextDIE = getOrCreateContextDIE(Context);
719 if (DIE *TyDIE = getDIE(Ty))
723 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
725 updateAcceleratorTables(Context, Ty, TyDIE);
727 if (auto *BT = dyn_cast<DIBasicType>(Ty))
728 constructTypeDIE(TyDIE, BT);
729 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
730 constructTypeDIE(TyDIE, STy);
731 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
732 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
733 if (MDString *TypeId = CTy->getRawIdentifier()) {
734 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
735 // Skip updating the accelerator tables since this is not the full type.
738 constructTypeDIE(TyDIE, CTy);
740 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
746 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
747 const DIType *Ty, const DIE &TyDIE) {
748 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
749 bool IsImplementation = false;
750 if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
751 // A runtime language of 0 actually means C/C++ and that any
752 // non-negative value is some version of Objective-C/C++.
753 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
755 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
756 DD->addAccelType(Ty->getName(), TyDIE, Flags);
758 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
759 isa<DINamespace>(Context))
760 addGlobalType(Ty, TyDIE, Context);
764 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
765 dwarf::Attribute Attribute) {
766 assert(Ty && "Trying to add a type that doesn't exist?");
767 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
770 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
774 // FIXME: Decide whether to implement this for non-C++ languages.
775 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
779 SmallVector<const DIScope *, 1> Parents;
780 while (!isa<DICompileUnit>(Context)) {
781 Parents.push_back(Context);
782 if (Context->getScope())
783 Context = resolve(Context->getScope());
785 // Structure, etc types will have a NULL context if they're at the top
790 // Reverse iterate over our list to go from the outermost construct to the
792 for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
793 StringRef Name = Ctx->getName();
794 if (Name.empty() && isa<DINamespace>(Ctx))
795 Name = "(anonymous namespace)";
804 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
805 // Get core information.
806 StringRef Name = BTy->getName();
807 // Add name if not anonymous or intermediate type.
809 addString(Buffer, dwarf::DW_AT_name, Name);
811 // An unspecified type only has a name attribute.
812 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
815 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
818 uint64_t Size = BTy->getSizeInBits() >> 3;
819 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
822 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
823 // Get core information.
824 StringRef Name = DTy->getName();
825 uint64_t Size = DTy->getSizeInBits() >> 3;
826 uint16_t Tag = Buffer.getTag();
828 // Map to main type, void will not have a type.
829 const DIType *FromTy = resolve(DTy->getBaseType());
831 addType(Buffer, FromTy);
833 // Add name if not anonymous or intermediate type.
835 addString(Buffer, dwarf::DW_AT_name, Name);
837 // Add size if non-zero (derived types might be zero-sized.)
838 if (Size && Tag != dwarf::DW_TAG_pointer_type
839 && Tag != dwarf::DW_TAG_ptr_to_member_type
840 && Tag != dwarf::DW_TAG_reference_type
841 && Tag != dwarf::DW_TAG_rvalue_reference_type)
842 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
844 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
846 Buffer, dwarf::DW_AT_containing_type,
847 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
848 // Add source line info if available and TyDesc is not a forward declaration.
849 if (!DTy->isForwardDecl())
850 addSourceLine(Buffer, DTy);
852 // If DWARF address space value is other than None, add it for pointer and
853 // reference types as DW_AT_address_class.
854 if (DTy->getDWARFAddressSpace() && (Tag == dwarf::DW_TAG_pointer_type ||
855 Tag == dwarf::DW_TAG_reference_type))
856 addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
857 DTy->getDWARFAddressSpace().getValue());
860 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
861 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
862 const DIType *Ty = resolve(Args[i]);
864 assert(i == N-1 && "Unspecified parameter must be the last argument");
865 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
867 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
869 if (Ty->isArtificial())
870 addFlag(Arg, dwarf::DW_AT_artificial);
875 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
876 // Add return type. A void return won't have a type.
877 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
879 if (auto RTy = resolve(Elements[0]))
880 addType(Buffer, RTy);
882 bool isPrototyped = true;
883 if (Elements.size() == 2 && !Elements[1])
884 isPrototyped = false;
886 constructSubprogramArguments(Buffer, Elements);
888 // Add prototype flag if we're dealing with a C language and the function has
890 uint16_t Language = getLanguage();
892 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
893 Language == dwarf::DW_LANG_ObjC))
894 addFlag(Buffer, dwarf::DW_AT_prototyped);
896 // Add a DW_AT_calling_convention if this has an explicit convention.
897 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
898 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
901 if (CTy->isLValueReference())
902 addFlag(Buffer, dwarf::DW_AT_reference);
904 if (CTy->isRValueReference())
905 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
908 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
909 // Add name if not anonymous or intermediate type.
910 StringRef Name = CTy->getName();
912 uint64_t Size = CTy->getSizeInBits() >> 3;
913 uint16_t Tag = Buffer.getTag();
916 case dwarf::DW_TAG_array_type:
917 constructArrayTypeDIE(Buffer, CTy);
919 case dwarf::DW_TAG_enumeration_type:
920 constructEnumTypeDIE(Buffer, CTy);
922 case dwarf::DW_TAG_structure_type:
923 case dwarf::DW_TAG_union_type:
924 case dwarf::DW_TAG_class_type: {
925 // Add elements to structure type.
926 DINodeArray Elements = CTy->getElements();
927 for (const auto *Element : Elements) {
930 if (auto *SP = dyn_cast<DISubprogram>(Element))
931 getOrCreateSubprogramDIE(SP);
932 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
933 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
934 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
935 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
936 } else if (DDTy->isStaticMember()) {
937 getOrCreateStaticMemberDIE(DDTy);
939 constructMemberDIE(Buffer, DDTy);
941 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
942 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
943 StringRef PropertyName = Property->getName();
944 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
945 if (Property->getType())
946 addType(ElemDie, resolve(Property->getType()));
947 addSourceLine(ElemDie, Property);
948 StringRef GetterName = Property->getGetterName();
949 if (!GetterName.empty())
950 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
951 StringRef SetterName = Property->getSetterName();
952 if (!SetterName.empty())
953 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
954 if (unsigned PropertyAttributes = Property->getAttributes())
955 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
960 if (CTy->isAppleBlockExtension())
961 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
963 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
964 // inside C++ composite types to point to the base class with the vtable.
965 if (auto *ContainingType =
966 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
967 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
968 *getOrCreateTypeDIE(ContainingType));
970 if (CTy->isObjcClassComplete())
971 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
973 // Add template parameters to a class, structure or union types.
974 // FIXME: The support isn't in the metadata for this yet.
975 if (Tag == dwarf::DW_TAG_class_type ||
976 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
977 addTemplateParams(Buffer, CTy->getTemplateParams());
985 // Add name if not anonymous or intermediate type.
987 addString(Buffer, dwarf::DW_AT_name, Name);
989 if (Tag == dwarf::DW_TAG_enumeration_type ||
990 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
991 Tag == dwarf::DW_TAG_union_type) {
992 // Add size if non-zero (derived types might be zero-sized.)
993 // TODO: Do we care about size for enum forward declarations?
995 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
996 else if (!CTy->isForwardDecl())
997 // Add zero size if it is not a forward declaration.
998 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1000 // If we're a forward decl, say so.
1001 if (CTy->isForwardDecl())
1002 addFlag(Buffer, dwarf::DW_AT_declaration);
1004 // Add source line info if available.
1005 if (!CTy->isForwardDecl())
1006 addSourceLine(Buffer, CTy);
1008 // No harm in adding the runtime language to the declaration.
1009 unsigned RLang = CTy->getRuntimeLang();
1011 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1014 // Add align info if available.
1015 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1016 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1021 void DwarfUnit::constructTemplateTypeParameterDIE(
1022 DIE &Buffer, const DITemplateTypeParameter *TP) {
1024 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1025 // Add the type if it exists, it could be void and therefore no type.
1027 addType(ParamDIE, resolve(TP->getType()));
1028 if (!TP->getName().empty())
1029 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1032 void DwarfUnit::constructTemplateValueParameterDIE(
1033 DIE &Buffer, const DITemplateValueParameter *VP) {
1034 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1036 // Add the type if there is one, template template and template parameter
1037 // packs will not have a type.
1038 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1039 addType(ParamDIE, resolve(VP->getType()));
1040 if (!VP->getName().empty())
1041 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1042 if (Metadata *Val = VP->getValue()) {
1043 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1044 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1045 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1046 // We cannot describe the location of dllimport'd entities: the
1047 // computation of their address requires loads from the IAT.
1048 if (!GV->hasDLLImportStorageClass()) {
1049 // For declaration non-type template parameters (such as global values
1051 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1052 addOpAddress(*Loc, Asm->getSymbol(GV));
1053 // Emit DW_OP_stack_value to use the address as the immediate value of
1054 // the parameter, rather than a pointer to it.
1055 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1056 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1058 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1059 assert(isa<MDString>(Val));
1060 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1061 cast<MDString>(Val)->getString());
1062 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1063 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1068 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1069 // Construct the context before querying for the existence of the DIE in case
1070 // such construction creates the DIE.
1071 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1073 if (DIE *NDie = getDIE(NS))
1075 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1077 StringRef Name = NS->getName();
1079 addString(NDie, dwarf::DW_AT_name, NS->getName());
1081 Name = "(anonymous namespace)";
1082 DD->addAccelNamespace(Name, NDie);
1083 addGlobalName(Name, NDie, NS->getScope());
1084 if (NS->getExportSymbols())
1085 addFlag(NDie, dwarf::DW_AT_export_symbols);
1089 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1090 // Construct the context before querying for the existence of the DIE in case
1091 // such construction creates the DIE.
1092 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1094 if (DIE *MDie = getDIE(M))
1096 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1098 if (!M->getName().empty()) {
1099 addString(MDie, dwarf::DW_AT_name, M->getName());
1100 addGlobalName(M->getName(), MDie, M->getScope());
1102 if (!M->getConfigurationMacros().empty())
1103 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1104 M->getConfigurationMacros());
1105 if (!M->getIncludePath().empty())
1106 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1107 if (!M->getISysRoot().empty())
1108 addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1113 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1114 // Construct the context before querying for the existence of the DIE in case
1115 // such construction creates the DIE (as is the case for member function
1118 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1120 if (DIE *SPDie = getDIE(SP))
1123 if (auto *SPDecl = SP->getDeclaration()) {
1125 // Add subprogram definitions to the CU die directly.
1126 ContextDIE = &getUnitDie();
1127 // Build the decl now to ensure it precedes the definition.
1128 getOrCreateSubprogramDIE(SPDecl);
1132 // DW_TAG_inlined_subroutine may refer to this DIE.
1133 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1135 // Stop here and fill this in later, depending on whether or not this
1136 // subprogram turns out to have inlined instances or not.
1137 if (SP->isDefinition())
1140 applySubprogramAttributes(SP, SPDie);
1144 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1146 DIE *DeclDie = nullptr;
1147 StringRef DeclLinkageName;
1148 if (auto *SPDecl = SP->getDeclaration()) {
1149 DeclDie = getDIE(SPDecl);
1150 assert(DeclDie && "This DIE should've already been constructed when the "
1151 "definition DIE was created in "
1152 "getOrCreateSubprogramDIE");
1153 // Look at the Decl's linkage name only if we emitted it.
1154 if (DD->useAllLinkageNames())
1155 DeclLinkageName = SPDecl->getLinkageName();
1157 getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1158 unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1159 if (DeclID != DefID)
1160 addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1162 if (SP->getLine() != SPDecl->getLine())
1163 addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1166 // Add function template parameters.
1167 addTemplateParams(SPDie, SP->getTemplateParams());
1169 // Add the linkage name if we have one and it isn't in the Decl.
1170 StringRef LinkageName = SP->getLinkageName();
1171 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1172 LinkageName == DeclLinkageName) &&
1173 "decl has a linkage name and it is different");
1174 if (DeclLinkageName.empty() &&
1175 // Always emit it for abstract subprograms.
1176 (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1177 addLinkageName(SPDie, LinkageName);
1182 // Refer to the function declaration where all the other attributes will be
1184 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1188 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1189 bool SkipSPAttributes) {
1190 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1191 // and its source location.
1192 bool SkipSPSourceLocation = SkipSPAttributes &&
1193 !CUNode->getDebugInfoForProfiling();
1194 if (!SkipSPSourceLocation)
1195 if (applySubprogramDefinitionAttributes(SP, SPDie))
1198 // Constructors and operators for anonymous aggregates do not have names.
1199 if (!SP->getName().empty())
1200 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1202 if (!SkipSPSourceLocation)
1203 addSourceLine(SPDie, SP);
1205 // Skip the rest of the attributes under -gmlt to save space.
1206 if (SkipSPAttributes)
1209 // Add the prototype if we have a prototype and we have a C like
1211 uint16_t Language = getLanguage();
1212 if (SP->isPrototyped() &&
1213 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1214 Language == dwarf::DW_LANG_ObjC))
1215 addFlag(SPDie, dwarf::DW_AT_prototyped);
1218 DITypeRefArray Args;
1219 if (const DISubroutineType *SPTy = SP->getType()) {
1220 Args = SPTy->getTypeArray();
1224 // Add a DW_AT_calling_convention if this has an explicit convention.
1225 if (CC && CC != dwarf::DW_CC_normal)
1226 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1228 // Add a return type. If this is a type like a C/C++ void type we don't add a
1231 if (auto Ty = resolve(Args[0]))
1234 unsigned VK = SP->getVirtuality();
1236 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1237 if (SP->getVirtualIndex() != -1u) {
1238 DIELoc *Block = getDIELoc();
1239 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1240 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1241 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1243 ContainingTypeMap.insert(
1244 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1247 if (!SP->isDefinition()) {
1248 addFlag(SPDie, dwarf::DW_AT_declaration);
1250 // Add arguments. Do not add arguments for subprogram definition. They will
1251 // be handled while processing variables.
1252 constructSubprogramArguments(SPDie, Args);
1255 addThrownTypes(SPDie, SP->getThrownTypes());
1257 if (SP->isArtificial())
1258 addFlag(SPDie, dwarf::DW_AT_artificial);
1260 if (!SP->isLocalToUnit())
1261 addFlag(SPDie, dwarf::DW_AT_external);
1263 if (DD->useAppleExtensionAttributes()) {
1264 if (SP->isOptimized())
1265 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1267 if (unsigned isa = Asm->getISAEncoding())
1268 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1271 if (SP->isLValueReference())
1272 addFlag(SPDie, dwarf::DW_AT_reference);
1274 if (SP->isRValueReference())
1275 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1277 if (SP->isNoReturn())
1278 addFlag(SPDie, dwarf::DW_AT_noreturn);
1280 if (SP->isProtected())
1281 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1282 dwarf::DW_ACCESS_protected);
1283 else if (SP->isPrivate())
1284 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1285 dwarf::DW_ACCESS_private);
1286 else if (SP->isPublic())
1287 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1288 dwarf::DW_ACCESS_public);
1290 if (SP->isExplicit())
1291 addFlag(SPDie, dwarf::DW_AT_explicit);
1293 if (SP->isMainSubprogram())
1294 addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1297 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1299 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1300 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1302 // The LowerBound value defines the lower bounds which is typically zero for
1303 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1304 // Count == -1 then the array is unbounded and we do not emit
1305 // DW_AT_lower_bound and DW_AT_count attributes.
1306 int64_t LowerBound = SR->getLowerBound();
1307 int64_t DefaultLowerBound = getDefaultLowerBound();
1308 int64_t Count = SR->getCount();
1310 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1311 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1314 // FIXME: An unbounded array should reference the expression that defines
1316 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1319 DIE *DwarfUnit::getIndexTyDie() {
1322 // Construct an integer type to use for indexes.
1323 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1324 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1325 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1326 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1327 dwarf::DW_ATE_unsigned);
1331 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1332 if (CTy->isVector())
1333 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1335 // Emit the element type.
1336 addType(Buffer, resolve(CTy->getBaseType()));
1338 // Get an anonymous type for index type.
1339 // FIXME: This type should be passed down from the front end
1340 // as different languages may have different sizes for indexes.
1341 DIE *IdxTy = getIndexTyDie();
1343 // Add subranges to array type.
1344 DINodeArray Elements = CTy->getElements();
1345 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1346 // FIXME: Should this really be such a loose cast?
1347 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1348 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1349 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1353 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1354 DINodeArray Elements = CTy->getElements();
1356 // Add enumerators to enumeration type.
1357 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1358 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1360 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1361 StringRef Name = Enum->getName();
1362 addString(Enumerator, dwarf::DW_AT_name, Name);
1363 int64_t Value = Enum->getValue();
1364 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1368 const DIType *DTy = resolve(CTy->getBaseType());
1370 addType(Buffer, DTy);
1371 addFlag(Buffer, dwarf::DW_AT_enum_class);
1375 void DwarfUnit::constructContainingTypeDIEs() {
1376 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1378 DIE &SPDie = *CI->first;
1379 const DINode *D = CI->second;
1382 DIE *NDie = getDIE(D);
1385 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1389 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1390 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1391 StringRef Name = DT->getName();
1393 addString(MemberDie, dwarf::DW_AT_name, Name);
1395 addType(MemberDie, resolve(DT->getBaseType()));
1397 addSourceLine(MemberDie, DT);
1399 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1401 // For C++, virtual base classes are not at fixed offset. Use following
1402 // expression to extract appropriate offset from vtable.
1403 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1405 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1406 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1407 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1408 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1409 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1410 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1411 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1412 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1414 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1416 uint64_t Size = DT->getSizeInBits();
1417 uint64_t FieldSize = DD->getBaseTypeSize(DT);
1418 uint32_t AlignInBytes = DT->getAlignInBytes();
1419 uint64_t OffsetInBytes;
1421 bool IsBitfield = FieldSize && Size != FieldSize;
1423 // Handle bitfield, assume bytes are 8 bits.
1424 if (DD->useDWARF2Bitfields())
1425 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1426 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1428 uint64_t Offset = DT->getOffsetInBits();
1429 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1430 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1431 // which can't be done with bitfields. Thus we use FieldSize here.
1432 uint32_t AlignInBits = FieldSize;
1433 uint32_t AlignMask = ~(AlignInBits - 1);
1434 // The bits from the start of the storage unit to the start of the field.
1435 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1436 // The byte offset of the field's aligned storage unit inside the struct.
1437 OffsetInBytes = (Offset - StartBitOffset) / 8;
1439 if (DD->useDWARF2Bitfields()) {
1440 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1441 uint64_t FieldOffset = (HiMark - FieldSize);
1442 Offset -= FieldOffset;
1444 // Maybe we need to work from the other end.
1445 if (Asm->getDataLayout().isLittleEndian())
1446 Offset = FieldSize - (Offset + Size);
1448 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1449 OffsetInBytes = FieldOffset >> 3;
1451 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1454 // This is not a bitfield.
1455 OffsetInBytes = DT->getOffsetInBits() / 8;
1457 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1461 if (DD->getDwarfVersion() <= 2) {
1462 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1463 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1464 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1465 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1466 } else if (!IsBitfield || DD->useDWARF2Bitfields())
1467 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1471 if (DT->isProtected())
1472 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1473 dwarf::DW_ACCESS_protected);
1474 else if (DT->isPrivate())
1475 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1476 dwarf::DW_ACCESS_private);
1477 // Otherwise C++ member and base classes are considered public.
1478 else if (DT->isPublic())
1479 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1480 dwarf::DW_ACCESS_public);
1481 if (DT->isVirtual())
1482 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1483 dwarf::DW_VIRTUALITY_virtual);
1485 // Objective-C properties.
1486 if (DINode *PNode = DT->getObjCProperty())
1487 if (DIE *PDie = getDIE(PNode))
1488 MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1489 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1491 if (DT->isArtificial())
1492 addFlag(MemberDie, dwarf::DW_AT_artificial);
1495 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1499 // Construct the context before querying for the existence of the DIE in case
1500 // such construction creates the DIE.
1501 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1502 assert(dwarf::isType(ContextDIE->getTag()) &&
1503 "Static member should belong to a type.");
1505 if (DIE *StaticMemberDIE = getDIE(DT))
1506 return StaticMemberDIE;
1508 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1510 const DIType *Ty = resolve(DT->getBaseType());
1512 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1513 addType(StaticMemberDIE, Ty);
1514 addSourceLine(StaticMemberDIE, DT);
1515 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1516 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1518 // FIXME: We could omit private if the parent is a class_type, and
1519 // public if the parent is something else.
1520 if (DT->isProtected())
1521 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1522 dwarf::DW_ACCESS_protected);
1523 else if (DT->isPrivate())
1524 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1525 dwarf::DW_ACCESS_private);
1526 else if (DT->isPublic())
1527 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1528 dwarf::DW_ACCESS_public);
1530 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1531 addConstantValue(StaticMemberDIE, CI, Ty);
1532 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1533 addConstantFPValue(StaticMemberDIE, CFP);
1535 if (uint32_t AlignInBytes = DT->getAlignInBytes())
1536 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1539 return &StaticMemberDIE;
1542 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1543 // Emit size of content not including length itself
1544 Asm->OutStreamer->AddComment("Length of Unit");
1545 Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1547 Asm->OutStreamer->AddComment("DWARF version number");
1548 unsigned Version = DD->getDwarfVersion();
1549 Asm->EmitInt16(Version);
1551 // DWARF v5 reorders the address size and adds a unit type.
1553 Asm->OutStreamer->AddComment("DWARF Unit Type");
1555 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1556 Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1559 // We share one abbreviations table across all units so it's always at the
1560 // start of the section. Use a relocatable offset where needed to ensure
1561 // linking doesn't invalidate that offset.
1562 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1563 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1567 Asm->emitDwarfSymbolReference(
1568 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1571 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1572 Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1576 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1577 DwarfUnit::emitCommonHeader(UseOffsets,
1578 DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1579 : dwarf::DW_UT_type);
1580 Asm->OutStreamer->AddComment("Type Signature");
1581 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1582 Asm->OutStreamer->AddComment("Type DIE Offset");
1583 // In a skeleton type unit there is no type DIE so emit a zero offset.
1584 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1585 sizeof(Ty->getOffset()));
1588 bool DwarfTypeUnit::isDwoUnit() const {
1589 // Since there are no skeleton type units, all type units are dwo type units
1590 // when split DWARF is being used.
1591 return DD->useSplitDwarf();
1594 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1595 const DIScope *Context) {
1596 getCU().addGlobalNameForTypeUnit(Name, Context);
1599 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1600 const DIScope *Context) {
1601 getCU().addGlobalTypeUnitType(Ty, Context);
1604 const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1605 if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1609 return getSection()->getBeginSymbol();