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/None.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFile.h"
26 #include "llvm/CodeGen/TargetRegisterInfo.h"
27 #include "llvm/CodeGen/TargetSubtargetInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCDwarf.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MachineLocation.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/CommandLine.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 bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const {
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 if (isDwoUnit() && !DD->shareAcrossDWOCUs())
186 return (isa<DIType>(D) ||
187 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
188 !GenerateDwarfTypeUnits;
191 DIE *DwarfUnit::getDIE(const DINode *D) const {
192 if (isShareableAcrossCUs(D))
193 return DU->getDIE(D);
194 return MDNodeToDieMap.lookup(D);
197 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
198 if (isShareableAcrossCUs(Desc)) {
199 DU->insertDIE(Desc, D);
202 MDNodeToDieMap.insert(std::make_pair(Desc, D));
205 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
206 if (DD->getDwarfVersion() >= 4)
207 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
210 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
214 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
215 Optional<dwarf::Form> Form, uint64_t Integer) {
217 Form = DIEInteger::BestForm(false, Integer);
218 assert(Form != dwarf::DW_FORM_implicit_const &&
219 "DW_FORM_implicit_const is used only for signed integers");
220 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
223 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
225 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
228 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
229 Optional<dwarf::Form> Form, int64_t Integer) {
231 Form = DIEInteger::BestForm(true, Integer);
232 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
235 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
237 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
240 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
242 Die.addValue(DIEValueAllocator, Attribute,
243 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
244 DIEString(DU->getStringPool().getEntry(*Asm, String)));
247 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
248 dwarf::Attribute Attribute,
250 const MCSymbol *Label) {
251 return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
254 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
255 addLabel(Die, (dwarf::Attribute)0, Form, Label);
258 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
260 if (DD->getDwarfVersion() >= 4)
261 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
263 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
266 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
267 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
268 : getCU().getOrCreateSourceID(FileName, DirName);
271 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
272 if (!DD->useSplitDwarf()) {
273 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
274 addLabel(Die, dwarf::DW_FORM_udata, Sym);
276 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
277 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
278 DD->getAddressPool().getIndex(Sym));
282 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
283 const MCSymbol *Hi, const MCSymbol *Lo) {
284 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
285 new (DIEValueAllocator) DIEDelta(Hi, Lo));
288 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
289 addDIEEntry(Die, Attribute, DIEEntry(Entry));
292 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
293 // Flag the type unit reference as a declaration so that if it contains
294 // members (implicit special members, static data member definitions, member
295 // declarations for definitions in this CU, etc) consumers don't get confused
296 // and think this is a full definition.
297 addFlag(Die, dwarf::DW_AT_declaration);
299 Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
300 dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
303 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
305 const DIEUnit *CU = Die.getUnit();
306 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
308 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
309 CU = getUnitDie().getUnit();
311 EntryCU = getUnitDie().getUnit();
312 Die.addValue(DIEValueAllocator, Attribute,
313 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
317 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
318 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
324 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
325 Loc->ComputeSize(Asm);
326 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
327 Die.addValue(DIEValueAllocator, Attribute,
328 Loc->BestForm(DD->getDwarfVersion()), Loc);
331 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
333 Block->ComputeSize(Asm);
334 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
335 Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
338 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
339 StringRef Directory) {
343 unsigned FileID = getOrCreateSourceID(File, Directory);
344 assert(FileID && "Invalid file id");
345 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
346 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
349 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
352 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
353 V->getScope()->getDirectory());
356 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
359 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
362 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
365 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
368 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
371 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
374 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
377 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
380 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
381 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
382 gives the variable VarName either the struct, or a pointer to the struct, as
383 its type. This is necessary for various behind-the-scenes things the
384 compiler needs to do with by-reference variables in Blocks.
386 However, as far as the original *programmer* is concerned, the variable
387 should still have type 'SomeType', as originally declared.
389 The function getBlockByrefType dives into the __Block_byref_x_VarName
390 struct to find the original type of the variable, which is then assigned to
391 the variable's Debug Information Entry as its real type. So far, so good.
392 However now the debugger will expect the variable VarName to have the type
393 SomeType. So we need the location attribute for the variable to be an
394 expression that explains to the debugger how to navigate through the
395 pointers and struct to find the actual variable of type SomeType.
397 The following function does just that. We start by getting
398 the "normal" location for the variable. This will be the location
399 of either the struct __Block_byref_x_VarName or the pointer to the
400 struct __Block_byref_x_VarName.
402 The struct will look something like:
404 struct __Block_byref_x_VarName {
406 struct __Block_byref_x_VarName *forwarding;
407 ... <various other fields>
409 ... <maybe more fields>
412 If we are given the struct directly (as our starting point) we
413 need to tell the debugger to:
415 1). Add the offset of the forwarding field.
417 2). Follow that pointer to get the real __Block_byref_x_VarName
418 struct to use (the real one may have been copied onto the heap).
420 3). Add the offset for the field VarName, to find the actual variable.
422 If we started with a pointer to the struct, then we need to
423 dereference that pointer first, before the other steps.
424 Translating this into DWARF ops, we will need to append the following
425 to the current location description for the variable:
427 DW_OP_deref -- optional, if we start with a pointer
428 DW_OP_plus_uconst <forward_fld_offset>
430 DW_OP_plus_uconst <varName_fld_offset>
432 That is what this function does. */
434 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
435 dwarf::Attribute Attribute,
436 const MachineLocation &Location) {
437 const DIType *Ty = DV.getType();
438 const DIType *TmpTy = Ty;
439 uint16_t Tag = Ty->getTag();
440 bool isPointer = false;
442 StringRef varName = DV.getName();
444 if (Tag == dwarf::DW_TAG_pointer_type) {
445 auto *DTy = cast<DIDerivedType>(Ty);
446 TmpTy = resolve(DTy->getBaseType());
450 // Find the __forwarding field and the variable field in the __Block_byref
452 DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
453 const DIDerivedType *varField = nullptr;
454 const DIDerivedType *forwardingField = nullptr;
456 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
457 auto *DT = cast<DIDerivedType>(Fields[i]);
458 StringRef fieldName = DT->getName();
459 if (fieldName == "__forwarding")
460 forwardingField = DT;
461 else if (fieldName == varName)
465 // Get the offsets for the forwarding field and the variable field.
466 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
467 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
469 // Decode the original location, and use that as the start of the byref
470 // variable's location.
471 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
472 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
473 if (Location.isIndirect())
474 DwarfExpr.setMemoryLocationKind();
476 SmallVector<uint64_t, 6> Ops;
477 // If we started with a pointer to the __Block_byref... struct, then
478 // the first thing we need to do is dereference the pointer (DW_OP_deref).
480 Ops.push_back(dwarf::DW_OP_deref);
482 // Next add the offset for the '__forwarding' field:
483 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
484 // adding the offset if it's 0.
485 if (forwardingFieldOffset > 0) {
486 Ops.push_back(dwarf::DW_OP_plus_uconst);
487 Ops.push_back(forwardingFieldOffset);
490 // Now dereference the __forwarding field to get to the real __Block_byref
491 // struct: DW_OP_deref.
492 Ops.push_back(dwarf::DW_OP_deref);
494 // Now that we've got the real __Block_byref... struct, add the offset
495 // for the variable's field to get to the location of the actual variable:
496 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
497 if (varFieldOffset > 0) {
498 Ops.push_back(dwarf::DW_OP_plus_uconst);
499 Ops.push_back(varFieldOffset);
502 DIExpressionCursor Cursor(Ops);
503 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
504 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
506 DwarfExpr.addExpression(std::move(Cursor));
508 // Now attach the location information to the DIE.
509 addBlock(Die, Attribute, DwarfExpr.finalize());
512 /// Return true if type encoding is unsigned.
513 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
514 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
515 // FIXME: Enums without a fixed underlying type have unknown signedness
516 // here, leading to incorrectly emitted constants.
517 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
520 // (Pieces of) aggregate types that get hacked apart by SROA may be
521 // represented by a constant. Encode them as unsigned bytes.
525 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
526 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
527 // Encode pointer constants as unsigned bytes. This is used at least for
528 // null pointer constant emission.
529 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
530 // here, but accept them for now due to a bug in SROA producing bogus
532 if (T == dwarf::DW_TAG_pointer_type ||
533 T == dwarf::DW_TAG_ptr_to_member_type ||
534 T == dwarf::DW_TAG_reference_type ||
535 T == dwarf::DW_TAG_rvalue_reference_type)
537 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
538 T == dwarf::DW_TAG_volatile_type ||
539 T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
540 DITypeRef Deriv = DTy->getBaseType();
541 assert(Deriv && "Expected valid base type");
542 return isUnsignedDIType(DD, DD->resolve(Deriv));
545 auto *BTy = cast<DIBasicType>(Ty);
546 unsigned Encoding = BTy->getEncoding();
547 assert((Encoding == dwarf::DW_ATE_unsigned ||
548 Encoding == dwarf::DW_ATE_unsigned_char ||
549 Encoding == dwarf::DW_ATE_signed ||
550 Encoding == dwarf::DW_ATE_signed_char ||
551 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
552 Encoding == dwarf::DW_ATE_boolean ||
553 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
554 Ty->getName() == "decltype(nullptr)")) &&
555 "Unsupported encoding");
556 return Encoding == dwarf::DW_ATE_unsigned ||
557 Encoding == dwarf::DW_ATE_unsigned_char ||
558 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
559 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
562 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
563 assert(MO.isFPImm() && "Invalid machine operand!");
564 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
565 APFloat FPImm = MO.getFPImm()->getValueAPF();
567 // Get the raw data form of the floating point.
568 const APInt FltVal = FPImm.bitcastToAPInt();
569 const char *FltPtr = (const char *)FltVal.getRawData();
571 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
572 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
573 int Incr = (LittleEndian ? 1 : -1);
574 int Start = (LittleEndian ? 0 : NumBytes - 1);
575 int Stop = (LittleEndian ? NumBytes : -1);
577 // Output the constant to DWARF one byte at a time.
578 for (; Start != Stop; Start += Incr)
579 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
581 addBlock(Die, dwarf::DW_AT_const_value, Block);
584 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
585 // Pass this down to addConstantValue as an unsigned bag of bits.
586 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
589 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
591 addConstantValue(Die, CI->getValue(), Ty);
594 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
596 assert(MO.isImm() && "Invalid machine operand!");
598 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
601 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
602 // FIXME: This is a bit conservative/simple - it emits negative values always
603 // sign extended to 64 bits rather than minimizing the number of bytes.
604 addUInt(Die, dwarf::DW_AT_const_value,
605 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
608 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
609 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
612 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
613 unsigned CIBitWidth = Val.getBitWidth();
614 if (CIBitWidth <= 64) {
615 addConstantValue(Die, Unsigned,
616 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
620 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
622 // Get the raw data form of the large APInt.
623 const uint64_t *Ptr64 = Val.getRawData();
625 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
626 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
628 // Output the constant to DWARF one byte at a time.
629 for (int i = 0; i < NumBytes; i++) {
632 c = Ptr64[i / 8] >> (8 * (i & 7));
634 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
635 addUInt(*Block, dwarf::DW_FORM_data1, c);
638 addBlock(Die, dwarf::DW_AT_const_value, Block);
641 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
642 if (!LinkageName.empty())
644 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
645 : dwarf::DW_AT_MIPS_linkage_name,
646 GlobalValue::dropLLVMManglingEscape(LinkageName));
649 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
650 // Add template parameters.
651 for (const auto *Element : TParams) {
652 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
653 constructTemplateTypeParameterDIE(Buffer, TTP);
654 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
655 constructTemplateValueParameterDIE(Buffer, TVP);
659 /// Add thrown types.
660 void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
661 for (const auto *Ty : ThrownTypes) {
662 DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
663 addType(TT, cast<DIType>(Ty));
667 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
668 if (!Context || isa<DIFile>(Context))
669 return &getUnitDie();
670 if (auto *T = dyn_cast<DIType>(Context))
671 return getOrCreateTypeDIE(T);
672 if (auto *NS = dyn_cast<DINamespace>(Context))
673 return getOrCreateNameSpace(NS);
674 if (auto *SP = dyn_cast<DISubprogram>(Context))
675 return getOrCreateSubprogramDIE(SP);
676 if (auto *M = dyn_cast<DIModule>(Context))
677 return getOrCreateModule(M);
678 return getDIE(Context);
681 DIE *DwarfTypeUnit::createTypeDIE(const DICompositeType *Ty) {
682 auto *Context = resolve(Ty->getScope());
683 DIE *ContextDIE = getOrCreateContextDIE(Context);
685 if (DIE *TyDIE = getDIE(Ty))
689 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
691 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
693 updateAcceleratorTables(Context, Ty, TyDIE);
697 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
701 auto *Ty = cast<DIType>(TyNode);
703 // DW_TAG_restrict_type is not supported in DWARF2
704 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
705 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
707 // DW_TAG_atomic_type is not supported in DWARF < 5
708 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
709 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
711 // Construct the context before querying for the existence of the DIE in case
712 // such construction creates the DIE.
713 auto *Context = resolve(Ty->getScope());
714 DIE *ContextDIE = getOrCreateContextDIE(Context);
717 if (DIE *TyDIE = getDIE(Ty))
721 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
723 updateAcceleratorTables(Context, Ty, TyDIE);
725 if (auto *BT = dyn_cast<DIBasicType>(Ty))
726 constructTypeDIE(TyDIE, BT);
727 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
728 constructTypeDIE(TyDIE, STy);
729 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
730 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
731 if (MDString *TypeId = CTy->getRawIdentifier()) {
732 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
733 // Skip updating the accelerator tables since this is not the full type.
736 constructTypeDIE(TyDIE, CTy);
738 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
744 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
745 const DIType *Ty, const DIE &TyDIE) {
746 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
747 bool IsImplementation = false;
748 if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
749 // A runtime language of 0 actually means C/C++ and that any
750 // non-negative value is some version of Objective-C/C++.
751 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
753 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
754 DD->addAccelType(Ty->getName(), TyDIE, Flags);
756 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
757 isa<DINamespace>(Context))
758 addGlobalType(Ty, TyDIE, Context);
762 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
763 dwarf::Attribute Attribute) {
764 assert(Ty && "Trying to add a type that doesn't exist?");
765 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
768 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
772 // FIXME: Decide whether to implement this for non-C++ languages.
773 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
777 SmallVector<const DIScope *, 1> Parents;
778 while (!isa<DICompileUnit>(Context)) {
779 Parents.push_back(Context);
780 if (Context->getScope())
781 Context = resolve(Context->getScope());
783 // Structure, etc types will have a NULL context if they're at the top
788 // Reverse iterate over our list to go from the outermost construct to the
790 for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
791 StringRef Name = Ctx->getName();
792 if (Name.empty() && isa<DINamespace>(Ctx))
793 Name = "(anonymous namespace)";
802 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
803 // Get core information.
804 StringRef Name = BTy->getName();
805 // Add name if not anonymous or intermediate type.
807 addString(Buffer, dwarf::DW_AT_name, Name);
809 // An unspecified type only has a name attribute.
810 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
813 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
816 uint64_t Size = BTy->getSizeInBits() >> 3;
817 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
820 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
821 // Get core information.
822 StringRef Name = DTy->getName();
823 uint64_t Size = DTy->getSizeInBits() >> 3;
824 uint16_t Tag = Buffer.getTag();
826 // Map to main type, void will not have a type.
827 const DIType *FromTy = resolve(DTy->getBaseType());
829 addType(Buffer, FromTy);
831 // Add name if not anonymous or intermediate type.
833 addString(Buffer, dwarf::DW_AT_name, Name);
835 // Add size if non-zero (derived types might be zero-sized.)
836 if (Size && Tag != dwarf::DW_TAG_pointer_type
837 && Tag != dwarf::DW_TAG_ptr_to_member_type
838 && Tag != dwarf::DW_TAG_reference_type
839 && Tag != dwarf::DW_TAG_rvalue_reference_type)
840 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
842 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
844 Buffer, dwarf::DW_AT_containing_type,
845 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
846 // Add source line info if available and TyDesc is not a forward declaration.
847 if (!DTy->isForwardDecl())
848 addSourceLine(Buffer, DTy);
850 // If DWARF address space value is other than None, add it for pointer and
851 // reference types as DW_AT_address_class.
852 if (DTy->getDWARFAddressSpace() && (Tag == dwarf::DW_TAG_pointer_type ||
853 Tag == dwarf::DW_TAG_reference_type))
854 addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
855 DTy->getDWARFAddressSpace().getValue());
858 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
859 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
860 const DIType *Ty = resolve(Args[i]);
862 assert(i == N-1 && "Unspecified parameter must be the last argument");
863 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
865 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
867 if (Ty->isArtificial())
868 addFlag(Arg, dwarf::DW_AT_artificial);
873 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
874 // Add return type. A void return won't have a type.
875 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
877 if (auto RTy = resolve(Elements[0]))
878 addType(Buffer, RTy);
880 bool isPrototyped = true;
881 if (Elements.size() == 2 && !Elements[1])
882 isPrototyped = false;
884 constructSubprogramArguments(Buffer, Elements);
886 // Add prototype flag if we're dealing with a C language and the function has
888 uint16_t Language = getLanguage();
890 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
891 Language == dwarf::DW_LANG_ObjC))
892 addFlag(Buffer, dwarf::DW_AT_prototyped);
894 // Add a DW_AT_calling_convention if this has an explicit convention.
895 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
896 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
899 if (CTy->isLValueReference())
900 addFlag(Buffer, dwarf::DW_AT_reference);
902 if (CTy->isRValueReference())
903 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
906 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
907 // Add name if not anonymous or intermediate type.
908 StringRef Name = CTy->getName();
910 uint64_t Size = CTy->getSizeInBits() >> 3;
911 uint16_t Tag = Buffer.getTag();
914 case dwarf::DW_TAG_array_type:
915 constructArrayTypeDIE(Buffer, CTy);
917 case dwarf::DW_TAG_enumeration_type:
918 constructEnumTypeDIE(Buffer, CTy);
920 case dwarf::DW_TAG_structure_type:
921 case dwarf::DW_TAG_union_type:
922 case dwarf::DW_TAG_class_type: {
923 // Add elements to structure type.
924 DINodeArray Elements = CTy->getElements();
925 for (const auto *Element : Elements) {
928 if (auto *SP = dyn_cast<DISubprogram>(Element))
929 getOrCreateSubprogramDIE(SP);
930 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
931 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
932 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
933 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
934 } else if (DDTy->isStaticMember()) {
935 getOrCreateStaticMemberDIE(DDTy);
937 constructMemberDIE(Buffer, DDTy);
939 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
940 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
941 StringRef PropertyName = Property->getName();
942 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
943 if (Property->getType())
944 addType(ElemDie, resolve(Property->getType()));
945 addSourceLine(ElemDie, Property);
946 StringRef GetterName = Property->getGetterName();
947 if (!GetterName.empty())
948 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
949 StringRef SetterName = Property->getSetterName();
950 if (!SetterName.empty())
951 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
952 if (unsigned PropertyAttributes = Property->getAttributes())
953 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
958 if (CTy->isAppleBlockExtension())
959 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
961 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
962 // inside C++ composite types to point to the base class with the vtable.
963 // Rust uses DW_AT_containing_type to link a vtable to the type
964 // for which it was created.
965 if (auto *ContainingType = resolve(CTy->getVTableHolder()))
966 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
967 *getOrCreateTypeDIE(ContainingType));
969 if (CTy->isObjcClassComplete())
970 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
972 // Add template parameters to a class, structure or union types.
973 // FIXME: The support isn't in the metadata for this yet.
974 if (Tag == dwarf::DW_TAG_class_type ||
975 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
976 addTemplateParams(Buffer, CTy->getTemplateParams());
984 // Add name if not anonymous or intermediate type.
986 addString(Buffer, dwarf::DW_AT_name, Name);
988 if (Tag == dwarf::DW_TAG_enumeration_type ||
989 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
990 Tag == dwarf::DW_TAG_union_type) {
991 // Add size if non-zero (derived types might be zero-sized.)
992 // TODO: Do we care about size for enum forward declarations?
994 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
995 else if (!CTy->isForwardDecl())
996 // Add zero size if it is not a forward declaration.
997 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
999 // If we're a forward decl, say so.
1000 if (CTy->isForwardDecl())
1001 addFlag(Buffer, dwarf::DW_AT_declaration);
1003 // Add source line info if available.
1004 if (!CTy->isForwardDecl())
1005 addSourceLine(Buffer, CTy);
1007 // No harm in adding the runtime language to the declaration.
1008 unsigned RLang = CTy->getRuntimeLang();
1010 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1013 // Add align info if available.
1014 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1015 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1020 void DwarfUnit::constructTemplateTypeParameterDIE(
1021 DIE &Buffer, const DITemplateTypeParameter *TP) {
1023 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1024 // Add the type if it exists, it could be void and therefore no type.
1026 addType(ParamDIE, resolve(TP->getType()));
1027 if (!TP->getName().empty())
1028 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1031 void DwarfUnit::constructTemplateValueParameterDIE(
1032 DIE &Buffer, const DITemplateValueParameter *VP) {
1033 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1035 // Add the type if there is one, template template and template parameter
1036 // packs will not have a type.
1037 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1038 addType(ParamDIE, resolve(VP->getType()));
1039 if (!VP->getName().empty())
1040 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1041 if (Metadata *Val = VP->getValue()) {
1042 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1043 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1044 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1045 // We cannot describe the location of dllimport'd entities: the
1046 // computation of their address requires loads from the IAT.
1047 if (!GV->hasDLLImportStorageClass()) {
1048 // For declaration non-type template parameters (such as global values
1050 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1051 addOpAddress(*Loc, Asm->getSymbol(GV));
1052 // Emit DW_OP_stack_value to use the address as the immediate value of
1053 // the parameter, rather than a pointer to it.
1054 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1055 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1057 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1058 assert(isa<MDString>(Val));
1059 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1060 cast<MDString>(Val)->getString());
1061 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1062 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1067 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1068 // Construct the context before querying for the existence of the DIE in case
1069 // such construction creates the DIE.
1070 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1072 if (DIE *NDie = getDIE(NS))
1074 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1076 StringRef Name = NS->getName();
1078 addString(NDie, dwarf::DW_AT_name, NS->getName());
1080 Name = "(anonymous namespace)";
1081 DD->addAccelNamespace(Name, NDie);
1082 addGlobalName(Name, NDie, NS->getScope());
1083 if (NS->getExportSymbols())
1084 addFlag(NDie, dwarf::DW_AT_export_symbols);
1088 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1089 // Construct the context before querying for the existence of the DIE in case
1090 // such construction creates the DIE.
1091 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1093 if (DIE *MDie = getDIE(M))
1095 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1097 if (!M->getName().empty()) {
1098 addString(MDie, dwarf::DW_AT_name, M->getName());
1099 addGlobalName(M->getName(), MDie, M->getScope());
1101 if (!M->getConfigurationMacros().empty())
1102 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1103 M->getConfigurationMacros());
1104 if (!M->getIncludePath().empty())
1105 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1106 if (!M->getISysRoot().empty())
1107 addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1112 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1113 // Construct the context before querying for the existence of the DIE in case
1114 // such construction creates the DIE (as is the case for member function
1117 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1119 if (DIE *SPDie = getDIE(SP))
1122 if (auto *SPDecl = SP->getDeclaration()) {
1124 // Add subprogram definitions to the CU die directly.
1125 ContextDIE = &getUnitDie();
1126 // Build the decl now to ensure it precedes the definition.
1127 getOrCreateSubprogramDIE(SPDecl);
1131 // DW_TAG_inlined_subroutine may refer to this DIE.
1132 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1134 // Stop here and fill this in later, depending on whether or not this
1135 // subprogram turns out to have inlined instances or not.
1136 if (SP->isDefinition())
1139 applySubprogramAttributes(SP, SPDie);
1143 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1145 DIE *DeclDie = nullptr;
1146 StringRef DeclLinkageName;
1147 if (auto *SPDecl = SP->getDeclaration()) {
1148 DeclDie = getDIE(SPDecl);
1149 assert(DeclDie && "This DIE should've already been constructed when the "
1150 "definition DIE was created in "
1151 "getOrCreateSubprogramDIE");
1152 // Look at the Decl's linkage name only if we emitted it.
1153 if (DD->useAllLinkageNames())
1154 DeclLinkageName = SPDecl->getLinkageName();
1156 getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1157 unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1158 if (DeclID != DefID)
1159 addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1161 if (SP->getLine() != SPDecl->getLine())
1162 addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1165 // Add function template parameters.
1166 addTemplateParams(SPDie, SP->getTemplateParams());
1168 // Add the linkage name if we have one and it isn't in the Decl.
1169 StringRef LinkageName = SP->getLinkageName();
1170 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1171 LinkageName == DeclLinkageName) &&
1172 "decl has a linkage name and it is different");
1173 if (DeclLinkageName.empty() &&
1174 // Always emit it for abstract subprograms.
1175 (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1176 addLinkageName(SPDie, LinkageName);
1181 // Refer to the function declaration where all the other attributes will be
1183 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1187 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1188 bool SkipSPAttributes) {
1189 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1190 // and its source location.
1191 bool SkipSPSourceLocation = SkipSPAttributes &&
1192 !CUNode->getDebugInfoForProfiling();
1193 if (!SkipSPSourceLocation)
1194 if (applySubprogramDefinitionAttributes(SP, SPDie))
1197 // Constructors and operators for anonymous aggregates do not have names.
1198 if (!SP->getName().empty())
1199 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1201 if (!SkipSPSourceLocation)
1202 addSourceLine(SPDie, SP);
1204 // Skip the rest of the attributes under -gmlt to save space.
1205 if (SkipSPAttributes)
1208 // Add the prototype if we have a prototype and we have a C like
1210 uint16_t Language = getLanguage();
1211 if (SP->isPrototyped() &&
1212 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1213 Language == dwarf::DW_LANG_ObjC))
1214 addFlag(SPDie, dwarf::DW_AT_prototyped);
1217 DITypeRefArray Args;
1218 if (const DISubroutineType *SPTy = SP->getType()) {
1219 Args = SPTy->getTypeArray();
1223 // Add a DW_AT_calling_convention if this has an explicit convention.
1224 if (CC && CC != dwarf::DW_CC_normal)
1225 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1227 // Add a return type. If this is a type like a C/C++ void type we don't add a
1230 if (auto Ty = resolve(Args[0]))
1233 unsigned VK = SP->getVirtuality();
1235 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1236 if (SP->getVirtualIndex() != -1u) {
1237 DIELoc *Block = getDIELoc();
1238 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1239 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1240 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1242 ContainingTypeMap.insert(
1243 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1246 if (!SP->isDefinition()) {
1247 addFlag(SPDie, dwarf::DW_AT_declaration);
1249 // Add arguments. Do not add arguments for subprogram definition. They will
1250 // be handled while processing variables.
1251 constructSubprogramArguments(SPDie, Args);
1254 addThrownTypes(SPDie, SP->getThrownTypes());
1256 if (SP->isArtificial())
1257 addFlag(SPDie, dwarf::DW_AT_artificial);
1259 if (!SP->isLocalToUnit())
1260 addFlag(SPDie, dwarf::DW_AT_external);
1262 if (DD->useAppleExtensionAttributes()) {
1263 if (SP->isOptimized())
1264 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1266 if (unsigned isa = Asm->getISAEncoding())
1267 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1270 if (SP->isLValueReference())
1271 addFlag(SPDie, dwarf::DW_AT_reference);
1273 if (SP->isRValueReference())
1274 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1276 if (SP->isNoReturn())
1277 addFlag(SPDie, dwarf::DW_AT_noreturn);
1279 if (SP->isProtected())
1280 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1281 dwarf::DW_ACCESS_protected);
1282 else if (SP->isPrivate())
1283 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1284 dwarf::DW_ACCESS_private);
1285 else if (SP->isPublic())
1286 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1287 dwarf::DW_ACCESS_public);
1289 if (SP->isExplicit())
1290 addFlag(SPDie, dwarf::DW_AT_explicit);
1292 if (SP->isMainSubprogram())
1293 addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1296 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1298 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1299 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1301 // The LowerBound value defines the lower bounds which is typically zero for
1302 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1303 // Count == -1 then the array is unbounded and we do not emit
1304 // DW_AT_lower_bound and DW_AT_count attributes.
1305 int64_t LowerBound = SR->getLowerBound();
1306 int64_t DefaultLowerBound = getDefaultLowerBound();
1307 int64_t Count = SR->getCount();
1309 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1310 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1313 // FIXME: An unbounded array should reference the expression that defines
1315 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1318 DIE *DwarfUnit::getIndexTyDie() {
1321 // Construct an integer type to use for indexes.
1322 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1323 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1324 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1325 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1326 dwarf::DW_ATE_unsigned);
1330 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1331 if (CTy->isVector())
1332 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1334 // Emit the element type.
1335 addType(Buffer, resolve(CTy->getBaseType()));
1337 // Get an anonymous type for index type.
1338 // FIXME: This type should be passed down from the front end
1339 // as different languages may have different sizes for indexes.
1340 DIE *IdxTy = getIndexTyDie();
1342 // Add subranges to array type.
1343 DINodeArray Elements = CTy->getElements();
1344 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1345 // FIXME: Should this really be such a loose cast?
1346 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1347 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1348 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1352 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1353 DINodeArray Elements = CTy->getElements();
1355 // Add enumerators to enumeration type.
1356 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1357 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1359 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1360 StringRef Name = Enum->getName();
1361 addString(Enumerator, dwarf::DW_AT_name, Name);
1362 int64_t Value = Enum->getValue();
1363 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1367 const DIType *DTy = resolve(CTy->getBaseType());
1369 addType(Buffer, DTy);
1370 addFlag(Buffer, dwarf::DW_AT_enum_class);
1374 void DwarfUnit::constructContainingTypeDIEs() {
1375 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1377 DIE &SPDie = *CI->first;
1378 const DINode *D = CI->second;
1381 DIE *NDie = getDIE(D);
1384 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1388 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1389 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1390 StringRef Name = DT->getName();
1392 addString(MemberDie, dwarf::DW_AT_name, Name);
1394 addType(MemberDie, resolve(DT->getBaseType()));
1396 addSourceLine(MemberDie, DT);
1398 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1400 // For C++, virtual base classes are not at fixed offset. Use following
1401 // expression to extract appropriate offset from vtable.
1402 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1404 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1405 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1406 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1407 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1408 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1409 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1410 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1411 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1413 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1415 uint64_t Size = DT->getSizeInBits();
1416 uint64_t FieldSize = DD->getBaseTypeSize(DT);
1417 uint32_t AlignInBytes = DT->getAlignInBytes();
1418 uint64_t OffsetInBytes;
1420 bool IsBitfield = FieldSize && Size != FieldSize;
1422 // Handle bitfield, assume bytes are 8 bits.
1423 if (DD->useDWARF2Bitfields())
1424 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1425 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1427 uint64_t Offset = DT->getOffsetInBits();
1428 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1429 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1430 // which can't be done with bitfields. Thus we use FieldSize here.
1431 uint32_t AlignInBits = FieldSize;
1432 uint32_t AlignMask = ~(AlignInBits - 1);
1433 // The bits from the start of the storage unit to the start of the field.
1434 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1435 // The byte offset of the field's aligned storage unit inside the struct.
1436 OffsetInBytes = (Offset - StartBitOffset) / 8;
1438 if (DD->useDWARF2Bitfields()) {
1439 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1440 uint64_t FieldOffset = (HiMark - FieldSize);
1441 Offset -= FieldOffset;
1443 // Maybe we need to work from the other end.
1444 if (Asm->getDataLayout().isLittleEndian())
1445 Offset = FieldSize - (Offset + Size);
1447 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1448 OffsetInBytes = FieldOffset >> 3;
1450 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1453 // This is not a bitfield.
1454 OffsetInBytes = DT->getOffsetInBits() / 8;
1456 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1460 if (DD->getDwarfVersion() <= 2) {
1461 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1462 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1463 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1464 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1465 } else if (!IsBitfield || DD->useDWARF2Bitfields())
1466 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1470 if (DT->isProtected())
1471 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1472 dwarf::DW_ACCESS_protected);
1473 else if (DT->isPrivate())
1474 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1475 dwarf::DW_ACCESS_private);
1476 // Otherwise C++ member and base classes are considered public.
1477 else if (DT->isPublic())
1478 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1479 dwarf::DW_ACCESS_public);
1480 if (DT->isVirtual())
1481 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1482 dwarf::DW_VIRTUALITY_virtual);
1484 // Objective-C properties.
1485 if (DINode *PNode = DT->getObjCProperty())
1486 if (DIE *PDie = getDIE(PNode))
1487 MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1488 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1490 if (DT->isArtificial())
1491 addFlag(MemberDie, dwarf::DW_AT_artificial);
1494 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1498 // Construct the context before querying for the existence of the DIE in case
1499 // such construction creates the DIE.
1500 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1501 assert(dwarf::isType(ContextDIE->getTag()) &&
1502 "Static member should belong to a type.");
1504 if (DIE *StaticMemberDIE = getDIE(DT))
1505 return StaticMemberDIE;
1507 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1509 const DIType *Ty = resolve(DT->getBaseType());
1511 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1512 addType(StaticMemberDIE, Ty);
1513 addSourceLine(StaticMemberDIE, DT);
1514 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1515 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1517 // FIXME: We could omit private if the parent is a class_type, and
1518 // public if the parent is something else.
1519 if (DT->isProtected())
1520 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1521 dwarf::DW_ACCESS_protected);
1522 else if (DT->isPrivate())
1523 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1524 dwarf::DW_ACCESS_private);
1525 else if (DT->isPublic())
1526 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1527 dwarf::DW_ACCESS_public);
1529 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1530 addConstantValue(StaticMemberDIE, CI, Ty);
1531 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1532 addConstantFPValue(StaticMemberDIE, CFP);
1534 if (uint32_t AlignInBytes = DT->getAlignInBytes())
1535 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1538 return &StaticMemberDIE;
1541 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1542 // Emit size of content not including length itself
1543 Asm->OutStreamer->AddComment("Length of Unit");
1544 Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1546 Asm->OutStreamer->AddComment("DWARF version number");
1547 unsigned Version = DD->getDwarfVersion();
1548 Asm->EmitInt16(Version);
1550 // DWARF v5 reorders the address size and adds a unit type.
1552 Asm->OutStreamer->AddComment("DWARF Unit Type");
1554 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1555 Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1558 // We share one abbreviations table across all units so it's always at the
1559 // start of the section. Use a relocatable offset where needed to ensure
1560 // linking doesn't invalidate that offset.
1561 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1562 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1566 Asm->emitDwarfSymbolReference(
1567 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1570 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1571 Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1575 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1576 DwarfUnit::emitCommonHeader(UseOffsets,
1577 DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1578 : dwarf::DW_UT_type);
1579 Asm->OutStreamer->AddComment("Type Signature");
1580 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1581 Asm->OutStreamer->AddComment("Type DIE Offset");
1582 // In a skeleton type unit there is no type DIE so emit a zero offset.
1583 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1584 sizeof(Ty->getOffset()));
1588 DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
1589 const MCSymbol *Hi, const MCSymbol *Lo) {
1590 return Die.addValue(DIEValueAllocator, Attribute,
1591 DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1592 : dwarf::DW_FORM_data4,
1593 new (DIEValueAllocator) DIEDelta(Hi, Lo));
1597 DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
1598 const MCSymbol *Label, const MCSymbol *Sec) {
1599 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1600 return addLabel(Die, Attribute,
1601 DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1602 : dwarf::DW_FORM_data4,
1604 return addSectionDelta(Die, Attribute, Label, Sec);
1607 bool DwarfTypeUnit::isDwoUnit() const {
1608 // Since there are no skeleton type units, all type units are dwo type units
1609 // when split DWARF is being used.
1610 return DD->useSplitDwarf();
1613 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1614 const DIScope *Context) {
1615 getCU().addGlobalNameForTypeUnit(Name, Context);
1618 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1619 const DIScope *Context) {
1620 getCU().addGlobalTypeUnitType(Ty, Context);
1623 const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1624 if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1628 return getSection()->getBeginSymbol();