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"
16 #include "DwarfAccelTable.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfDebug.h"
19 #include "DwarfExpression.h"
20 #include "llvm/ADT/APFloat.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "dwarfdebug"
43 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
44 cl::desc("Generate DWARF4 type units."),
47 /// DwarfExpression implementation for DwarfUnit.
48 class DIEDwarfExpression : public DwarfExpression {
52 DIEDwarfExpression(TargetMachine &TM, DwarfUnit &DU, DIELoc &DIE)
53 : DwarfExpression(TM), DU(DU), DIE(DIE) {}
55 void EmitOp(uint8_t Op, const char* Comment = nullptr) override;
56 void EmitSigned(int Value) override;
57 void EmitUnsigned(unsigned Value) override;
58 unsigned getFrameRegister() override;
61 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
62 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
64 void DIEDwarfExpression::EmitSigned(int Value) {
65 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
67 void DIEDwarfExpression::EmitUnsigned(unsigned Value) {
68 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
70 unsigned DIEDwarfExpression::getFrameRegister() {
71 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
72 return TRI->getFrameRegister(*DU.getAsmPrinter()->MF);
76 /// Unit - Unit constructor.
77 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
78 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
79 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
80 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
81 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
82 UnitTag == dwarf::DW_TAG_type_unit);
83 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
86 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
87 DwarfDebug *DW, DwarfFile *DWU,
88 MCDwarfDwoLineTable *SplitLineTable)
89 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
90 CU(CU), SplitLineTable(SplitLineTable) {
92 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
95 /// ~Unit - Destructor for compile unit.
96 DwarfUnit::~DwarfUnit() {
97 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
98 DIEBlocks[j]->~DIEBlock();
99 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
100 DIELocs[j]->~DIELoc();
103 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
104 /// information entry.
105 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
106 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
110 /// getDefaultLowerBound - Return the default lower bound for an array. If the
111 /// DWARF version doesn't handle the language, return -1.
112 int64_t DwarfUnit::getDefaultLowerBound() const {
113 switch (getLanguage()) {
117 case dwarf::DW_LANG_C89:
118 case dwarf::DW_LANG_C99:
119 case dwarf::DW_LANG_C:
120 case dwarf::DW_LANG_C_plus_plus:
121 case dwarf::DW_LANG_ObjC:
122 case dwarf::DW_LANG_ObjC_plus_plus:
125 case dwarf::DW_LANG_Fortran77:
126 case dwarf::DW_LANG_Fortran90:
127 case dwarf::DW_LANG_Fortran95:
130 // The languages below have valid values only if the DWARF version >= 4.
131 case dwarf::DW_LANG_Java:
132 case dwarf::DW_LANG_Python:
133 case dwarf::DW_LANG_UPC:
134 case dwarf::DW_LANG_D:
135 if (dwarf::DWARF_VERSION >= 4)
139 case dwarf::DW_LANG_Ada83:
140 case dwarf::DW_LANG_Ada95:
141 case dwarf::DW_LANG_Cobol74:
142 case dwarf::DW_LANG_Cobol85:
143 case dwarf::DW_LANG_Modula2:
144 case dwarf::DW_LANG_Pascal83:
145 case dwarf::DW_LANG_PLI:
146 if (dwarf::DWARF_VERSION >= 4)
154 /// Check whether the DIE for this MDNode can be shared across CUs.
155 static bool isShareableAcrossCUs(DIDescriptor D) {
156 // When the MDNode can be part of the type system, the DIE can be shared
158 // Combining type units and cross-CU DIE sharing is lower value (since
159 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
160 // level already) but may be implementable for some value in projects
161 // building multiple independent libraries with LTO and then linking those
163 return (D.isType() ||
164 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
165 !GenerateDwarfTypeUnits;
168 /// getDIE - Returns the debug information entry map slot for the
169 /// specified debug variable. We delegate the request to DwarfDebug
170 /// when the DIE for this MDNode can be shared across CUs. The mappings
171 /// will be kept in DwarfDebug for shareable DIEs.
172 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
173 if (isShareableAcrossCUs(D))
174 return DU->getDIE(D);
175 return MDNodeToDieMap.lookup(D);
178 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
179 /// when the DIE for this MDNode can be shared across CUs. The mappings
180 /// will be kept in DwarfDebug for shareable DIEs.
181 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
182 if (isShareableAcrossCUs(Desc)) {
183 DU->insertDIE(Desc, D);
186 MDNodeToDieMap.insert(std::make_pair(Desc, D));
189 /// addFlag - Add a flag that is true.
190 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
191 if (DD->getDwarfVersion() >= 4)
192 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
194 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
197 /// addUInt - Add an unsigned integer attribute data and value.
199 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
200 Optional<dwarf::Form> Form, uint64_t Integer) {
202 Form = DIEInteger::BestForm(false, Integer);
203 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
205 Die.addValue(Attribute, *Form, Value);
208 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
209 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
212 /// addSInt - Add an signed integer attribute data and value.
214 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
215 Optional<dwarf::Form> Form, int64_t Integer) {
217 Form = DIEInteger::BestForm(true, Integer);
218 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
219 Die.addValue(Attribute, *Form, Value);
222 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
224 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
227 /// addString - Add a string attribute data and value. We always emit a
228 /// reference to the string pool instead of immediate strings so that DIEs have
229 /// more predictable sizes. In the case of split dwarf we emit an index
230 /// into another table which gets us the static offset into the string
232 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
235 return addLocalString(Die, Attribute, String);
237 addIndexedString(Die, Attribute, String);
240 void DwarfUnit::addIndexedString(DIE &Die, dwarf::Attribute Attribute,
242 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
243 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
244 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
245 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
248 /// addLocalString - Add a string attribute data and value. This is guaranteed
249 /// to be in the local string pool instead of indirected.
250 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
252 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
254 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
255 Value = new (DIEValueAllocator) DIELabel(Symb);
257 Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
258 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
259 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
262 /// addLabel - Add a Dwarf label attribute data and value.
264 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
265 const MCSymbol *Label) {
266 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
267 Die.addValue(Attribute, Form, Value);
270 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
271 addLabel(Die, (dwarf::Attribute)0, Form, Label);
274 /// addSectionOffset - Add an offset into a section attribute data and value.
276 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
278 if (DD->getDwarfVersion() >= 4)
279 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
281 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
284 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
285 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
286 : getCU().getOrCreateSourceID(FileName, DirName);
289 /// addOpAddress - Add a dwarf op address data and value using the
290 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
292 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
293 if (!DD->useSplitDwarf()) {
294 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
295 addLabel(Die, dwarf::DW_FORM_udata, Sym);
297 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
298 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
299 DD->getAddressPool().getIndex(Sym));
303 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
304 const MCSymbol *Hi, const MCSymbol *Lo) {
305 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
306 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
309 /// addDIEEntry - Add a DIE attribute data and value.
311 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
312 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
315 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
316 // Flag the type unit reference as a declaration so that if it contains
317 // members (implicit special members, static data member definitions, member
318 // declarations for definitions in this CU, etc) consumers don't get confused
319 // and think this is a full definition.
320 addFlag(Die, dwarf::DW_AT_declaration);
322 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
323 new (DIEValueAllocator) DIETypeSignature(Type));
326 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
328 const DIE *DieCU = Die.getUnitOrNull();
329 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
331 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
332 DieCU = &getUnitDie();
334 EntryCU = &getUnitDie();
335 Die.addValue(Attribute,
336 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
340 /// Create a DIE with the given Tag, add the DIE to its parent, and
341 /// call insertDIE if MD is not null.
342 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
343 assert(Tag != dwarf::DW_TAG_auto_variable &&
344 Tag != dwarf::DW_TAG_arg_variable);
345 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
346 DIE &Die = *Parent.getChildren().back();
352 /// addBlock - Add block data.
354 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
355 Loc->ComputeSize(Asm);
356 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
357 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
360 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
362 Block->ComputeSize(Asm);
363 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
364 Die.addValue(Attribute, Block->BestForm(), Block);
367 /// addSourceLine - Add location information to specified debug information
369 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
370 StringRef Directory) {
374 unsigned FileID = getOrCreateSourceID(File, Directory);
375 assert(FileID && "Invalid file id");
376 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
377 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
380 /// addSourceLine - Add location information to specified debug information
382 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
383 assert(V.isVariable());
385 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
386 V.getContext().getDirectory());
389 /// addSourceLine - Add location information to specified debug information
391 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
392 assert(G.isGlobalVariable());
394 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
397 /// addSourceLine - Add location information to specified debug information
399 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
400 assert(SP.isSubprogram());
402 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
405 /// addSourceLine - Add location information to specified debug information
407 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
410 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
413 /// addSourceLine - Add location information to specified debug information
415 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
416 assert(Ty.isObjCProperty());
418 DIFile File = Ty.getFile();
419 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
420 File.getDirectory());
423 /// addSourceLine - Add location information to specified debug information
425 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
428 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
431 /// addRegisterOp - Add register operand.
432 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
433 unsigned SizeInBits, unsigned OffsetInBits) {
434 DIEDwarfExpression Expr(Asm->TM, *this, TheDie);
435 Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
439 /// addRegisterOffset - Add register offset.
440 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
442 DIEDwarfExpression Expr(Asm->TM, *this, TheDie);
443 return Expr.AddMachineRegIndirect(Reg, Offset);
446 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
447 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
448 gives the variable VarName either the struct, or a pointer to the struct, as
449 its type. This is necessary for various behind-the-scenes things the
450 compiler needs to do with by-reference variables in Blocks.
452 However, as far as the original *programmer* is concerned, the variable
453 should still have type 'SomeType', as originally declared.
455 The function getBlockByrefType dives into the __Block_byref_x_VarName
456 struct to find the original type of the variable, which is then assigned to
457 the variable's Debug Information Entry as its real type. So far, so good.
458 However now the debugger will expect the variable VarName to have the type
459 SomeType. So we need the location attribute for the variable to be an
460 expression that explains to the debugger how to navigate through the
461 pointers and struct to find the actual variable of type SomeType.
463 The following function does just that. We start by getting
464 the "normal" location for the variable. This will be the location
465 of either the struct __Block_byref_x_VarName or the pointer to the
466 struct __Block_byref_x_VarName.
468 The struct will look something like:
470 struct __Block_byref_x_VarName {
472 struct __Block_byref_x_VarName *forwarding;
473 ... <various other fields>
475 ... <maybe more fields>
478 If we are given the struct directly (as our starting point) we
479 need to tell the debugger to:
481 1). Add the offset of the forwarding field.
483 2). Follow that pointer to get the real __Block_byref_x_VarName
484 struct to use (the real one may have been copied onto the heap).
486 3). Add the offset for the field VarName, to find the actual variable.
488 If we started with a pointer to the struct, then we need to
489 dereference that pointer first, before the other steps.
490 Translating this into DWARF ops, we will need to append the following
491 to the current location description for the variable:
493 DW_OP_deref -- optional, if we start with a pointer
494 DW_OP_plus_uconst <forward_fld_offset>
496 DW_OP_plus_uconst <varName_fld_offset>
498 That is what this function does. */
500 /// addBlockByrefAddress - Start with the address based on the location
501 /// provided, and generate the DWARF information necessary to find the
502 /// actual Block variable (navigating the Block struct) based on the
503 /// starting location. Add the DWARF information to the die. For
504 /// more information, read large comment just above here.
506 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
507 dwarf::Attribute Attribute,
508 const MachineLocation &Location) {
509 DIType Ty = DV.getType();
511 uint16_t Tag = Ty.getTag();
512 bool isPointer = false;
514 StringRef varName = DV.getName();
516 if (Tag == dwarf::DW_TAG_pointer_type) {
517 DIDerivedType DTy(Ty);
518 TmpTy = resolve(DTy.getTypeDerivedFrom());
522 DICompositeType blockStruct(TmpTy);
524 // Find the __forwarding field and the variable field in the __Block_byref
526 DIArray Fields = blockStruct.getElements();
527 DIDerivedType varField;
528 DIDerivedType forwardingField;
530 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
531 DIDerivedType DT(Fields.getElement(i));
532 StringRef fieldName = DT.getName();
533 if (fieldName == "__forwarding")
534 forwardingField = DT;
535 else if (fieldName == varName)
539 // Get the offsets for the forwarding field and the variable field.
540 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
541 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
543 // Decode the original location, and use that as the start of the byref
544 // variable's location.
545 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
548 if (Location.isReg())
549 validReg = addRegisterOpPiece(*Loc, Location.getReg());
551 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
556 // If we started with a pointer to the __Block_byref... struct, then
557 // the first thing we need to do is dereference the pointer (DW_OP_deref).
559 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
561 // Next add the offset for the '__forwarding' field:
562 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
563 // adding the offset if it's 0.
564 if (forwardingFieldOffset > 0) {
565 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
566 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
569 // Now dereference the __forwarding field to get to the real __Block_byref
570 // struct: DW_OP_deref.
571 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
573 // Now that we've got the real __Block_byref... struct, add the offset
574 // for the variable's field to get to the location of the actual variable:
575 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
576 if (varFieldOffset > 0) {
577 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
578 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
581 // Now attach the location information to the DIE.
582 addBlock(Die, Attribute, Loc);
585 /// Return true if type encoding is unsigned.
586 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
587 DIDerivedType DTy(Ty);
588 if (DTy.isDerivedType()) {
589 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
590 // Encode pointer constants as unsigned bytes. This is used at least for
591 // null pointer constant emission.
592 // (Pieces of) aggregate types that get hacked apart by SROA may also be
593 // represented by a constant. Encode them as unsigned bytes.
594 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
595 // here, but accept them for now due to a bug in SROA producing bogus
597 if (T == dwarf::DW_TAG_array_type ||
598 T == dwarf::DW_TAG_class_type ||
599 T == dwarf::DW_TAG_pointer_type ||
600 T == dwarf::DW_TAG_ptr_to_member_type ||
601 T == dwarf::DW_TAG_reference_type ||
602 T == dwarf::DW_TAG_rvalue_reference_type ||
603 T == dwarf::DW_TAG_structure_type)
605 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
606 T == dwarf::DW_TAG_volatile_type ||
607 T == dwarf::DW_TAG_restrict_type ||
608 T == dwarf::DW_TAG_enumeration_type);
609 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
610 return isUnsignedDIType(DD, DD->resolve(Deriv));
611 // FIXME: Enums without a fixed underlying type have unknown signedness
612 // here, leading to incorrectly emitted constants.
613 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
618 assert(BTy.isBasicType());
619 unsigned Encoding = BTy.getEncoding();
620 assert((Encoding == dwarf::DW_ATE_unsigned ||
621 Encoding == dwarf::DW_ATE_unsigned_char ||
622 Encoding == dwarf::DW_ATE_signed ||
623 Encoding == dwarf::DW_ATE_signed_char ||
624 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
625 (Ty.getTag() == dwarf::DW_TAG_unspecified_type &&
626 Ty.getName() == "decltype(nullptr)")) &&
627 "Unsupported encoding");
628 return (Encoding == dwarf::DW_ATE_unsigned ||
629 Encoding == dwarf::DW_ATE_unsigned_char ||
630 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
631 Ty.getTag() == dwarf::DW_TAG_unspecified_type);
634 /// If this type is derived from a base type then return base type size.
635 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
636 unsigned Tag = Ty.getTag();
638 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
639 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
640 Tag != dwarf::DW_TAG_restrict_type)
641 return Ty.getSizeInBits();
643 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
645 // If this type is not derived from any type or the type is a declaration then
646 // take conservative approach.
647 if (!BaseType.isValid() || BaseType.isForwardDecl())
648 return Ty.getSizeInBits();
650 // If this is a derived type, go ahead and get the base type, unless it's a
651 // reference then it's just the size of the field. Pointer types have no need
652 // of this since they're a different type of qualification on the type.
653 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
654 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
655 return Ty.getSizeInBits();
657 if (BaseType.isDerivedType())
658 return getBaseTypeSize(DD, DIDerivedType(BaseType));
660 return BaseType.getSizeInBits();
663 /// addConstantFPValue - Add constant value entry in variable DIE.
664 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
665 assert(MO.isFPImm() && "Invalid machine operand!");
666 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
667 APFloat FPImm = MO.getFPImm()->getValueAPF();
669 // Get the raw data form of the floating point.
670 const APInt FltVal = FPImm.bitcastToAPInt();
671 const char *FltPtr = (const char *)FltVal.getRawData();
673 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
674 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
675 int Incr = (LittleEndian ? 1 : -1);
676 int Start = (LittleEndian ? 0 : NumBytes - 1);
677 int Stop = (LittleEndian ? NumBytes : -1);
679 // Output the constant to DWARF one byte at a time.
680 for (; Start != Stop; Start += Incr)
681 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
683 addBlock(Die, dwarf::DW_AT_const_value, Block);
686 /// addConstantFPValue - Add constant value entry in variable DIE.
687 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
688 // Pass this down to addConstantValue as an unsigned bag of bits.
689 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
692 /// addConstantValue - Add constant value entry in variable DIE.
693 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
694 addConstantValue(Die, CI->getValue(), Ty);
697 /// addConstantValue - Add constant value entry in variable DIE.
698 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
700 assert(MO.isImm() && "Invalid machine operand!");
702 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
705 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
706 // FIXME: This is a bit conservative/simple - it emits negative values always
707 // sign extended to 64 bits rather than minimizing the number of bytes.
708 addUInt(Die, dwarf::DW_AT_const_value,
709 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
712 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
713 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
716 // addConstantValue - Add constant value entry in variable DIE.
717 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
718 unsigned CIBitWidth = Val.getBitWidth();
719 if (CIBitWidth <= 64) {
720 addConstantValue(Die, Unsigned,
721 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
725 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
727 // Get the raw data form of the large APInt.
728 const uint64_t *Ptr64 = Val.getRawData();
730 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
731 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
733 // Output the constant to DWARF one byte at a time.
734 for (int i = 0; i < NumBytes; i++) {
737 c = Ptr64[i / 8] >> (8 * (i & 7));
739 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
740 addUInt(*Block, dwarf::DW_FORM_data1, c);
743 addBlock(Die, dwarf::DW_AT_const_value, Block);
746 /// addTemplateParams - Add template parameters into buffer.
747 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
748 // Add template parameters.
749 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
750 DIDescriptor Element = TParams.getElement(i);
751 if (Element.isTemplateTypeParameter())
752 constructTemplateTypeParameterDIE(Buffer,
753 DITemplateTypeParameter(Element));
754 else if (Element.isTemplateValueParameter())
755 constructTemplateValueParameterDIE(Buffer,
756 DITemplateValueParameter(Element));
760 /// getOrCreateContextDIE - Get context owner's DIE.
761 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
762 if (!Context || Context.isFile())
763 return &getUnitDie();
764 if (Context.isType())
765 return getOrCreateTypeDIE(DIType(Context));
766 if (Context.isNameSpace())
767 return getOrCreateNameSpace(DINameSpace(Context));
768 if (Context.isSubprogram())
769 return getOrCreateSubprogramDIE(DISubprogram(Context));
770 return getDIE(Context);
773 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
774 DIScope Context = resolve(Ty.getContext());
775 DIE *ContextDIE = getOrCreateContextDIE(Context);
777 if (DIE *TyDIE = getDIE(Ty))
781 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
783 constructTypeDIE(TyDIE, Ty);
785 updateAcceleratorTables(Context, Ty, TyDIE);
789 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
791 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
797 assert(Ty == resolve(Ty.getRef()) &&
798 "type was not uniqued, possible ODR violation.");
800 // DW_TAG_restrict_type is not supported in DWARF2
801 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
802 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
804 // Construct the context before querying for the existence of the DIE in case
805 // such construction creates the DIE.
806 DIScope Context = resolve(Ty.getContext());
807 DIE *ContextDIE = getOrCreateContextDIE(Context);
810 if (DIE *TyDIE = getDIE(Ty))
814 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
816 updateAcceleratorTables(Context, Ty, TyDIE);
818 if (Ty.isBasicType())
819 constructTypeDIE(TyDIE, DIBasicType(Ty));
820 else if (Ty.isCompositeType()) {
821 DICompositeType CTy(Ty);
822 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
823 if (MDString *TypeId = CTy.getIdentifier()) {
824 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
825 // Skip updating the accelerator tables since this is not the full type.
828 constructTypeDIE(TyDIE, CTy);
830 assert(Ty.isDerivedType() && "Unknown kind of DIType");
831 constructTypeDIE(TyDIE, DIDerivedType(Ty));
837 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
839 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
840 bool IsImplementation = 0;
841 if (Ty.isCompositeType()) {
842 DICompositeType CT(Ty);
843 // A runtime language of 0 actually means C/C++ and that any
844 // non-negative value is some version of Objective-C/C++.
845 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
847 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
848 DD->addAccelType(Ty.getName(), TyDIE, Flags);
850 if (!Context || Context.isCompileUnit() || Context.isFile() ||
851 Context.isNameSpace())
852 addGlobalType(Ty, TyDIE, Context);
856 /// addType - Add a new type attribute to the specified entity.
857 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
858 assert(Ty && "Trying to add a type that doesn't exist?");
860 // Check for pre-existence.
861 DIEEntry *Entry = getDIEEntry(Ty);
862 // If it exists then use the existing value.
864 addDIEEntry(Entity, Attribute, Entry);
869 DIE *Buffer = getOrCreateTypeDIE(Ty);
872 Entry = createDIEEntry(*Buffer);
873 insertDIEEntry(Ty, Entry);
874 addDIEEntry(Entity, Attribute, Entry);
877 /// getParentContextString - Walks the metadata parent chain in a language
878 /// specific manner (using the compile unit language) and returns
879 /// it as a string. This is done at the metadata level because DIEs may
880 /// not currently have been added to the parent context and walking the
881 /// DIEs looking for names is more expensive than walking the metadata.
882 std::string DwarfUnit::getParentContextString(DIScope Context) const {
886 // FIXME: Decide whether to implement this for non-C++ languages.
887 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
891 SmallVector<DIScope, 1> Parents;
892 while (!Context.isCompileUnit()) {
893 Parents.push_back(Context);
894 if (Context.getContext())
895 Context = resolve(Context.getContext());
897 // Structure, etc types will have a NULL context if they're at the top
902 // Reverse iterate over our list to go from the outermost construct to the
904 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
908 StringRef Name = Ctx.getName();
909 if (Name.empty() && Ctx.isNameSpace())
910 Name = "(anonymous namespace)";
919 /// constructTypeDIE - Construct basic type die from DIBasicType.
920 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
921 // Get core information.
922 StringRef Name = BTy.getName();
923 // Add name if not anonymous or intermediate type.
925 addString(Buffer, dwarf::DW_AT_name, Name);
927 // An unspecified type only has a name attribute.
928 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
931 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
934 uint64_t Size = BTy.getSizeInBits() >> 3;
935 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
938 /// constructTypeDIE - Construct derived type die from DIDerivedType.
939 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
940 // Get core information.
941 StringRef Name = DTy.getName();
942 uint64_t Size = DTy.getSizeInBits() >> 3;
943 uint16_t Tag = Buffer.getTag();
945 // Map to main type, void will not have a type.
946 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
948 addType(Buffer, FromTy);
950 // Add name if not anonymous or intermediate type.
952 addString(Buffer, dwarf::DW_AT_name, Name);
954 // Add size if non-zero (derived types might be zero-sized.)
955 if (Size && Tag != dwarf::DW_TAG_pointer_type
956 && Tag != dwarf::DW_TAG_ptr_to_member_type)
957 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
959 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
960 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
961 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
962 // Add source line info if available and TyDesc is not a forward declaration.
963 if (!DTy.isForwardDecl())
964 addSourceLine(Buffer, DTy);
967 /// constructSubprogramArguments - Construct function argument DIEs.
968 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
969 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
970 DIType Ty = resolve(Args.getElement(i));
972 assert(i == N-1 && "Unspecified parameter must be the last argument");
973 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
975 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
977 if (Ty.isArtificial())
978 addFlag(Arg, dwarf::DW_AT_artificial);
983 /// constructTypeDIE - Construct type DIE from DICompositeType.
984 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
985 // Add name if not anonymous or intermediate type.
986 StringRef Name = CTy.getName();
988 uint64_t Size = CTy.getSizeInBits() >> 3;
989 uint16_t Tag = Buffer.getTag();
992 case dwarf::DW_TAG_array_type:
993 constructArrayTypeDIE(Buffer, CTy);
995 case dwarf::DW_TAG_enumeration_type:
996 constructEnumTypeDIE(Buffer, CTy);
998 case dwarf::DW_TAG_subroutine_type: {
999 // Add return type. A void return won't have a type.
1000 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1001 DIType RTy(resolve(Elements.getElement(0)));
1003 addType(Buffer, RTy);
1005 bool isPrototyped = true;
1006 if (Elements.getNumElements() == 2 &&
1007 !Elements.getElement(1))
1008 isPrototyped = false;
1010 constructSubprogramArguments(Buffer, Elements);
1012 // Add prototype flag if we're dealing with a C language and the
1013 // function has been prototyped.
1014 uint16_t Language = getLanguage();
1016 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1017 Language == dwarf::DW_LANG_ObjC))
1018 addFlag(Buffer, dwarf::DW_AT_prototyped);
1020 if (CTy.isLValueReference())
1021 addFlag(Buffer, dwarf::DW_AT_reference);
1023 if (CTy.isRValueReference())
1024 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1026 case dwarf::DW_TAG_structure_type:
1027 case dwarf::DW_TAG_union_type:
1028 case dwarf::DW_TAG_class_type: {
1029 // Add elements to structure type.
1030 DIArray Elements = CTy.getElements();
1031 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1032 DIDescriptor Element = Elements.getElement(i);
1033 if (Element.isSubprogram())
1034 getOrCreateSubprogramDIE(DISubprogram(Element));
1035 else if (Element.isDerivedType()) {
1036 DIDerivedType DDTy(Element);
1037 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1038 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1039 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1040 dwarf::DW_AT_friend);
1041 } else if (DDTy.isStaticMember()) {
1042 getOrCreateStaticMemberDIE(DDTy);
1044 constructMemberDIE(Buffer, DDTy);
1046 } else if (Element.isObjCProperty()) {
1047 DIObjCProperty Property(Element);
1048 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1049 StringRef PropertyName = Property.getObjCPropertyName();
1050 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1051 if (Property.getType())
1052 addType(ElemDie, Property.getType());
1053 addSourceLine(ElemDie, Property);
1054 StringRef GetterName = Property.getObjCPropertyGetterName();
1055 if (!GetterName.empty())
1056 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1057 StringRef SetterName = Property.getObjCPropertySetterName();
1058 if (!SetterName.empty())
1059 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1060 unsigned PropertyAttributes = 0;
1061 if (Property.isReadOnlyObjCProperty())
1062 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1063 if (Property.isReadWriteObjCProperty())
1064 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1065 if (Property.isAssignObjCProperty())
1066 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1067 if (Property.isRetainObjCProperty())
1068 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1069 if (Property.isCopyObjCProperty())
1070 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1071 if (Property.isNonAtomicObjCProperty())
1072 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1073 if (PropertyAttributes)
1074 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1075 PropertyAttributes);
1077 DIEEntry *Entry = getDIEEntry(Element);
1079 Entry = createDIEEntry(ElemDie);
1080 insertDIEEntry(Element, Entry);
1086 if (CTy.isAppleBlockExtension())
1087 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1089 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
1090 // inside C++ composite types to point to the base class with the vtable.
1091 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1093 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1094 *getOrCreateTypeDIE(ContainingType));
1096 if (CTy.isObjcClassComplete())
1097 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1099 // Add template parameters to a class, structure or union types.
1100 // FIXME: The support isn't in the metadata for this yet.
1101 if (Tag == dwarf::DW_TAG_class_type ||
1102 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1103 addTemplateParams(Buffer, CTy.getTemplateParams());
1111 // Add name if not anonymous or intermediate type.
1113 addString(Buffer, dwarf::DW_AT_name, Name);
1115 if (Tag == dwarf::DW_TAG_enumeration_type ||
1116 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1117 Tag == dwarf::DW_TAG_union_type) {
1118 // Add size if non-zero (derived types might be zero-sized.)
1119 // TODO: Do we care about size for enum forward declarations?
1121 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1122 else if (!CTy.isForwardDecl())
1123 // Add zero size if it is not a forward declaration.
1124 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1126 // If we're a forward decl, say so.
1127 if (CTy.isForwardDecl())
1128 addFlag(Buffer, dwarf::DW_AT_declaration);
1130 // Add source line info if available.
1131 if (!CTy.isForwardDecl())
1132 addSourceLine(Buffer, CTy);
1134 // No harm in adding the runtime language to the declaration.
1135 unsigned RLang = CTy.getRunTimeLang();
1137 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1142 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1143 /// DITemplateTypeParameter.
1144 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1145 DITemplateTypeParameter TP) {
1147 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1148 // Add the type if it exists, it could be void and therefore no type.
1150 addType(ParamDIE, resolve(TP.getType()));
1151 if (!TP.getName().empty())
1152 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1155 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1156 /// DITemplateValueParameter.
1158 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1159 DITemplateValueParameter VP) {
1160 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1162 // Add the type if there is one, template template and template parameter
1163 // packs will not have a type.
1164 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1165 addType(ParamDIE, resolve(VP.getType()));
1166 if (!VP.getName().empty())
1167 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1168 if (Metadata *Val = VP.getValue()) {
1169 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1170 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1171 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1172 // For declaration non-type template parameters (such as global values and
1174 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1175 addOpAddress(*Loc, Asm->getSymbol(GV));
1176 // Emit DW_OP_stack_value to use the address as the immediate value of the
1177 // parameter, rather than a pointer to it.
1178 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1179 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1180 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1181 assert(isa<MDString>(Val));
1182 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1183 cast<MDString>(Val)->getString());
1184 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1185 assert(isa<MDNode>(Val));
1186 DIArray A(cast<MDNode>(Val));
1187 addTemplateParams(ParamDIE, A);
1192 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1193 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1194 // Construct the context before querying for the existence of the DIE in case
1195 // such construction creates the DIE.
1196 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1198 if (DIE *NDie = getDIE(NS))
1200 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1202 StringRef Name = NS.getName();
1204 addString(NDie, dwarf::DW_AT_name, NS.getName());
1206 Name = "(anonymous namespace)";
1207 DD->addAccelNamespace(Name, NDie);
1208 addGlobalName(Name, NDie, NS.getContext());
1209 addSourceLine(NDie, NS);
1213 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1214 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP, bool Minimal) {
1215 // Construct the context before querying for the existence of the DIE in case
1216 // such construction creates the DIE (as is the case for member function
1219 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP.getContext()));
1221 if (DIE *SPDie = getDIE(SP))
1224 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1226 // Add subprogram definitions to the CU die directly.
1227 ContextDIE = &getUnitDie();
1228 // Build the decl now to ensure it precedes the definition.
1229 getOrCreateSubprogramDIE(SPDecl);
1233 // DW_TAG_inlined_subroutine may refer to this DIE.
1234 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1236 // Stop here and fill this in later, depending on whether or not this
1237 // subprogram turns out to have inlined instances or not.
1238 if (SP.isDefinition())
1241 applySubprogramAttributes(SP, SPDie);
1245 bool DwarfUnit::applySubprogramDefinitionAttributes(DISubprogram SP,
1247 DIE *DeclDie = nullptr;
1248 StringRef DeclLinkageName;
1249 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1250 DeclDie = getDIE(SPDecl);
1251 assert(DeclDie && "This DIE should've already been constructed when the "
1252 "definition DIE was created in "
1253 "getOrCreateSubprogramDIE");
1254 DeclLinkageName = SPDecl.getLinkageName();
1257 // Add function template parameters.
1258 addTemplateParams(SPDie, SP.getTemplateParams());
1260 // Add the linkage name if we have one and it isn't in the Decl.
1261 StringRef LinkageName = SP.getLinkageName();
1262 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1263 LinkageName == DeclLinkageName) &&
1264 "decl has a linkage name and it is different");
1265 if (!LinkageName.empty() && DeclLinkageName.empty())
1266 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1267 GlobalValue::getRealLinkageName(LinkageName));
1272 // Refer to the function declaration where all the other attributes will be
1274 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1278 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie,
1281 if (applySubprogramDefinitionAttributes(SP, SPDie))
1284 // Constructors and operators for anonymous aggregates do not have names.
1285 if (!SP.getName().empty())
1286 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1288 // Skip the rest of the attributes under -gmlt to save space.
1292 addSourceLine(SPDie, SP);
1294 // Add the prototype if we have a prototype and we have a C like
1296 uint16_t Language = getLanguage();
1297 if (SP.isPrototyped() &&
1298 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1299 Language == dwarf::DW_LANG_ObjC))
1300 addFlag(SPDie, dwarf::DW_AT_prototyped);
1302 DISubroutineType SPTy = SP.getType();
1303 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1304 "the type of a subprogram should be a subroutine");
1306 DITypeArray Args = SPTy.getTypeArray();
1307 // Add a return type. If this is a type like a C/C++ void type we don't add a
1309 if (resolve(Args.getElement(0)))
1310 addType(SPDie, DIType(resolve(Args.getElement(0))));
1312 unsigned VK = SP.getVirtuality();
1314 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1315 DIELoc *Block = getDIELoc();
1316 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1317 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1318 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1319 ContainingTypeMap.insert(
1320 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1323 if (!SP.isDefinition()) {
1324 addFlag(SPDie, dwarf::DW_AT_declaration);
1326 // Add arguments. Do not add arguments for subprogram definition. They will
1327 // be handled while processing variables.
1328 constructSubprogramArguments(SPDie, Args);
1331 if (SP.isArtificial())
1332 addFlag(SPDie, dwarf::DW_AT_artificial);
1334 if (!SP.isLocalToUnit())
1335 addFlag(SPDie, dwarf::DW_AT_external);
1337 if (SP.isOptimized())
1338 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1340 if (unsigned isa = Asm->getISAEncoding()) {
1341 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1344 if (SP.isLValueReference())
1345 addFlag(SPDie, dwarf::DW_AT_reference);
1347 if (SP.isRValueReference())
1348 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1350 if (SP.isProtected())
1351 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1352 dwarf::DW_ACCESS_protected);
1353 else if (SP.isPrivate())
1354 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1355 dwarf::DW_ACCESS_private);
1356 else if (SP.isPublic())
1357 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1358 dwarf::DW_ACCESS_public);
1360 if (SP.isExplicit())
1361 addFlag(SPDie, dwarf::DW_AT_explicit);
1364 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1365 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1366 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1367 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1369 // The LowerBound value defines the lower bounds which is typically zero for
1370 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1371 // Count == -1 then the array is unbounded and we do not emit
1372 // DW_AT_lower_bound and DW_AT_count attributes.
1373 int64_t LowerBound = SR.getLo();
1374 int64_t DefaultLowerBound = getDefaultLowerBound();
1375 int64_t Count = SR.getCount();
1377 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1378 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1381 // FIXME: An unbounded array should reference the expression that defines
1383 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1386 DIE *DwarfUnit::getIndexTyDie() {
1389 // Construct an integer type to use for indexes.
1390 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1391 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1392 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1393 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1394 dwarf::DW_ATE_unsigned);
1398 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1399 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1401 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1403 // Emit the element type.
1404 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1406 // Get an anonymous type for index type.
1407 // FIXME: This type should be passed down from the front end
1408 // as different languages may have different sizes for indexes.
1409 DIE *IdxTy = getIndexTyDie();
1411 // Add subranges to array type.
1412 DIArray Elements = CTy.getElements();
1413 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1414 DIDescriptor Element = Elements.getElement(i);
1415 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1416 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1420 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1421 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1422 DIArray Elements = CTy.getElements();
1424 // Add enumerators to enumeration type.
1425 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1426 DIEnumerator Enum(Elements.getElement(i));
1427 if (Enum.isEnumerator()) {
1428 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1429 StringRef Name = Enum.getName();
1430 addString(Enumerator, dwarf::DW_AT_name, Name);
1431 int64_t Value = Enum.getEnumValue();
1432 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1436 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1438 addType(Buffer, DTy);
1439 addFlag(Buffer, dwarf::DW_AT_enum_class);
1443 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1445 void DwarfUnit::constructContainingTypeDIEs() {
1446 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1447 CE = ContainingTypeMap.end();
1449 DIE &SPDie = *CI->first;
1450 DIDescriptor D(CI->second);
1453 DIE *NDie = getDIE(D);
1456 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1460 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1461 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1462 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1463 StringRef Name = DT.getName();
1465 addString(MemberDie, dwarf::DW_AT_name, Name);
1467 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1469 addSourceLine(MemberDie, DT);
1471 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1473 // For C++, virtual base classes are not at fixed offset. Use following
1474 // expression to extract appropriate offset from vtable.
1475 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1477 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1478 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1479 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1480 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1481 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1482 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1483 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1484 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1486 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1488 uint64_t Size = DT.getSizeInBits();
1489 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1490 uint64_t OffsetInBytes;
1492 if (Size != FieldSize) {
1493 // Handle bitfield, assume bytes are 8 bits.
1494 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1495 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1497 uint64_t Offset = DT.getOffsetInBits();
1498 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1499 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1500 uint64_t FieldOffset = (HiMark - FieldSize);
1501 Offset -= FieldOffset;
1503 // Maybe we need to work from the other end.
1504 if (Asm->getDataLayout().isLittleEndian())
1505 Offset = FieldSize - (Offset + Size);
1506 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1508 // Here DW_AT_data_member_location points to the anonymous
1509 // field that includes this bit field.
1510 OffsetInBytes = FieldOffset >> 3;
1512 // This is not a bitfield.
1513 OffsetInBytes = DT.getOffsetInBits() >> 3;
1515 if (DD->getDwarfVersion() <= 2) {
1516 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1517 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1518 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1519 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1521 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1525 if (DT.isProtected())
1526 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1527 dwarf::DW_ACCESS_protected);
1528 else if (DT.isPrivate())
1529 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1530 dwarf::DW_ACCESS_private);
1531 // Otherwise C++ member and base classes are considered public.
1532 else if (DT.isPublic())
1533 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1534 dwarf::DW_ACCESS_public);
1536 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1537 dwarf::DW_VIRTUALITY_virtual);
1539 // Objective-C properties.
1540 if (MDNode *PNode = DT.getObjCProperty())
1541 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1542 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1545 if (DT.isArtificial())
1546 addFlag(MemberDie, dwarf::DW_AT_artificial);
1549 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1550 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1554 // Construct the context before querying for the existence of the DIE in case
1555 // such construction creates the DIE.
1556 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1557 assert(dwarf::isType(ContextDIE->getTag()) &&
1558 "Static member should belong to a type.");
1560 if (DIE *StaticMemberDIE = getDIE(DT))
1561 return StaticMemberDIE;
1563 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1565 DIType Ty = resolve(DT.getTypeDerivedFrom());
1567 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1568 addType(StaticMemberDIE, Ty);
1569 addSourceLine(StaticMemberDIE, DT);
1570 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1571 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1573 // FIXME: We could omit private if the parent is a class_type, and
1574 // public if the parent is something else.
1575 if (DT.isProtected())
1576 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1577 dwarf::DW_ACCESS_protected);
1578 else if (DT.isPrivate())
1579 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1580 dwarf::DW_ACCESS_private);
1581 else if (DT.isPublic())
1582 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1583 dwarf::DW_ACCESS_public);
1585 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1586 addConstantValue(StaticMemberDIE, CI, Ty);
1587 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1588 addConstantFPValue(StaticMemberDIE, CFP);
1590 return &StaticMemberDIE;
1593 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
1594 // Emit size of content not including length itself
1595 Asm->OutStreamer.AddComment("Length of Unit");
1596 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1598 Asm->OutStreamer.AddComment("DWARF version number");
1599 Asm->EmitInt16(DD->getDwarfVersion());
1600 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1601 // We share one abbreviations table across all units so it's always at the
1602 // start of the section. Use a relocatable offset where needed to ensure
1603 // linking doesn't invalidate that offset.
1605 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1607 // Use a constant value when no symbol is provided.
1609 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1610 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1613 void DwarfUnit::initSection(const MCSection *Section) {
1614 assert(!this->Section);
1615 this->Section = Section;
1618 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
1619 DwarfUnit::emitHeader(ASectionSym);
1620 Asm->OutStreamer.AddComment("Type Signature");
1621 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1622 Asm->OutStreamer.AddComment("Type DIE Offset");
1623 // In a skeleton type unit there is no type DIE so emit a zero offset.
1624 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1625 sizeof(Ty->getOffset()));
1628 bool DwarfTypeUnit::isDwoUnit() const {
1629 // Since there are no skeleton type units, all type units are dwo type units
1630 // when split DWARF is being used.
1631 return DD->useSplitDwarf();