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 case dwarf::DW_LANG_C89:
102 case dwarf::DW_LANG_C99:
103 case dwarf::DW_LANG_C:
104 case dwarf::DW_LANG_C_plus_plus:
105 case dwarf::DW_LANG_ObjC:
106 case dwarf::DW_LANG_ObjC_plus_plus:
109 case dwarf::DW_LANG_Fortran77:
110 case dwarf::DW_LANG_Fortran90:
111 case dwarf::DW_LANG_Fortran95:
114 // The languages below have valid values only if the DWARF version >= 4.
115 case dwarf::DW_LANG_Java:
116 case dwarf::DW_LANG_Python:
117 case dwarf::DW_LANG_UPC:
118 case dwarf::DW_LANG_D:
119 if (dwarf::DWARF_VERSION >= 4)
123 case dwarf::DW_LANG_Ada83:
124 case dwarf::DW_LANG_Ada95:
125 case dwarf::DW_LANG_Cobol74:
126 case dwarf::DW_LANG_Cobol85:
127 case dwarf::DW_LANG_Modula2:
128 case dwarf::DW_LANG_Pascal83:
129 case dwarf::DW_LANG_PLI:
130 if (dwarf::DWARF_VERSION >= 4)
134 // The languages below have valid values only if the DWARF version >= 5.
135 case dwarf::DW_LANG_OpenCL:
136 case dwarf::DW_LANG_Go:
137 case dwarf::DW_LANG_Haskell:
138 case dwarf::DW_LANG_C_plus_plus_03:
139 case dwarf::DW_LANG_C_plus_plus_11:
140 case dwarf::DW_LANG_OCaml:
141 case dwarf::DW_LANG_Rust:
142 case dwarf::DW_LANG_C11:
143 case dwarf::DW_LANG_Swift:
144 case dwarf::DW_LANG_Dylan:
145 case dwarf::DW_LANG_C_plus_plus_14:
146 if (dwarf::DWARF_VERSION >= 5)
150 case dwarf::DW_LANG_Modula3:
151 case dwarf::DW_LANG_Julia:
152 case dwarf::DW_LANG_Fortran03:
153 case dwarf::DW_LANG_Fortran08:
154 if (dwarf::DWARF_VERSION >= 5)
162 /// Check whether the DIE for this MDNode can be shared across CUs.
163 static bool isShareableAcrossCUs(const DINode *D) {
164 // When the MDNode can be part of the type system, the DIE can be shared
166 // Combining type units and cross-CU DIE sharing is lower value (since
167 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
168 // level already) but may be implementable for some value in projects
169 // building multiple independent libraries with LTO and then linking those
171 return (isa<DIType>(D) ||
172 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
173 !GenerateDwarfTypeUnits;
176 DIE *DwarfUnit::getDIE(const DINode *D) const {
177 if (isShareableAcrossCUs(D))
178 return DU->getDIE(D);
179 return MDNodeToDieMap.lookup(D);
182 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
183 if (isShareableAcrossCUs(Desc)) {
184 DU->insertDIE(Desc, D);
187 MDNodeToDieMap.insert(std::make_pair(Desc, D));
190 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
191 if (DD->getDwarfVersion() >= 4)
192 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
195 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
199 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
200 Optional<dwarf::Form> Form, uint64_t Integer) {
202 Form = DIEInteger::BestForm(false, Integer);
203 assert(Form != dwarf::DW_FORM_implicit_const &&
204 "DW_FORM_implicit_const is used only for signed integers");
205 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
208 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
210 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
213 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
214 Optional<dwarf::Form> Form, int64_t Integer) {
216 Form = DIEInteger::BestForm(true, Integer);
217 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
220 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
222 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
225 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
227 Die.addValue(DIEValueAllocator, Attribute,
228 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
229 DIEString(DU->getStringPool().getEntry(*Asm, String)));
232 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
233 dwarf::Attribute Attribute,
235 const MCSymbol *Label) {
236 return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
239 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
240 addLabel(Die, (dwarf::Attribute)0, Form, Label);
243 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
245 if (DD->getDwarfVersion() >= 4)
246 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
248 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
251 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
252 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
253 : getCU().getOrCreateSourceID(FileName, DirName);
256 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
257 if (!DD->useSplitDwarf()) {
258 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
259 addLabel(Die, dwarf::DW_FORM_udata, Sym);
261 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
262 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
263 DD->getAddressPool().getIndex(Sym));
267 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
268 const MCSymbol *Hi, const MCSymbol *Lo) {
269 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
270 new (DIEValueAllocator) DIEDelta(Hi, Lo));
273 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
274 addDIEEntry(Die, Attribute, DIEEntry(Entry));
277 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
278 // Flag the type unit reference as a declaration so that if it contains
279 // members (implicit special members, static data member definitions, member
280 // declarations for definitions in this CU, etc) consumers don't get confused
281 // and think this is a full definition.
282 addFlag(Die, dwarf::DW_AT_declaration);
284 Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
285 dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
288 void DwarfUnit::addDIETypeSignature(DIE &Die, dwarf::Attribute Attribute,
289 StringRef Identifier) {
290 uint64_t Signature = DD->makeTypeSignature(Identifier);
291 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_ref_sig8,
292 DIEInteger(Signature));
295 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
297 const DIEUnit *CU = Die.getUnit();
298 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
300 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
301 CU = getUnitDie().getUnit();
303 EntryCU = getUnitDie().getUnit();
304 Die.addValue(DIEValueAllocator, Attribute,
305 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
309 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
310 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
316 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
317 Loc->ComputeSize(Asm);
318 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
319 Die.addValue(DIEValueAllocator, Attribute,
320 Loc->BestForm(DD->getDwarfVersion()), Loc);
323 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
325 Block->ComputeSize(Asm);
326 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
327 Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
330 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
331 StringRef Directory) {
335 unsigned FileID = getOrCreateSourceID(File, Directory);
336 assert(FileID && "Invalid file id");
337 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
338 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
341 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
344 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
345 V->getScope()->getDirectory());
348 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
351 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
354 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
357 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
360 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
363 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
366 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
369 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
372 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
373 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
376 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
377 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
378 gives the variable VarName either the struct, or a pointer to the struct, as
379 its type. This is necessary for various behind-the-scenes things the
380 compiler needs to do with by-reference variables in Blocks.
382 However, as far as the original *programmer* is concerned, the variable
383 should still have type 'SomeType', as originally declared.
385 The function getBlockByrefType dives into the __Block_byref_x_VarName
386 struct to find the original type of the variable, which is then assigned to
387 the variable's Debug Information Entry as its real type. So far, so good.
388 However now the debugger will expect the variable VarName to have the type
389 SomeType. So we need the location attribute for the variable to be an
390 expression that explains to the debugger how to navigate through the
391 pointers and struct to find the actual variable of type SomeType.
393 The following function does just that. We start by getting
394 the "normal" location for the variable. This will be the location
395 of either the struct __Block_byref_x_VarName or the pointer to the
396 struct __Block_byref_x_VarName.
398 The struct will look something like:
400 struct __Block_byref_x_VarName {
402 struct __Block_byref_x_VarName *forwarding;
403 ... <various other fields>
405 ... <maybe more fields>
408 If we are given the struct directly (as our starting point) we
409 need to tell the debugger to:
411 1). Add the offset of the forwarding field.
413 2). Follow that pointer to get the real __Block_byref_x_VarName
414 struct to use (the real one may have been copied onto the heap).
416 3). Add the offset for the field VarName, to find the actual variable.
418 If we started with a pointer to the struct, then we need to
419 dereference that pointer first, before the other steps.
420 Translating this into DWARF ops, we will need to append the following
421 to the current location description for the variable:
423 DW_OP_deref -- optional, if we start with a pointer
424 DW_OP_plus_uconst <forward_fld_offset>
426 DW_OP_plus_uconst <varName_fld_offset>
428 That is what this function does. */
430 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
431 dwarf::Attribute Attribute,
432 const MachineLocation &Location) {
433 const DIType *Ty = DV.getType();
434 const DIType *TmpTy = Ty;
435 uint16_t Tag = Ty->getTag();
436 bool isPointer = false;
438 StringRef varName = DV.getName();
440 if (Tag == dwarf::DW_TAG_pointer_type) {
441 auto *DTy = cast<DIDerivedType>(Ty);
442 TmpTy = resolve(DTy->getBaseType());
446 // Find the __forwarding field and the variable field in the __Block_byref
448 DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
449 const DIDerivedType *varField = nullptr;
450 const DIDerivedType *forwardingField = nullptr;
452 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
453 auto *DT = cast<DIDerivedType>(Fields[i]);
454 StringRef fieldName = DT->getName();
455 if (fieldName == "__forwarding")
456 forwardingField = DT;
457 else if (fieldName == varName)
461 // Get the offsets for the forwarding field and the variable field.
462 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
463 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
465 // Decode the original location, and use that as the start of the byref
466 // variable's location.
467 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
468 SmallVector<uint64_t, 6> DIExpr;
469 DIEDwarfExpression Expr(*Asm, *this, *Loc);
472 if (Location.isReg())
473 validReg = Expr.AddMachineReg(*Asm->MF->getSubtarget().getRegisterInfo(),
477 Expr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(),
478 Location.getReg(), Location.getOffset());
483 // If we started with a pointer to the __Block_byref... struct, then
484 // the first thing we need to do is dereference the pointer (DW_OP_deref).
486 DIExpr.push_back(dwarf::DW_OP_deref);
488 // Next add the offset for the '__forwarding' field:
489 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
490 // adding the offset if it's 0.
491 if (forwardingFieldOffset > 0) {
492 DIExpr.push_back(dwarf::DW_OP_plus);
493 DIExpr.push_back(forwardingFieldOffset);
496 // Now dereference the __forwarding field to get to the real __Block_byref
497 // struct: DW_OP_deref.
498 DIExpr.push_back(dwarf::DW_OP_deref);
500 // Now that we've got the real __Block_byref... struct, add the offset
501 // for the variable's field to get to the location of the actual variable:
502 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
503 if (varFieldOffset > 0) {
504 DIExpr.push_back(dwarf::DW_OP_plus);
505 DIExpr.push_back(varFieldOffset);
507 Expr.AddExpression(makeArrayRef(DIExpr));
510 // Now attach the location information to the DIE.
511 addBlock(Die, Attribute, Loc);
514 /// Return true if type encoding is unsigned.
515 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
516 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
517 // FIXME: Enums without a fixed underlying type have unknown signedness
518 // here, leading to incorrectly emitted constants.
519 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
522 // (Pieces of) aggregate types that get hacked apart by SROA may be
523 // represented by a constant. Encode them as unsigned bytes.
527 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
528 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
529 // Encode pointer constants as unsigned bytes. This is used at least for
530 // null pointer constant emission.
531 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
532 // here, but accept them for now due to a bug in SROA producing bogus
534 if (T == dwarf::DW_TAG_pointer_type ||
535 T == dwarf::DW_TAG_ptr_to_member_type ||
536 T == dwarf::DW_TAG_reference_type ||
537 T == dwarf::DW_TAG_rvalue_reference_type)
539 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
540 T == dwarf::DW_TAG_volatile_type ||
541 T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
542 DITypeRef Deriv = DTy->getBaseType();
543 assert(Deriv && "Expected valid base type");
544 return isUnsignedDIType(DD, DD->resolve(Deriv));
547 auto *BTy = cast<DIBasicType>(Ty);
548 unsigned Encoding = BTy->getEncoding();
549 assert((Encoding == dwarf::DW_ATE_unsigned ||
550 Encoding == dwarf::DW_ATE_unsigned_char ||
551 Encoding == dwarf::DW_ATE_signed ||
552 Encoding == dwarf::DW_ATE_signed_char ||
553 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
554 Encoding == dwarf::DW_ATE_boolean ||
555 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
556 Ty->getName() == "decltype(nullptr)")) &&
557 "Unsupported encoding");
558 return Encoding == dwarf::DW_ATE_unsigned ||
559 Encoding == dwarf::DW_ATE_unsigned_char ||
560 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
561 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
564 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
565 assert(MO.isFPImm() && "Invalid machine operand!");
566 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
567 APFloat FPImm = MO.getFPImm()->getValueAPF();
569 // Get the raw data form of the floating point.
570 const APInt FltVal = FPImm.bitcastToAPInt();
571 const char *FltPtr = (const char *)FltVal.getRawData();
573 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
574 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
575 int Incr = (LittleEndian ? 1 : -1);
576 int Start = (LittleEndian ? 0 : NumBytes - 1);
577 int Stop = (LittleEndian ? NumBytes : -1);
579 // Output the constant to DWARF one byte at a time.
580 for (; Start != Stop; Start += Incr)
581 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
583 addBlock(Die, dwarf::DW_AT_const_value, Block);
586 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
587 // Pass this down to addConstantValue as an unsigned bag of bits.
588 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
591 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
593 addConstantValue(Die, CI->getValue(), Ty);
596 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
598 assert(MO.isImm() && "Invalid machine operand!");
600 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
603 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
604 // FIXME: This is a bit conservative/simple - it emits negative values always
605 // sign extended to 64 bits rather than minimizing the number of bytes.
606 addUInt(Die, dwarf::DW_AT_const_value,
607 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
610 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
611 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
614 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
615 unsigned CIBitWidth = Val.getBitWidth();
616 if (CIBitWidth <= 64) {
617 addConstantValue(Die, Unsigned,
618 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
622 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
624 // Get the raw data form of the large APInt.
625 const uint64_t *Ptr64 = Val.getRawData();
627 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
628 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
630 // Output the constant to DWARF one byte at a time.
631 for (int i = 0; i < NumBytes; i++) {
634 c = Ptr64[i / 8] >> (8 * (i & 7));
636 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
637 addUInt(*Block, dwarf::DW_FORM_data1, c);
640 addBlock(Die, dwarf::DW_AT_const_value, Block);
643 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
644 if (!LinkageName.empty())
646 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
647 : dwarf::DW_AT_MIPS_linkage_name,
648 GlobalValue::getRealLinkageName(LinkageName));
651 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
652 // Add template parameters.
653 for (const auto *Element : TParams) {
654 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
655 constructTemplateTypeParameterDIE(Buffer, TTP);
656 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
657 constructTemplateValueParameterDIE(Buffer, TVP);
661 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
662 if (!Context || isa<DIFile>(Context))
663 return &getUnitDie();
664 if (auto *T = dyn_cast<DIType>(Context))
665 return getOrCreateTypeDIE(T);
666 if (auto *NS = dyn_cast<DINamespace>(Context))
667 return getOrCreateNameSpace(NS);
668 if (auto *SP = dyn_cast<DISubprogram>(Context))
669 return getOrCreateSubprogramDIE(SP);
670 if (auto *M = dyn_cast<DIModule>(Context))
671 return getOrCreateModule(M);
672 return getDIE(Context);
675 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
676 auto *Context = resolve(Ty->getScope());
677 DIE *ContextDIE = getOrCreateContextDIE(Context);
679 if (DIE *TyDIE = getDIE(Ty))
683 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
685 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
687 if (!Ty->isExternalTypeRef())
688 updateAcceleratorTables(Context, Ty, TyDIE);
692 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
696 auto *Ty = cast<DIType>(TyNode);
698 // DW_TAG_restrict_type is not supported in DWARF2
699 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
700 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
702 // DW_TAG_atomic_type is not supported in DWARF < 5
703 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
704 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
706 // Construct the context before querying for the existence of the DIE in case
707 // such construction creates the DIE.
708 auto *Context = resolve(Ty->getScope());
709 DIE *ContextDIE = getOrCreateContextDIE(Context);
712 if (DIE *TyDIE = getDIE(Ty))
716 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
718 updateAcceleratorTables(Context, Ty, TyDIE);
720 if (auto *BT = dyn_cast<DIBasicType>(Ty))
721 constructTypeDIE(TyDIE, BT);
722 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
723 constructTypeDIE(TyDIE, STy);
724 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
725 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
726 if (MDString *TypeId = CTy->getRawIdentifier()) {
727 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
728 // Skip updating the accelerator tables since this is not the full type.
731 constructTypeDIE(TyDIE, CTy);
733 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
739 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
740 const DIType *Ty, const DIE &TyDIE) {
741 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
742 bool IsImplementation = false;
743 if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
744 // A runtime language of 0 actually means C/C++ and that any
745 // non-negative value is some version of Objective-C/C++.
746 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
748 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
749 DD->addAccelType(Ty->getName(), TyDIE, Flags);
751 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
752 isa<DINamespace>(Context))
753 addGlobalType(Ty, TyDIE, Context);
757 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
758 dwarf::Attribute Attribute) {
759 assert(Ty && "Trying to add a type that doesn't exist?");
760 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
763 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
767 // FIXME: Decide whether to implement this for non-C++ languages.
768 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
772 SmallVector<const DIScope *, 1> Parents;
773 while (!isa<DICompileUnit>(Context)) {
774 Parents.push_back(Context);
775 if (Context->getScope())
776 Context = resolve(Context->getScope());
778 // Structure, etc types will have a NULL context if they're at the top
783 // Reverse iterate over our list to go from the outermost construct to the
785 for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
786 StringRef Name = Ctx->getName();
787 if (Name.empty() && isa<DINamespace>(Ctx))
788 Name = "(anonymous namespace)";
797 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
798 // Get core information.
799 StringRef Name = BTy->getName();
800 // Add name if not anonymous or intermediate type.
802 addString(Buffer, dwarf::DW_AT_name, Name);
804 // An unspecified type only has a name attribute.
805 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
808 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
811 uint64_t Size = BTy->getSizeInBits() >> 3;
812 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
815 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
816 // Get core information.
817 StringRef Name = DTy->getName();
818 uint64_t Size = DTy->getSizeInBits() >> 3;
819 uint16_t Tag = Buffer.getTag();
821 // Map to main type, void will not have a type.
822 const DIType *FromTy = resolve(DTy->getBaseType());
824 addType(Buffer, FromTy);
826 // Add name if not anonymous or intermediate type.
828 addString(Buffer, dwarf::DW_AT_name, Name);
830 // Add size if non-zero (derived types might be zero-sized.)
831 if (Size && Tag != dwarf::DW_TAG_pointer_type
832 && Tag != dwarf::DW_TAG_ptr_to_member_type
833 && Tag != dwarf::DW_TAG_reference_type
834 && Tag != dwarf::DW_TAG_rvalue_reference_type)
835 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
837 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
839 Buffer, dwarf::DW_AT_containing_type,
840 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
841 // Add source line info if available and TyDesc is not a forward declaration.
842 if (!DTy->isForwardDecl())
843 addSourceLine(Buffer, DTy);
846 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
847 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
848 const DIType *Ty = resolve(Args[i]);
850 assert(i == N-1 && "Unspecified parameter must be the last argument");
851 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
853 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
855 if (Ty->isArtificial())
856 addFlag(Arg, dwarf::DW_AT_artificial);
861 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
862 // Add return type. A void return won't have a type.
863 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
865 if (auto RTy = resolve(Elements[0]))
866 addType(Buffer, RTy);
868 bool isPrototyped = true;
869 if (Elements.size() == 2 && !Elements[1])
870 isPrototyped = false;
872 constructSubprogramArguments(Buffer, Elements);
874 // Add prototype flag if we're dealing with a C language and the function has
876 uint16_t Language = getLanguage();
878 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
879 Language == dwarf::DW_LANG_ObjC))
880 addFlag(Buffer, dwarf::DW_AT_prototyped);
882 // Add a DW_AT_calling_convention if this has an explicit convention.
883 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
884 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
887 if (CTy->isLValueReference())
888 addFlag(Buffer, dwarf::DW_AT_reference);
890 if (CTy->isRValueReference())
891 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
894 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
895 if (CTy->isExternalTypeRef()) {
896 StringRef Identifier = CTy->getIdentifier();
897 assert(!Identifier.empty() && "external type ref without identifier");
898 addFlag(Buffer, dwarf::DW_AT_declaration);
899 return addDIETypeSignature(Buffer, dwarf::DW_AT_signature, Identifier);
902 // Add name if not anonymous or intermediate type.
903 StringRef Name = CTy->getName();
905 uint64_t Size = CTy->getSizeInBits() >> 3;
906 uint16_t Tag = Buffer.getTag();
909 case dwarf::DW_TAG_array_type:
910 constructArrayTypeDIE(Buffer, CTy);
912 case dwarf::DW_TAG_enumeration_type:
913 constructEnumTypeDIE(Buffer, CTy);
915 case dwarf::DW_TAG_structure_type:
916 case dwarf::DW_TAG_union_type:
917 case dwarf::DW_TAG_class_type: {
918 // Add elements to structure type.
919 DINodeArray Elements = CTy->getElements();
920 for (const auto *Element : Elements) {
923 if (auto *SP = dyn_cast<DISubprogram>(Element))
924 getOrCreateSubprogramDIE(SP);
925 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
926 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
927 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
928 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
929 } else if (DDTy->isStaticMember()) {
930 getOrCreateStaticMemberDIE(DDTy);
932 constructMemberDIE(Buffer, DDTy);
934 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
935 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
936 StringRef PropertyName = Property->getName();
937 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
938 if (Property->getType())
939 addType(ElemDie, resolve(Property->getType()));
940 addSourceLine(ElemDie, Property);
941 StringRef GetterName = Property->getGetterName();
942 if (!GetterName.empty())
943 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
944 StringRef SetterName = Property->getSetterName();
945 if (!SetterName.empty())
946 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
947 if (unsigned PropertyAttributes = Property->getAttributes())
948 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
953 if (CTy->isAppleBlockExtension())
954 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
956 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
957 // inside C++ composite types to point to the base class with the vtable.
958 if (auto *ContainingType =
959 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
960 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
961 *getOrCreateTypeDIE(ContainingType));
963 if (CTy->isObjcClassComplete())
964 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
966 // Add template parameters to a class, structure or union types.
967 // FIXME: The support isn't in the metadata for this yet.
968 if (Tag == dwarf::DW_TAG_class_type ||
969 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
970 addTemplateParams(Buffer, CTy->getTemplateParams());
978 // Add name if not anonymous or intermediate type.
980 addString(Buffer, dwarf::DW_AT_name, Name);
982 if (Tag == dwarf::DW_TAG_enumeration_type ||
983 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
984 Tag == dwarf::DW_TAG_union_type) {
985 // Add size if non-zero (derived types might be zero-sized.)
986 // TODO: Do we care about size for enum forward declarations?
988 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
989 else if (!CTy->isForwardDecl())
990 // Add zero size if it is not a forward declaration.
991 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
993 // If we're a forward decl, say so.
994 if (CTy->isForwardDecl())
995 addFlag(Buffer, dwarf::DW_AT_declaration);
997 // Add source line info if available.
998 if (!CTy->isForwardDecl())
999 addSourceLine(Buffer, CTy);
1001 // No harm in adding the runtime language to the declaration.
1002 unsigned RLang = CTy->getRuntimeLang();
1004 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1007 // Add align info if available.
1008 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1009 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1014 void DwarfUnit::constructTemplateTypeParameterDIE(
1015 DIE &Buffer, const DITemplateTypeParameter *TP) {
1017 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1018 // Add the type if it exists, it could be void and therefore no type.
1020 addType(ParamDIE, resolve(TP->getType()));
1021 if (!TP->getName().empty())
1022 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1025 void DwarfUnit::constructTemplateValueParameterDIE(
1026 DIE &Buffer, const DITemplateValueParameter *VP) {
1027 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1029 // Add the type if there is one, template template and template parameter
1030 // packs will not have a type.
1031 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1032 addType(ParamDIE, resolve(VP->getType()));
1033 if (!VP->getName().empty())
1034 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1035 if (Metadata *Val = VP->getValue()) {
1036 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1037 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1038 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1039 // We cannot describe the location of dllimport'd entities: the
1040 // computation of their address requires loads from the IAT.
1041 if (!GV->hasDLLImportStorageClass()) {
1042 // For declaration non-type template parameters (such as global values
1044 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1045 addOpAddress(*Loc, Asm->getSymbol(GV));
1046 // Emit DW_OP_stack_value to use the address as the immediate value of
1047 // the parameter, rather than a pointer to it.
1048 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1049 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1051 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1052 assert(isa<MDString>(Val));
1053 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1054 cast<MDString>(Val)->getString());
1055 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1056 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1061 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1062 // Construct the context before querying for the existence of the DIE in case
1063 // such construction creates the DIE.
1064 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1066 if (DIE *NDie = getDIE(NS))
1068 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1070 StringRef Name = NS->getName();
1072 addString(NDie, dwarf::DW_AT_name, NS->getName());
1074 Name = "(anonymous namespace)";
1075 DD->addAccelNamespace(Name, NDie);
1076 addGlobalName(Name, NDie, NS->getScope());
1077 addSourceLine(NDie, NS);
1078 if (NS->getExportSymbols())
1079 addFlag(NDie, dwarf::DW_AT_export_symbols);
1083 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1084 // Construct the context before querying for the existence of the DIE in case
1085 // such construction creates the DIE.
1086 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1088 if (DIE *MDie = getDIE(M))
1090 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1092 if (!M->getName().empty()) {
1093 addString(MDie, dwarf::DW_AT_name, M->getName());
1094 addGlobalName(M->getName(), MDie, M->getScope());
1096 if (!M->getConfigurationMacros().empty())
1097 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1098 M->getConfigurationMacros());
1099 if (!M->getIncludePath().empty())
1100 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1101 if (!M->getISysRoot().empty())
1102 addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1107 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1108 // Construct the context before querying for the existence of the DIE in case
1109 // such construction creates the DIE (as is the case for member function
1112 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1114 if (DIE *SPDie = getDIE(SP))
1117 if (auto *SPDecl = SP->getDeclaration()) {
1119 // Add subprogram definitions to the CU die directly.
1120 ContextDIE = &getUnitDie();
1121 // Build the decl now to ensure it precedes the definition.
1122 getOrCreateSubprogramDIE(SPDecl);
1126 // DW_TAG_inlined_subroutine may refer to this DIE.
1127 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1129 // Stop here and fill this in later, depending on whether or not this
1130 // subprogram turns out to have inlined instances or not.
1131 if (SP->isDefinition())
1134 applySubprogramAttributes(SP, SPDie);
1138 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1140 DIE *DeclDie = nullptr;
1141 StringRef DeclLinkageName;
1142 if (auto *SPDecl = SP->getDeclaration()) {
1143 DeclDie = getDIE(SPDecl);
1144 assert(DeclDie && "This DIE should've already been constructed when the "
1145 "definition DIE was created in "
1146 "getOrCreateSubprogramDIE");
1147 // Look at the Decl's linkage name only if we emitted it.
1148 if (DD->useAllLinkageNames())
1149 DeclLinkageName = SPDecl->getLinkageName();
1151 getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1152 unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1153 if (DeclID != DefID)
1154 addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1156 if (SP->getLine() != SPDecl->getLine())
1157 addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1160 // Add function template parameters.
1161 addTemplateParams(SPDie, SP->getTemplateParams());
1163 // Add the linkage name if we have one and it isn't in the Decl.
1164 StringRef LinkageName = SP->getLinkageName();
1165 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1166 LinkageName == DeclLinkageName) &&
1167 "decl has a linkage name and it is different");
1168 if (DeclLinkageName.empty() &&
1169 // Always emit it for abstract subprograms.
1170 (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1171 addLinkageName(SPDie, LinkageName);
1176 // Refer to the function declaration where all the other attributes will be
1178 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1182 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1185 if (applySubprogramDefinitionAttributes(SP, SPDie))
1188 // Constructors and operators for anonymous aggregates do not have names.
1189 if (!SP->getName().empty())
1190 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1192 // Skip the rest of the attributes under -gmlt to save space.
1196 addSourceLine(SPDie, SP);
1198 // Add the prototype if we have a prototype and we have a C like
1200 uint16_t Language = getLanguage();
1201 if (SP->isPrototyped() &&
1202 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1203 Language == dwarf::DW_LANG_ObjC))
1204 addFlag(SPDie, dwarf::DW_AT_prototyped);
1207 DITypeRefArray Args;
1208 if (const DISubroutineType *SPTy = SP->getType()) {
1209 Args = SPTy->getTypeArray();
1213 // Add a DW_AT_calling_convention if this has an explicit convention.
1214 if (CC && CC != dwarf::DW_CC_normal)
1215 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1217 // Add a return type. If this is a type like a C/C++ void type we don't add a
1220 if (auto Ty = resolve(Args[0]))
1223 unsigned VK = SP->getVirtuality();
1225 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1226 if (SP->getVirtualIndex() != -1u) {
1227 DIELoc *Block = getDIELoc();
1228 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1229 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1230 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1232 ContainingTypeMap.insert(
1233 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1236 if (!SP->isDefinition()) {
1237 addFlag(SPDie, dwarf::DW_AT_declaration);
1239 // Add arguments. Do not add arguments for subprogram definition. They will
1240 // be handled while processing variables.
1241 constructSubprogramArguments(SPDie, Args);
1244 if (SP->isArtificial())
1245 addFlag(SPDie, dwarf::DW_AT_artificial);
1247 if (!SP->isLocalToUnit())
1248 addFlag(SPDie, dwarf::DW_AT_external);
1250 if (DD->useAppleExtensionAttributes()) {
1251 if (SP->isOptimized())
1252 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1254 if (unsigned isa = Asm->getISAEncoding())
1255 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1258 if (SP->isLValueReference())
1259 addFlag(SPDie, dwarf::DW_AT_reference);
1261 if (SP->isRValueReference())
1262 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1264 if (SP->isNoReturn())
1265 addFlag(SPDie, dwarf::DW_AT_noreturn);
1267 if (SP->isProtected())
1268 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1269 dwarf::DW_ACCESS_protected);
1270 else if (SP->isPrivate())
1271 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1272 dwarf::DW_ACCESS_private);
1273 else if (SP->isPublic())
1274 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1275 dwarf::DW_ACCESS_public);
1277 if (SP->isExplicit())
1278 addFlag(SPDie, dwarf::DW_AT_explicit);
1280 if (SP->isMainSubprogram())
1281 addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1284 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1286 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1287 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1289 // The LowerBound value defines the lower bounds which is typically zero for
1290 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1291 // Count == -1 then the array is unbounded and we do not emit
1292 // DW_AT_lower_bound and DW_AT_count attributes.
1293 int64_t LowerBound = SR->getLowerBound();
1294 int64_t DefaultLowerBound = getDefaultLowerBound();
1295 int64_t Count = SR->getCount();
1297 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1298 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1301 // FIXME: An unbounded array should reference the expression that defines
1303 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1306 DIE *DwarfUnit::getIndexTyDie() {
1309 // Construct an integer type to use for indexes.
1310 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1311 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1312 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1313 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1314 dwarf::DW_ATE_unsigned);
1318 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1319 if (CTy->isVector())
1320 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1322 // Emit the element type.
1323 addType(Buffer, resolve(CTy->getBaseType()));
1325 // Get an anonymous type for index type.
1326 // FIXME: This type should be passed down from the front end
1327 // as different languages may have different sizes for indexes.
1328 DIE *IdxTy = getIndexTyDie();
1330 // Add subranges to array type.
1331 DINodeArray Elements = CTy->getElements();
1332 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1333 // FIXME: Should this really be such a loose cast?
1334 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1335 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1336 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1340 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1341 DINodeArray Elements = CTy->getElements();
1343 // Add enumerators to enumeration type.
1344 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1345 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1347 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1348 StringRef Name = Enum->getName();
1349 addString(Enumerator, dwarf::DW_AT_name, Name);
1350 int64_t Value = Enum->getValue();
1351 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1355 const DIType *DTy = resolve(CTy->getBaseType());
1357 addType(Buffer, DTy);
1358 addFlag(Buffer, dwarf::DW_AT_enum_class);
1362 void DwarfUnit::constructContainingTypeDIEs() {
1363 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1365 DIE &SPDie = *CI->first;
1366 const DINode *D = CI->second;
1369 DIE *NDie = getDIE(D);
1372 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1376 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1377 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1378 StringRef Name = DT->getName();
1380 addString(MemberDie, dwarf::DW_AT_name, Name);
1382 addType(MemberDie, resolve(DT->getBaseType()));
1384 addSourceLine(MemberDie, DT);
1386 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1388 // For C++, virtual base classes are not at fixed offset. Use following
1389 // expression to extract appropriate offset from vtable.
1390 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1392 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1393 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1394 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1395 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1396 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1397 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1398 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1399 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1401 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1403 uint64_t Size = DT->getSizeInBits();
1404 uint64_t FieldSize = DD->getBaseTypeSize(DT);
1405 uint32_t AlignInBytes = DT->getAlignInBytes();
1406 uint64_t OffsetInBytes;
1408 bool IsBitfield = FieldSize && Size != FieldSize;
1410 // Handle bitfield, assume bytes are 8 bits.
1411 if (DD->useDWARF2Bitfields())
1412 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1413 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1415 uint64_t Offset = DT->getOffsetInBits();
1416 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1417 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1418 // which can't be done with bitfields. Thus we use FieldSize here.
1419 uint32_t AlignInBits = FieldSize;
1420 uint32_t AlignMask = ~(AlignInBits - 1);
1421 // The bits from the start of the storage unit to the start of the field.
1422 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1423 // The byte offset of the field's aligned storage unit inside the struct.
1424 OffsetInBytes = (Offset - StartBitOffset) / 8;
1426 if (DD->useDWARF2Bitfields()) {
1427 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1428 uint64_t FieldOffset = (HiMark - FieldSize);
1429 Offset -= FieldOffset;
1431 // Maybe we need to work from the other end.
1432 if (Asm->getDataLayout().isLittleEndian())
1433 Offset = FieldSize - (Offset + Size);
1435 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1436 OffsetInBytes = FieldOffset >> 3;
1438 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1441 // This is not a bitfield.
1442 OffsetInBytes = DT->getOffsetInBits() / 8;
1444 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1448 if (DD->getDwarfVersion() <= 2) {
1449 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1450 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1451 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1452 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1453 } else if (!IsBitfield || DD->useDWARF2Bitfields())
1454 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1458 if (DT->isProtected())
1459 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1460 dwarf::DW_ACCESS_protected);
1461 else if (DT->isPrivate())
1462 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1463 dwarf::DW_ACCESS_private);
1464 // Otherwise C++ member and base classes are considered public.
1465 else if (DT->isPublic())
1466 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1467 dwarf::DW_ACCESS_public);
1468 if (DT->isVirtual())
1469 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1470 dwarf::DW_VIRTUALITY_virtual);
1472 // Objective-C properties.
1473 if (DINode *PNode = DT->getObjCProperty())
1474 if (DIE *PDie = getDIE(PNode))
1475 MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1476 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1478 if (DT->isArtificial())
1479 addFlag(MemberDie, dwarf::DW_AT_artificial);
1482 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1486 // Construct the context before querying for the existence of the DIE in case
1487 // such construction creates the DIE.
1488 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1489 assert(dwarf::isType(ContextDIE->getTag()) &&
1490 "Static member should belong to a type.");
1492 if (DIE *StaticMemberDIE = getDIE(DT))
1493 return StaticMemberDIE;
1495 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1497 const DIType *Ty = resolve(DT->getBaseType());
1499 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1500 addType(StaticMemberDIE, Ty);
1501 addSourceLine(StaticMemberDIE, DT);
1502 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1503 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1505 // FIXME: We could omit private if the parent is a class_type, and
1506 // public if the parent is something else.
1507 if (DT->isProtected())
1508 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1509 dwarf::DW_ACCESS_protected);
1510 else if (DT->isPrivate())
1511 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1512 dwarf::DW_ACCESS_private);
1513 else if (DT->isPublic())
1514 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1515 dwarf::DW_ACCESS_public);
1517 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1518 addConstantValue(StaticMemberDIE, CI, Ty);
1519 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1520 addConstantFPValue(StaticMemberDIE, CFP);
1522 if (uint32_t AlignInBytes = DT->getAlignInBytes())
1523 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1526 return &StaticMemberDIE;
1529 void DwarfUnit::emitHeader(bool UseOffsets) {
1530 // Emit size of content not including length itself
1531 Asm->OutStreamer->AddComment("Length of Unit");
1532 Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1534 Asm->OutStreamer->AddComment("DWARF version number");
1535 Asm->EmitInt16(DD->getDwarfVersion());
1536 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1538 // We share one abbreviations table across all units so it's always at the
1539 // start of the section. Use a relocatable offset where needed to ensure
1540 // linking doesn't invalidate that offset.
1541 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1545 Asm->emitDwarfSymbolReference(
1546 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1548 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1549 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1552 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1553 DwarfUnit::emitHeader(UseOffsets);
1554 Asm->OutStreamer->AddComment("Type Signature");
1555 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1556 Asm->OutStreamer->AddComment("Type DIE Offset");
1557 // In a skeleton type unit there is no type DIE so emit a zero offset.
1558 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1559 sizeof(Ty->getOffset()));
1562 bool DwarfTypeUnit::isDwoUnit() const {
1563 // Since there are no skeleton type units, all type units are dwo type units
1564 // when split DWARF is being used.
1565 return DD->useSplitDwarf();