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/MCDwarf.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "dwarfdebug"
48 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
49 cl::desc("Generate DWARF4 type units."),
52 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
54 : DwarfExpression(AP.getDwarfVersion()), AP(AP), DU(DU),
57 void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
58 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
61 void DIEDwarfExpression::emitSigned(int64_t Value) {
62 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
65 void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
66 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
69 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
70 unsigned MachineReg) {
71 return MachineReg == TRI.getFrameRegister(*AP.MF);
74 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
75 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
76 : DIEUnit(A->getDwarfVersion(), A->getPointerSize(), UnitTag), CUNode(Node),
77 Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) {
80 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
81 DwarfDebug *DW, DwarfFile *DWU,
82 MCDwarfDwoLineTable *SplitLineTable)
83 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
84 SplitLineTable(SplitLineTable) {
86 addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
89 DwarfUnit::~DwarfUnit() {
90 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
91 DIEBlocks[j]->~DIEBlock();
92 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
93 DIELocs[j]->~DIELoc();
96 int64_t DwarfUnit::getDefaultLowerBound() const {
97 switch (getLanguage()) {
101 // The languages below have valid values in all DWARF versions.
102 case dwarf::DW_LANG_C:
103 case dwarf::DW_LANG_C89:
104 case dwarf::DW_LANG_C_plus_plus:
107 case dwarf::DW_LANG_Fortran77:
108 case dwarf::DW_LANG_Fortran90:
111 // The languages below have valid values only if the DWARF version >= 3.
112 case dwarf::DW_LANG_C99:
113 case dwarf::DW_LANG_ObjC:
114 case dwarf::DW_LANG_ObjC_plus_plus:
115 if (DD->getDwarfVersion() >= 3)
119 case dwarf::DW_LANG_Fortran95:
120 if (DD->getDwarfVersion() >= 3)
124 // Starting with DWARF v4, all defined languages have valid values.
125 case dwarf::DW_LANG_D:
126 case dwarf::DW_LANG_Java:
127 case dwarf::DW_LANG_Python:
128 case dwarf::DW_LANG_UPC:
129 if (DD->getDwarfVersion() >= 4)
133 case dwarf::DW_LANG_Ada83:
134 case dwarf::DW_LANG_Ada95:
135 case dwarf::DW_LANG_Cobol74:
136 case dwarf::DW_LANG_Cobol85:
137 case dwarf::DW_LANG_Modula2:
138 case dwarf::DW_LANG_Pascal83:
139 case dwarf::DW_LANG_PLI:
140 if (DD->getDwarfVersion() >= 4)
144 // The languages below are new in DWARF v5.
145 case dwarf::DW_LANG_BLISS:
146 case dwarf::DW_LANG_C11:
147 case dwarf::DW_LANG_C_plus_plus_03:
148 case dwarf::DW_LANG_C_plus_plus_11:
149 case dwarf::DW_LANG_C_plus_plus_14:
150 case dwarf::DW_LANG_Dylan:
151 case dwarf::DW_LANG_Go:
152 case dwarf::DW_LANG_Haskell:
153 case dwarf::DW_LANG_OCaml:
154 case dwarf::DW_LANG_OpenCL:
155 case dwarf::DW_LANG_RenderScript:
156 case dwarf::DW_LANG_Rust:
157 case dwarf::DW_LANG_Swift:
158 if (DD->getDwarfVersion() >= 5)
162 case dwarf::DW_LANG_Fortran03:
163 case dwarf::DW_LANG_Fortran08:
164 case dwarf::DW_LANG_Julia:
165 case dwarf::DW_LANG_Modula3:
166 if (DD->getDwarfVersion() >= 5)
174 /// Check whether the DIE for this MDNode can be shared across CUs.
175 static bool isShareableAcrossCUs(const DINode *D) {
176 // When the MDNode can be part of the type system, the DIE can be shared
178 // Combining type units and cross-CU DIE sharing is lower value (since
179 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
180 // level already) but may be implementable for some value in projects
181 // building multiple independent libraries with LTO and then linking those
183 return (isa<DIType>(D) ||
184 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
185 !GenerateDwarfTypeUnits;
188 DIE *DwarfUnit::getDIE(const DINode *D) const {
189 if (isShareableAcrossCUs(D))
190 return DU->getDIE(D);
191 return MDNodeToDieMap.lookup(D);
194 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
195 if (isShareableAcrossCUs(Desc)) {
196 DU->insertDIE(Desc, D);
199 MDNodeToDieMap.insert(std::make_pair(Desc, D));
202 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
203 if (DD->getDwarfVersion() >= 4)
204 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
207 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
211 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
212 Optional<dwarf::Form> Form, uint64_t Integer) {
214 Form = DIEInteger::BestForm(false, Integer);
215 assert(Form != dwarf::DW_FORM_implicit_const &&
216 "DW_FORM_implicit_const is used only for signed integers");
217 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
220 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
222 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
225 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
226 Optional<dwarf::Form> Form, int64_t Integer) {
228 Form = DIEInteger::BestForm(true, Integer);
229 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
232 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
234 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
237 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
239 Die.addValue(DIEValueAllocator, Attribute,
240 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
241 DIEString(DU->getStringPool().getEntry(*Asm, String)));
244 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
245 dwarf::Attribute Attribute,
247 const MCSymbol *Label) {
248 return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
251 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
252 addLabel(Die, (dwarf::Attribute)0, Form, Label);
255 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
257 if (DD->getDwarfVersion() >= 4)
258 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
260 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
263 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
264 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
265 : getCU().getOrCreateSourceID(FileName, DirName);
268 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
269 if (!DD->useSplitDwarf()) {
270 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
271 addLabel(Die, dwarf::DW_FORM_udata, Sym);
273 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
274 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
275 DD->getAddressPool().getIndex(Sym));
279 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
280 const MCSymbol *Hi, const MCSymbol *Lo) {
281 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
282 new (DIEValueAllocator) DIEDelta(Hi, Lo));
285 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
286 addDIEEntry(Die, Attribute, DIEEntry(Entry));
289 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
290 // Flag the type unit reference as a declaration so that if it contains
291 // members (implicit special members, static data member definitions, member
292 // declarations for definitions in this CU, etc) consumers don't get confused
293 // and think this is a full definition.
294 addFlag(Die, dwarf::DW_AT_declaration);
296 Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
297 dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
300 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
302 const DIEUnit *CU = Die.getUnit();
303 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
305 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
306 CU = getUnitDie().getUnit();
308 EntryCU = getUnitDie().getUnit();
309 Die.addValue(DIEValueAllocator, Attribute,
310 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
314 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
315 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
321 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
322 Loc->ComputeSize(Asm);
323 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
324 Die.addValue(DIEValueAllocator, Attribute,
325 Loc->BestForm(DD->getDwarfVersion()), Loc);
328 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
330 Block->ComputeSize(Asm);
331 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
332 Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
335 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
336 StringRef Directory) {
340 unsigned FileID = getOrCreateSourceID(File, Directory);
341 assert(FileID && "Invalid file id");
342 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
343 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
346 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
349 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
350 V->getScope()->getDirectory());
353 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
356 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
359 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
362 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
365 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
368 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
371 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
374 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
377 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
378 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
381 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
382 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
383 gives the variable VarName either the struct, or a pointer to the struct, as
384 its type. This is necessary for various behind-the-scenes things the
385 compiler needs to do with by-reference variables in Blocks.
387 However, as far as the original *programmer* is concerned, the variable
388 should still have type 'SomeType', as originally declared.
390 The function getBlockByrefType dives into the __Block_byref_x_VarName
391 struct to find the original type of the variable, which is then assigned to
392 the variable's Debug Information Entry as its real type. So far, so good.
393 However now the debugger will expect the variable VarName to have the type
394 SomeType. So we need the location attribute for the variable to be an
395 expression that explains to the debugger how to navigate through the
396 pointers and struct to find the actual variable of type SomeType.
398 The following function does just that. We start by getting
399 the "normal" location for the variable. This will be the location
400 of either the struct __Block_byref_x_VarName or the pointer to the
401 struct __Block_byref_x_VarName.
403 The struct will look something like:
405 struct __Block_byref_x_VarName {
407 struct __Block_byref_x_VarName *forwarding;
408 ... <various other fields>
410 ... <maybe more fields>
413 If we are given the struct directly (as our starting point) we
414 need to tell the debugger to:
416 1). Add the offset of the forwarding field.
418 2). Follow that pointer to get the real __Block_byref_x_VarName
419 struct to use (the real one may have been copied onto the heap).
421 3). Add the offset for the field VarName, to find the actual variable.
423 If we started with a pointer to the struct, then we need to
424 dereference that pointer first, before the other steps.
425 Translating this into DWARF ops, we will need to append the following
426 to the current location description for the variable:
428 DW_OP_deref -- optional, if we start with a pointer
429 DW_OP_plus_uconst <forward_fld_offset>
431 DW_OP_plus_uconst <varName_fld_offset>
433 That is what this function does. */
435 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
436 dwarf::Attribute Attribute,
437 const MachineLocation &Location) {
438 const DIType *Ty = DV.getType();
439 const DIType *TmpTy = Ty;
440 uint16_t Tag = Ty->getTag();
441 bool isPointer = false;
443 StringRef varName = DV.getName();
445 if (Tag == dwarf::DW_TAG_pointer_type) {
446 auto *DTy = cast<DIDerivedType>(Ty);
447 TmpTy = resolve(DTy->getBaseType());
451 // Find the __forwarding field and the variable field in the __Block_byref
453 DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
454 const DIDerivedType *varField = nullptr;
455 const DIDerivedType *forwardingField = nullptr;
457 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
458 auto *DT = cast<DIDerivedType>(Fields[i]);
459 StringRef fieldName = DT->getName();
460 if (fieldName == "__forwarding")
461 forwardingField = DT;
462 else if (fieldName == varName)
466 // Get the offsets for the forwarding field and the variable field.
467 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
468 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
470 // Decode the original location, and use that as the start of the byref
471 // variable's location.
472 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
473 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
475 SmallVector<uint64_t, 9> Ops;
476 if (Location.isIndirect()) {
477 Ops.push_back(dwarf::DW_OP_plus);
478 Ops.push_back(Location.getOffset());
479 Ops.push_back(dwarf::DW_OP_deref);
481 // If we started with a pointer to the __Block_byref... struct, then
482 // the first thing we need to do is dereference the pointer (DW_OP_deref).
484 Ops.push_back(dwarf::DW_OP_deref);
486 // Next add the offset for the '__forwarding' field:
487 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
488 // adding the offset if it's 0.
489 if (forwardingFieldOffset > 0) {
490 Ops.push_back(dwarf::DW_OP_plus);
491 Ops.push_back(forwardingFieldOffset);
494 // Now dereference the __forwarding field to get to the real __Block_byref
495 // struct: DW_OP_deref.
496 Ops.push_back(dwarf::DW_OP_deref);
498 // Now that we've got the real __Block_byref... struct, add the offset
499 // for the variable's field to get to the location of the actual variable:
500 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
501 if (varFieldOffset > 0) {
502 Ops.push_back(dwarf::DW_OP_plus);
503 Ops.push_back(varFieldOffset);
506 DIExpressionCursor Cursor(Ops);
507 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
508 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
510 DwarfExpr.addExpression(std::move(Cursor));
512 // Now attach the location information to the DIE.
513 addBlock(Die, Attribute, DwarfExpr.finalize());
516 /// Return true if type encoding is unsigned.
517 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
518 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
519 // FIXME: Enums without a fixed underlying type have unknown signedness
520 // here, leading to incorrectly emitted constants.
521 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
524 // (Pieces of) aggregate types that get hacked apart by SROA may be
525 // represented by a constant. Encode them as unsigned bytes.
529 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
530 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
531 // Encode pointer constants as unsigned bytes. This is used at least for
532 // null pointer constant emission.
533 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
534 // here, but accept them for now due to a bug in SROA producing bogus
536 if (T == dwarf::DW_TAG_pointer_type ||
537 T == dwarf::DW_TAG_ptr_to_member_type ||
538 T == dwarf::DW_TAG_reference_type ||
539 T == dwarf::DW_TAG_rvalue_reference_type)
541 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
542 T == dwarf::DW_TAG_volatile_type ||
543 T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
544 DITypeRef Deriv = DTy->getBaseType();
545 assert(Deriv && "Expected valid base type");
546 return isUnsignedDIType(DD, DD->resolve(Deriv));
549 auto *BTy = cast<DIBasicType>(Ty);
550 unsigned Encoding = BTy->getEncoding();
551 assert((Encoding == dwarf::DW_ATE_unsigned ||
552 Encoding == dwarf::DW_ATE_unsigned_char ||
553 Encoding == dwarf::DW_ATE_signed ||
554 Encoding == dwarf::DW_ATE_signed_char ||
555 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
556 Encoding == dwarf::DW_ATE_boolean ||
557 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
558 Ty->getName() == "decltype(nullptr)")) &&
559 "Unsupported encoding");
560 return Encoding == dwarf::DW_ATE_unsigned ||
561 Encoding == dwarf::DW_ATE_unsigned_char ||
562 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
563 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
566 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
567 assert(MO.isFPImm() && "Invalid machine operand!");
568 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
569 APFloat FPImm = MO.getFPImm()->getValueAPF();
571 // Get the raw data form of the floating point.
572 const APInt FltVal = FPImm.bitcastToAPInt();
573 const char *FltPtr = (const char *)FltVal.getRawData();
575 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
576 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
577 int Incr = (LittleEndian ? 1 : -1);
578 int Start = (LittleEndian ? 0 : NumBytes - 1);
579 int Stop = (LittleEndian ? NumBytes : -1);
581 // Output the constant to DWARF one byte at a time.
582 for (; Start != Stop; Start += Incr)
583 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
585 addBlock(Die, dwarf::DW_AT_const_value, Block);
588 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
589 // Pass this down to addConstantValue as an unsigned bag of bits.
590 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
593 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
595 addConstantValue(Die, CI->getValue(), Ty);
598 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
600 assert(MO.isImm() && "Invalid machine operand!");
602 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
605 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
606 // FIXME: This is a bit conservative/simple - it emits negative values always
607 // sign extended to 64 bits rather than minimizing the number of bytes.
608 addUInt(Die, dwarf::DW_AT_const_value,
609 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
612 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
613 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
616 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
617 unsigned CIBitWidth = Val.getBitWidth();
618 if (CIBitWidth <= 64) {
619 addConstantValue(Die, Unsigned,
620 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
624 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
626 // Get the raw data form of the large APInt.
627 const uint64_t *Ptr64 = Val.getRawData();
629 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
630 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
632 // Output the constant to DWARF one byte at a time.
633 for (int i = 0; i < NumBytes; i++) {
636 c = Ptr64[i / 8] >> (8 * (i & 7));
638 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
639 addUInt(*Block, dwarf::DW_FORM_data1, c);
642 addBlock(Die, dwarf::DW_AT_const_value, Block);
645 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
646 if (!LinkageName.empty())
648 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
649 : dwarf::DW_AT_MIPS_linkage_name,
650 GlobalValue::getRealLinkageName(LinkageName));
653 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
654 // Add template parameters.
655 for (const auto *Element : TParams) {
656 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
657 constructTemplateTypeParameterDIE(Buffer, TTP);
658 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
659 constructTemplateValueParameterDIE(Buffer, TVP);
663 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
664 if (!Context || isa<DIFile>(Context))
665 return &getUnitDie();
666 if (auto *T = dyn_cast<DIType>(Context))
667 return getOrCreateTypeDIE(T);
668 if (auto *NS = dyn_cast<DINamespace>(Context))
669 return getOrCreateNameSpace(NS);
670 if (auto *SP = dyn_cast<DISubprogram>(Context))
671 return getOrCreateSubprogramDIE(SP);
672 if (auto *M = dyn_cast<DIModule>(Context))
673 return getOrCreateModule(M);
674 return getDIE(Context);
677 DIE *DwarfTypeUnit::createTypeDIE(const DICompositeType *Ty) {
678 auto *Context = resolve(Ty->getScope());
679 DIE *ContextDIE = getOrCreateContextDIE(Context);
681 if (DIE *TyDIE = getDIE(Ty))
685 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
687 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
689 updateAcceleratorTables(Context, Ty, TyDIE);
693 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
697 auto *Ty = cast<DIType>(TyNode);
699 // DW_TAG_restrict_type is not supported in DWARF2
700 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
701 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
703 // DW_TAG_atomic_type is not supported in DWARF < 5
704 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
705 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
707 // Construct the context before querying for the existence of the DIE in case
708 // such construction creates the DIE.
709 auto *Context = resolve(Ty->getScope());
710 DIE *ContextDIE = getOrCreateContextDIE(Context);
713 if (DIE *TyDIE = getDIE(Ty))
717 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
719 updateAcceleratorTables(Context, Ty, TyDIE);
721 if (auto *BT = dyn_cast<DIBasicType>(Ty))
722 constructTypeDIE(TyDIE, BT);
723 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
724 constructTypeDIE(TyDIE, STy);
725 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
726 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
727 if (MDString *TypeId = CTy->getRawIdentifier()) {
728 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
729 // Skip updating the accelerator tables since this is not the full type.
732 constructTypeDIE(TyDIE, CTy);
734 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
740 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
741 const DIType *Ty, const DIE &TyDIE) {
742 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
743 bool IsImplementation = false;
744 if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
745 // A runtime language of 0 actually means C/C++ and that any
746 // non-negative value is some version of Objective-C/C++.
747 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
749 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
750 DD->addAccelType(Ty->getName(), TyDIE, Flags);
752 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
753 isa<DINamespace>(Context))
754 addGlobalType(Ty, TyDIE, Context);
758 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
759 dwarf::Attribute Attribute) {
760 assert(Ty && "Trying to add a type that doesn't exist?");
761 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
764 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
768 // FIXME: Decide whether to implement this for non-C++ languages.
769 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
773 SmallVector<const DIScope *, 1> Parents;
774 while (!isa<DICompileUnit>(Context)) {
775 Parents.push_back(Context);
776 if (Context->getScope())
777 Context = resolve(Context->getScope());
779 // Structure, etc types will have a NULL context if they're at the top
784 // Reverse iterate over our list to go from the outermost construct to the
786 for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
787 StringRef Name = Ctx->getName();
788 if (Name.empty() && isa<DINamespace>(Ctx))
789 Name = "(anonymous namespace)";
798 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
799 // Get core information.
800 StringRef Name = BTy->getName();
801 // Add name if not anonymous or intermediate type.
803 addString(Buffer, dwarf::DW_AT_name, Name);
805 // An unspecified type only has a name attribute.
806 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
809 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
812 uint64_t Size = BTy->getSizeInBits() >> 3;
813 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
816 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
817 // Get core information.
818 StringRef Name = DTy->getName();
819 uint64_t Size = DTy->getSizeInBits() >> 3;
820 uint16_t Tag = Buffer.getTag();
822 // Map to main type, void will not have a type.
823 const DIType *FromTy = resolve(DTy->getBaseType());
825 addType(Buffer, FromTy);
827 // Add name if not anonymous or intermediate type.
829 addString(Buffer, dwarf::DW_AT_name, Name);
831 // Add size if non-zero (derived types might be zero-sized.)
832 if (Size && Tag != dwarf::DW_TAG_pointer_type
833 && Tag != dwarf::DW_TAG_ptr_to_member_type
834 && Tag != dwarf::DW_TAG_reference_type
835 && Tag != dwarf::DW_TAG_rvalue_reference_type)
836 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
838 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
840 Buffer, dwarf::DW_AT_containing_type,
841 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
842 // Add source line info if available and TyDesc is not a forward declaration.
843 if (!DTy->isForwardDecl())
844 addSourceLine(Buffer, DTy);
846 // If DWARF address space value is other than None, add it for pointer and
847 // reference types as DW_AT_address_class.
848 if (DTy->getDWARFAddressSpace() && (Tag == dwarf::DW_TAG_pointer_type ||
849 Tag == dwarf::DW_TAG_reference_type))
850 addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
851 DTy->getDWARFAddressSpace().getValue());
854 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
855 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
856 const DIType *Ty = resolve(Args[i]);
858 assert(i == N-1 && "Unspecified parameter must be the last argument");
859 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
861 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
863 if (Ty->isArtificial())
864 addFlag(Arg, dwarf::DW_AT_artificial);
869 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
870 // Add return type. A void return won't have a type.
871 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
873 if (auto RTy = resolve(Elements[0]))
874 addType(Buffer, RTy);
876 bool isPrototyped = true;
877 if (Elements.size() == 2 && !Elements[1])
878 isPrototyped = false;
880 constructSubprogramArguments(Buffer, Elements);
882 // Add prototype flag if we're dealing with a C language and the function has
884 uint16_t Language = getLanguage();
886 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
887 Language == dwarf::DW_LANG_ObjC))
888 addFlag(Buffer, dwarf::DW_AT_prototyped);
890 // Add a DW_AT_calling_convention if this has an explicit convention.
891 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
892 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
895 if (CTy->isLValueReference())
896 addFlag(Buffer, dwarf::DW_AT_reference);
898 if (CTy->isRValueReference())
899 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
902 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
903 // Add name if not anonymous or intermediate type.
904 StringRef Name = CTy->getName();
906 uint64_t Size = CTy->getSizeInBits() >> 3;
907 uint16_t Tag = Buffer.getTag();
910 case dwarf::DW_TAG_array_type:
911 constructArrayTypeDIE(Buffer, CTy);
913 case dwarf::DW_TAG_enumeration_type:
914 constructEnumTypeDIE(Buffer, CTy);
916 case dwarf::DW_TAG_structure_type:
917 case dwarf::DW_TAG_union_type:
918 case dwarf::DW_TAG_class_type: {
919 // Add elements to structure type.
920 DINodeArray Elements = CTy->getElements();
921 for (const auto *Element : Elements) {
924 if (auto *SP = dyn_cast<DISubprogram>(Element))
925 getOrCreateSubprogramDIE(SP);
926 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
927 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
928 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
929 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
930 } else if (DDTy->isStaticMember()) {
931 getOrCreateStaticMemberDIE(DDTy);
933 constructMemberDIE(Buffer, DDTy);
935 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
936 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
937 StringRef PropertyName = Property->getName();
938 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
939 if (Property->getType())
940 addType(ElemDie, resolve(Property->getType()));
941 addSourceLine(ElemDie, Property);
942 StringRef GetterName = Property->getGetterName();
943 if (!GetterName.empty())
944 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
945 StringRef SetterName = Property->getSetterName();
946 if (!SetterName.empty())
947 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
948 if (unsigned PropertyAttributes = Property->getAttributes())
949 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
954 if (CTy->isAppleBlockExtension())
955 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
957 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
958 // inside C++ composite types to point to the base class with the vtable.
959 if (auto *ContainingType =
960 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
961 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
962 *getOrCreateTypeDIE(ContainingType));
964 if (CTy->isObjcClassComplete())
965 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
967 // Add template parameters to a class, structure or union types.
968 // FIXME: The support isn't in the metadata for this yet.
969 if (Tag == dwarf::DW_TAG_class_type ||
970 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
971 addTemplateParams(Buffer, CTy->getTemplateParams());
979 // Add name if not anonymous or intermediate type.
981 addString(Buffer, dwarf::DW_AT_name, Name);
983 if (Tag == dwarf::DW_TAG_enumeration_type ||
984 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
985 Tag == dwarf::DW_TAG_union_type) {
986 // Add size if non-zero (derived types might be zero-sized.)
987 // TODO: Do we care about size for enum forward declarations?
989 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
990 else if (!CTy->isForwardDecl())
991 // Add zero size if it is not a forward declaration.
992 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
994 // If we're a forward decl, say so.
995 if (CTy->isForwardDecl())
996 addFlag(Buffer, dwarf::DW_AT_declaration);
998 // Add source line info if available.
999 if (!CTy->isForwardDecl())
1000 addSourceLine(Buffer, CTy);
1002 // No harm in adding the runtime language to the declaration.
1003 unsigned RLang = CTy->getRuntimeLang();
1005 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1008 // Add align info if available.
1009 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1010 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1015 void DwarfUnit::constructTemplateTypeParameterDIE(
1016 DIE &Buffer, const DITemplateTypeParameter *TP) {
1018 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1019 // Add the type if it exists, it could be void and therefore no type.
1021 addType(ParamDIE, resolve(TP->getType()));
1022 if (!TP->getName().empty())
1023 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1026 void DwarfUnit::constructTemplateValueParameterDIE(
1027 DIE &Buffer, const DITemplateValueParameter *VP) {
1028 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1030 // Add the type if there is one, template template and template parameter
1031 // packs will not have a type.
1032 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1033 addType(ParamDIE, resolve(VP->getType()));
1034 if (!VP->getName().empty())
1035 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1036 if (Metadata *Val = VP->getValue()) {
1037 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1038 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1039 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1040 // We cannot describe the location of dllimport'd entities: the
1041 // computation of their address requires loads from the IAT.
1042 if (!GV->hasDLLImportStorageClass()) {
1043 // For declaration non-type template parameters (such as global values
1045 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1046 addOpAddress(*Loc, Asm->getSymbol(GV));
1047 // Emit DW_OP_stack_value to use the address as the immediate value of
1048 // the parameter, rather than a pointer to it.
1049 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1050 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1052 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1053 assert(isa<MDString>(Val));
1054 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1055 cast<MDString>(Val)->getString());
1056 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1057 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1062 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1063 // Construct the context before querying for the existence of the DIE in case
1064 // such construction creates the DIE.
1065 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1067 if (DIE *NDie = getDIE(NS))
1069 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1071 StringRef Name = NS->getName();
1073 addString(NDie, dwarf::DW_AT_name, NS->getName());
1075 Name = "(anonymous namespace)";
1076 DD->addAccelNamespace(Name, NDie);
1077 addGlobalName(Name, NDie, NS->getScope());
1078 addSourceLine(NDie, NS);
1079 if (NS->getExportSymbols())
1080 addFlag(NDie, dwarf::DW_AT_export_symbols);
1084 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1085 // Construct the context before querying for the existence of the DIE in case
1086 // such construction creates the DIE.
1087 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1089 if (DIE *MDie = getDIE(M))
1091 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1093 if (!M->getName().empty()) {
1094 addString(MDie, dwarf::DW_AT_name, M->getName());
1095 addGlobalName(M->getName(), MDie, M->getScope());
1097 if (!M->getConfigurationMacros().empty())
1098 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1099 M->getConfigurationMacros());
1100 if (!M->getIncludePath().empty())
1101 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1102 if (!M->getISysRoot().empty())
1103 addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1108 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1109 // Construct the context before querying for the existence of the DIE in case
1110 // such construction creates the DIE (as is the case for member function
1113 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1115 if (DIE *SPDie = getDIE(SP))
1118 if (auto *SPDecl = SP->getDeclaration()) {
1120 // Add subprogram definitions to the CU die directly.
1121 ContextDIE = &getUnitDie();
1122 // Build the decl now to ensure it precedes the definition.
1123 getOrCreateSubprogramDIE(SPDecl);
1127 // DW_TAG_inlined_subroutine may refer to this DIE.
1128 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1130 // Stop here and fill this in later, depending on whether or not this
1131 // subprogram turns out to have inlined instances or not.
1132 if (SP->isDefinition())
1135 applySubprogramAttributes(SP, SPDie);
1139 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1141 DIE *DeclDie = nullptr;
1142 StringRef DeclLinkageName;
1143 if (auto *SPDecl = SP->getDeclaration()) {
1144 DeclDie = getDIE(SPDecl);
1145 assert(DeclDie && "This DIE should've already been constructed when the "
1146 "definition DIE was created in "
1147 "getOrCreateSubprogramDIE");
1148 // Look at the Decl's linkage name only if we emitted it.
1149 if (DD->useAllLinkageNames())
1150 DeclLinkageName = SPDecl->getLinkageName();
1152 getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1153 unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1154 if (DeclID != DefID)
1155 addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1157 if (SP->getLine() != SPDecl->getLine())
1158 addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1161 // Add function template parameters.
1162 addTemplateParams(SPDie, SP->getTemplateParams());
1164 // Add the linkage name if we have one and it isn't in the Decl.
1165 StringRef LinkageName = SP->getLinkageName();
1166 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1167 LinkageName == DeclLinkageName) &&
1168 "decl has a linkage name and it is different");
1169 if (DeclLinkageName.empty() &&
1170 // Always emit it for abstract subprograms.
1171 (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1172 addLinkageName(SPDie, LinkageName);
1177 // Refer to the function declaration where all the other attributes will be
1179 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1183 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1184 bool SkipSPAttributes) {
1185 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1186 // and its source location.
1187 bool SkipSPSourceLocation = SkipSPAttributes &&
1188 !CUNode->getDebugInfoForProfiling();
1189 if (!SkipSPSourceLocation)
1190 if (applySubprogramDefinitionAttributes(SP, SPDie))
1193 // Constructors and operators for anonymous aggregates do not have names.
1194 if (!SP->getName().empty())
1195 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1197 if (!SkipSPSourceLocation)
1198 addSourceLine(SPDie, SP);
1200 // Skip the rest of the attributes under -gmlt to save space.
1201 if (SkipSPAttributes)
1204 // Add the prototype if we have a prototype and we have a C like
1206 uint16_t Language = getLanguage();
1207 if (SP->isPrototyped() &&
1208 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1209 Language == dwarf::DW_LANG_ObjC))
1210 addFlag(SPDie, dwarf::DW_AT_prototyped);
1213 DITypeRefArray Args;
1214 if (const DISubroutineType *SPTy = SP->getType()) {
1215 Args = SPTy->getTypeArray();
1219 // Add a DW_AT_calling_convention if this has an explicit convention.
1220 if (CC && CC != dwarf::DW_CC_normal)
1221 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1223 // Add a return type. If this is a type like a C/C++ void type we don't add a
1226 if (auto Ty = resolve(Args[0]))
1229 unsigned VK = SP->getVirtuality();
1231 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1232 if (SP->getVirtualIndex() != -1u) {
1233 DIELoc *Block = getDIELoc();
1234 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1235 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1236 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1238 ContainingTypeMap.insert(
1239 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1242 if (!SP->isDefinition()) {
1243 addFlag(SPDie, dwarf::DW_AT_declaration);
1245 // Add arguments. Do not add arguments for subprogram definition. They will
1246 // be handled while processing variables.
1247 constructSubprogramArguments(SPDie, Args);
1250 if (SP->isArtificial())
1251 addFlag(SPDie, dwarf::DW_AT_artificial);
1253 if (!SP->isLocalToUnit())
1254 addFlag(SPDie, dwarf::DW_AT_external);
1256 if (DD->useAppleExtensionAttributes()) {
1257 if (SP->isOptimized())
1258 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1260 if (unsigned isa = Asm->getISAEncoding())
1261 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1264 if (SP->isLValueReference())
1265 addFlag(SPDie, dwarf::DW_AT_reference);
1267 if (SP->isRValueReference())
1268 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1270 if (SP->isNoReturn())
1271 addFlag(SPDie, dwarf::DW_AT_noreturn);
1273 if (SP->isProtected())
1274 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1275 dwarf::DW_ACCESS_protected);
1276 else if (SP->isPrivate())
1277 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1278 dwarf::DW_ACCESS_private);
1279 else if (SP->isPublic())
1280 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1281 dwarf::DW_ACCESS_public);
1283 if (SP->isExplicit())
1284 addFlag(SPDie, dwarf::DW_AT_explicit);
1286 if (SP->isMainSubprogram())
1287 addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1290 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1292 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1293 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1295 // The LowerBound value defines the lower bounds which is typically zero for
1296 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1297 // Count == -1 then the array is unbounded and we do not emit
1298 // DW_AT_lower_bound and DW_AT_count attributes.
1299 int64_t LowerBound = SR->getLowerBound();
1300 int64_t DefaultLowerBound = getDefaultLowerBound();
1301 int64_t Count = SR->getCount();
1303 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1304 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1307 // FIXME: An unbounded array should reference the expression that defines
1309 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1312 DIE *DwarfUnit::getIndexTyDie() {
1315 // Construct an integer type to use for indexes.
1316 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1317 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1318 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1319 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1320 dwarf::DW_ATE_unsigned);
1324 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1325 if (CTy->isVector())
1326 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1328 // Emit the element type.
1329 addType(Buffer, resolve(CTy->getBaseType()));
1331 // Get an anonymous type for index type.
1332 // FIXME: This type should be passed down from the front end
1333 // as different languages may have different sizes for indexes.
1334 DIE *IdxTy = getIndexTyDie();
1336 // Add subranges to array type.
1337 DINodeArray Elements = CTy->getElements();
1338 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1339 // FIXME: Should this really be such a loose cast?
1340 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1341 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1342 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1346 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1347 DINodeArray Elements = CTy->getElements();
1349 // Add enumerators to enumeration type.
1350 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1351 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1353 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1354 StringRef Name = Enum->getName();
1355 addString(Enumerator, dwarf::DW_AT_name, Name);
1356 int64_t Value = Enum->getValue();
1357 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1361 const DIType *DTy = resolve(CTy->getBaseType());
1363 addType(Buffer, DTy);
1364 addFlag(Buffer, dwarf::DW_AT_enum_class);
1368 void DwarfUnit::constructContainingTypeDIEs() {
1369 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1371 DIE &SPDie = *CI->first;
1372 const DINode *D = CI->second;
1375 DIE *NDie = getDIE(D);
1378 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1382 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1383 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1384 StringRef Name = DT->getName();
1386 addString(MemberDie, dwarf::DW_AT_name, Name);
1388 addType(MemberDie, resolve(DT->getBaseType()));
1390 addSourceLine(MemberDie, DT);
1392 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1394 // For C++, virtual base classes are not at fixed offset. Use following
1395 // expression to extract appropriate offset from vtable.
1396 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1398 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1399 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1400 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1401 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1402 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1403 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1404 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1405 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1407 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1409 uint64_t Size = DT->getSizeInBits();
1410 uint64_t FieldSize = DD->getBaseTypeSize(DT);
1411 uint32_t AlignInBytes = DT->getAlignInBytes();
1412 uint64_t OffsetInBytes;
1414 bool IsBitfield = FieldSize && Size != FieldSize;
1416 // Handle bitfield, assume bytes are 8 bits.
1417 if (DD->useDWARF2Bitfields())
1418 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1419 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1421 uint64_t Offset = DT->getOffsetInBits();
1422 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1423 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1424 // which can't be done with bitfields. Thus we use FieldSize here.
1425 uint32_t AlignInBits = FieldSize;
1426 uint32_t AlignMask = ~(AlignInBits - 1);
1427 // The bits from the start of the storage unit to the start of the field.
1428 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1429 // The byte offset of the field's aligned storage unit inside the struct.
1430 OffsetInBytes = (Offset - StartBitOffset) / 8;
1432 if (DD->useDWARF2Bitfields()) {
1433 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1434 uint64_t FieldOffset = (HiMark - FieldSize);
1435 Offset -= FieldOffset;
1437 // Maybe we need to work from the other end.
1438 if (Asm->getDataLayout().isLittleEndian())
1439 Offset = FieldSize - (Offset + Size);
1441 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1442 OffsetInBytes = FieldOffset >> 3;
1444 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1447 // This is not a bitfield.
1448 OffsetInBytes = DT->getOffsetInBits() / 8;
1450 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1454 if (DD->getDwarfVersion() <= 2) {
1455 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1456 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1457 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1458 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1459 } else if (!IsBitfield || DD->useDWARF2Bitfields())
1460 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1464 if (DT->isProtected())
1465 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1466 dwarf::DW_ACCESS_protected);
1467 else if (DT->isPrivate())
1468 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1469 dwarf::DW_ACCESS_private);
1470 // Otherwise C++ member and base classes are considered public.
1471 else if (DT->isPublic())
1472 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1473 dwarf::DW_ACCESS_public);
1474 if (DT->isVirtual())
1475 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1476 dwarf::DW_VIRTUALITY_virtual);
1478 // Objective-C properties.
1479 if (DINode *PNode = DT->getObjCProperty())
1480 if (DIE *PDie = getDIE(PNode))
1481 MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1482 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1484 if (DT->isArtificial())
1485 addFlag(MemberDie, dwarf::DW_AT_artificial);
1488 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1492 // Construct the context before querying for the existence of the DIE in case
1493 // such construction creates the DIE.
1494 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1495 assert(dwarf::isType(ContextDIE->getTag()) &&
1496 "Static member should belong to a type.");
1498 if (DIE *StaticMemberDIE = getDIE(DT))
1499 return StaticMemberDIE;
1501 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1503 const DIType *Ty = resolve(DT->getBaseType());
1505 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1506 addType(StaticMemberDIE, Ty);
1507 addSourceLine(StaticMemberDIE, DT);
1508 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1509 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1511 // FIXME: We could omit private if the parent is a class_type, and
1512 // public if the parent is something else.
1513 if (DT->isProtected())
1514 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1515 dwarf::DW_ACCESS_protected);
1516 else if (DT->isPrivate())
1517 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1518 dwarf::DW_ACCESS_private);
1519 else if (DT->isPublic())
1520 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1521 dwarf::DW_ACCESS_public);
1523 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1524 addConstantValue(StaticMemberDIE, CI, Ty);
1525 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1526 addConstantFPValue(StaticMemberDIE, CFP);
1528 if (uint32_t AlignInBytes = DT->getAlignInBytes())
1529 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1532 return &StaticMemberDIE;
1535 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1536 // Emit size of content not including length itself
1537 Asm->OutStreamer->AddComment("Length of Unit");
1538 Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1540 Asm->OutStreamer->AddComment("DWARF version number");
1541 unsigned Version = DD->getDwarfVersion();
1542 Asm->EmitInt16(Version);
1544 // DWARF v5 reorders the address size and adds a unit type.
1546 Asm->OutStreamer->AddComment("DWARF Unit Type");
1548 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1549 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1552 // We share one abbreviations table across all units so it's always at the
1553 // start of the section. Use a relocatable offset where needed to ensure
1554 // linking doesn't invalidate that offset.
1555 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1556 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1560 Asm->emitDwarfSymbolReference(
1561 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1564 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1565 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1569 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1570 DwarfUnit::emitCommonHeader(UseOffsets,
1571 DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1572 : dwarf::DW_UT_type);
1573 Asm->OutStreamer->AddComment("Type Signature");
1574 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1575 Asm->OutStreamer->AddComment("Type DIE Offset");
1576 // In a skeleton type unit there is no type DIE so emit a zero offset.
1577 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1578 sizeof(Ty->getOffset()));
1581 bool DwarfTypeUnit::isDwoUnit() const {
1582 // Since there are no skeleton type units, all type units are dwo type units
1583 // when split DWARF is being used.
1584 return DD->useSplitDwarf();
1587 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1588 const DIScope *Context) {
1589 getCU().addGlobalNameForTypeUnit(Name, Context);
1592 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1593 const DIScope *Context) {
1594 getCU().addGlobalTypeUnitType(Ty, Context);