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 "DwarfAccelTable.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DIBuilder.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
39 #define DEBUG_TYPE "dwarfdebug"
42 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
43 cl::desc("Generate DWARF4 type units."),
46 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
47 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
49 void DIEDwarfExpression::EmitSigned(int Value) {
50 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
52 void DIEDwarfExpression::EmitUnsigned(unsigned Value) {
53 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
55 bool DIEDwarfExpression::isFrameRegister(unsigned MachineReg) {
56 return MachineReg == getTRI()->getFrameRegister(*AP.MF);
60 /// Unit - Unit constructor.
61 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
62 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
63 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
64 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
65 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
66 UnitTag == dwarf::DW_TAG_type_unit);
67 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
70 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
71 DwarfDebug *DW, DwarfFile *DWU,
72 MCDwarfDwoLineTable *SplitLineTable)
73 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
74 CU(CU), SplitLineTable(SplitLineTable) {
76 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
79 /// ~Unit - Destructor for compile unit.
80 DwarfUnit::~DwarfUnit() {
81 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
82 DIEBlocks[j]->~DIEBlock();
83 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
84 DIELocs[j]->~DIELoc();
87 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
88 /// information entry.
89 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
90 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
94 /// getDefaultLowerBound - Return the default lower bound for an array. If the
95 /// DWARF version doesn't handle the language, return -1.
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(DIDescriptor 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 (D.isType() ||
172 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
173 !GenerateDwarfTypeUnits;
176 /// getDIE - Returns the debug information entry map slot for the
177 /// specified debug variable. We delegate the request to DwarfDebug
178 /// when the DIE for this MDNode can be shared across CUs. The mappings
179 /// will be kept in DwarfDebug for shareable DIEs.
180 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
181 if (isShareableAcrossCUs(D))
182 return DU->getDIE(D);
183 return MDNodeToDieMap.lookup(D);
186 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
187 /// when the DIE for this MDNode can be shared across CUs. The mappings
188 /// will be kept in DwarfDebug for shareable DIEs.
189 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
190 if (isShareableAcrossCUs(Desc)) {
191 DU->insertDIE(Desc, D);
194 MDNodeToDieMap.insert(std::make_pair(Desc, D));
197 /// addFlag - Add a flag that is true.
198 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
199 if (DD->getDwarfVersion() >= 4)
200 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
202 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
205 /// addUInt - Add an unsigned integer attribute data and value.
207 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
208 Optional<dwarf::Form> Form, uint64_t Integer) {
210 Form = DIEInteger::BestForm(false, Integer);
211 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
213 Die.addValue(Attribute, *Form, Value);
216 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
217 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
220 /// addSInt - Add an signed integer attribute data and value.
222 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
223 Optional<dwarf::Form> Form, int64_t Integer) {
225 Form = DIEInteger::BestForm(true, Integer);
226 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
227 Die.addValue(Attribute, *Form, Value);
230 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
232 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
235 /// addString - Add a string attribute data and value. We always emit a
236 /// reference to the string pool instead of immediate strings so that DIEs have
237 /// more predictable sizes. In the case of split dwarf we emit an index
238 /// into another table which gets us the static offset into the string
240 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
243 return addLocalString(Die, Attribute, String);
245 addIndexedString(Die, Attribute, String);
248 void DwarfUnit::addIndexedString(DIE &Die, dwarf::Attribute Attribute,
250 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
251 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
252 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
253 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
256 /// addLocalString - Add a string attribute data and value. This is guaranteed
257 /// to be in the local string pool instead of indirected.
258 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
260 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
262 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
263 Value = new (DIEValueAllocator) DIELabel(Symb);
265 Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
266 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
267 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
270 /// addLabel - Add a Dwarf label attribute data and value.
272 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
273 const MCSymbol *Label) {
274 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
275 Die.addValue(Attribute, Form, Value);
278 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
279 addLabel(Die, (dwarf::Attribute)0, Form, Label);
282 /// addSectionOffset - Add an offset into a section attribute data and value.
284 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
286 if (DD->getDwarfVersion() >= 4)
287 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
289 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
292 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
293 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
294 : getCU().getOrCreateSourceID(FileName, DirName);
297 /// addOpAddress - Add a dwarf op address data and value using the
298 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
300 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
301 if (!DD->useSplitDwarf()) {
302 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
303 addLabel(Die, dwarf::DW_FORM_udata, Sym);
305 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
306 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
307 DD->getAddressPool().getIndex(Sym));
311 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
312 const MCSymbol *Hi, const MCSymbol *Lo) {
313 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
314 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
317 /// addDIEEntry - Add a DIE attribute data and value.
319 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
320 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
323 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
324 // Flag the type unit reference as a declaration so that if it contains
325 // members (implicit special members, static data member definitions, member
326 // declarations for definitions in this CU, etc) consumers don't get confused
327 // and think this is a full definition.
328 addFlag(Die, dwarf::DW_AT_declaration);
330 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
331 new (DIEValueAllocator) DIETypeSignature(Type));
334 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
336 const DIE *DieCU = Die.getUnitOrNull();
337 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
339 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
340 DieCU = &getUnitDie();
342 EntryCU = &getUnitDie();
343 Die.addValue(Attribute,
344 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
348 /// Create a DIE with the given Tag, add the DIE to its parent, and
349 /// call insertDIE if MD is not null.
350 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
351 assert(Tag != dwarf::DW_TAG_auto_variable &&
352 Tag != dwarf::DW_TAG_arg_variable);
353 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
354 DIE &Die = *Parent.getChildren().back();
360 /// addBlock - Add block data.
362 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
363 Loc->ComputeSize(Asm);
364 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
365 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
368 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
370 Block->ComputeSize(Asm);
371 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
372 Die.addValue(Attribute, Block->BestForm(), Block);
375 /// addSourceLine - Add location information to specified debug information
377 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
378 StringRef Directory) {
382 unsigned FileID = getOrCreateSourceID(File, Directory);
383 assert(FileID && "Invalid file id");
384 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
385 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
388 /// addSourceLine - Add location information to specified debug information
390 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
391 assert(V.isVariable());
393 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
394 V.getContext().getDirectory());
397 /// addSourceLine - Add location information to specified debug information
399 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
400 assert(G.isGlobalVariable());
402 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
405 /// addSourceLine - Add location information to specified debug information
407 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
408 assert(SP.isSubprogram());
410 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
413 /// addSourceLine - Add location information to specified debug information
415 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
418 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
421 /// addSourceLine - Add location information to specified debug information
423 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
424 assert(Ty.isObjCProperty());
426 DIFile File = Ty.getFile();
427 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
428 File.getDirectory());
431 /// addSourceLine - Add location information to specified debug information
433 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
436 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
439 /// addRegisterOp - Add register operand.
440 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
441 unsigned SizeInBits, unsigned OffsetInBits) {
442 DIEDwarfExpression Expr(*Asm, *this, TheDie);
443 Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
447 /// addRegisterOffset - Add register offset.
448 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
450 DIEDwarfExpression Expr(*Asm, *this, TheDie);
451 return Expr.AddMachineRegIndirect(Reg, Offset);
454 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
455 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
456 gives the variable VarName either the struct, or a pointer to the struct, as
457 its type. This is necessary for various behind-the-scenes things the
458 compiler needs to do with by-reference variables in Blocks.
460 However, as far as the original *programmer* is concerned, the variable
461 should still have type 'SomeType', as originally declared.
463 The function getBlockByrefType dives into the __Block_byref_x_VarName
464 struct to find the original type of the variable, which is then assigned to
465 the variable's Debug Information Entry as its real type. So far, so good.
466 However now the debugger will expect the variable VarName to have the type
467 SomeType. So we need the location attribute for the variable to be an
468 expression that explains to the debugger how to navigate through the
469 pointers and struct to find the actual variable of type SomeType.
471 The following function does just that. We start by getting
472 the "normal" location for the variable. This will be the location
473 of either the struct __Block_byref_x_VarName or the pointer to the
474 struct __Block_byref_x_VarName.
476 The struct will look something like:
478 struct __Block_byref_x_VarName {
480 struct __Block_byref_x_VarName *forwarding;
481 ... <various other fields>
483 ... <maybe more fields>
486 If we are given the struct directly (as our starting point) we
487 need to tell the debugger to:
489 1). Add the offset of the forwarding field.
491 2). Follow that pointer to get the real __Block_byref_x_VarName
492 struct to use (the real one may have been copied onto the heap).
494 3). Add the offset for the field VarName, to find the actual variable.
496 If we started with a pointer to the struct, then we need to
497 dereference that pointer first, before the other steps.
498 Translating this into DWARF ops, we will need to append the following
499 to the current location description for the variable:
501 DW_OP_deref -- optional, if we start with a pointer
502 DW_OP_plus_uconst <forward_fld_offset>
504 DW_OP_plus_uconst <varName_fld_offset>
506 That is what this function does. */
508 /// addBlockByrefAddress - Start with the address based on the location
509 /// provided, and generate the DWARF information necessary to find the
510 /// actual Block variable (navigating the Block struct) based on the
511 /// starting location. Add the DWARF information to the die. For
512 /// more information, read large comment just above here.
514 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
515 dwarf::Attribute Attribute,
516 const MachineLocation &Location) {
517 DIType Ty = DV.getType();
519 uint16_t Tag = Ty.getTag();
520 bool isPointer = false;
522 StringRef varName = DV.getName();
524 if (Tag == dwarf::DW_TAG_pointer_type) {
525 DIDerivedType DTy(Ty);
526 TmpTy = resolve(DTy.getTypeDerivedFrom());
530 DICompositeType blockStruct(TmpTy);
532 // Find the __forwarding field and the variable field in the __Block_byref
534 DIArray Fields = blockStruct.getElements();
535 DIDerivedType varField;
536 DIDerivedType forwardingField;
538 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
539 DIDerivedType DT(Fields.getElement(i));
540 StringRef fieldName = DT.getName();
541 if (fieldName == "__forwarding")
542 forwardingField = DT;
543 else if (fieldName == varName)
547 // Get the offsets for the forwarding field and the variable field.
548 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
549 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
551 // Decode the original location, and use that as the start of the byref
552 // variable's location.
553 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
556 if (Location.isReg())
557 validReg = addRegisterOpPiece(*Loc, Location.getReg());
559 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
564 // If we started with a pointer to the __Block_byref... struct, then
565 // the first thing we need to do is dereference the pointer (DW_OP_deref).
567 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
569 // Next add the offset for the '__forwarding' field:
570 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
571 // adding the offset if it's 0.
572 if (forwardingFieldOffset > 0) {
573 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
574 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
577 // Now dereference the __forwarding field to get to the real __Block_byref
578 // struct: DW_OP_deref.
579 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
581 // Now that we've got the real __Block_byref... struct, add the offset
582 // for the variable's field to get to the location of the actual variable:
583 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
584 if (varFieldOffset > 0) {
585 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
586 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
589 // Now attach the location information to the DIE.
590 addBlock(Die, Attribute, Loc);
593 /// Return true if type encoding is unsigned.
594 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
595 DIDerivedType DTy(Ty);
596 if (DTy.isDerivedType()) {
597 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
598 // Encode pointer constants as unsigned bytes. This is used at least for
599 // null pointer constant emission.
600 // (Pieces of) aggregate types that get hacked apart by SROA may also be
601 // represented by a constant. Encode them as unsigned bytes.
602 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
603 // here, but accept them for now due to a bug in SROA producing bogus
605 if (T == dwarf::DW_TAG_array_type ||
606 T == dwarf::DW_TAG_class_type ||
607 T == dwarf::DW_TAG_pointer_type ||
608 T == dwarf::DW_TAG_ptr_to_member_type ||
609 T == dwarf::DW_TAG_reference_type ||
610 T == dwarf::DW_TAG_rvalue_reference_type ||
611 T == dwarf::DW_TAG_structure_type ||
612 T == dwarf::DW_TAG_union_type)
614 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
615 T == dwarf::DW_TAG_volatile_type ||
616 T == dwarf::DW_TAG_restrict_type ||
617 T == dwarf::DW_TAG_enumeration_type);
618 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
619 return isUnsignedDIType(DD, DD->resolve(Deriv));
620 // FIXME: Enums without a fixed underlying type have unknown signedness
621 // here, leading to incorrectly emitted constants.
622 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
627 assert(BTy.isBasicType());
628 unsigned Encoding = BTy.getEncoding();
629 assert((Encoding == dwarf::DW_ATE_unsigned ||
630 Encoding == dwarf::DW_ATE_unsigned_char ||
631 Encoding == dwarf::DW_ATE_signed ||
632 Encoding == dwarf::DW_ATE_signed_char ||
633 Encoding == dwarf::DW_ATE_float ||
634 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
635 (Ty.getTag() == dwarf::DW_TAG_unspecified_type &&
636 Ty.getName() == "decltype(nullptr)")) &&
637 "Unsupported encoding");
638 return (Encoding == dwarf::DW_ATE_unsigned ||
639 Encoding == dwarf::DW_ATE_unsigned_char ||
640 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
641 Ty.getTag() == dwarf::DW_TAG_unspecified_type);
644 /// If this type is derived from a base type then return base type size.
645 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
646 unsigned Tag = Ty.getTag();
648 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
649 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
650 Tag != dwarf::DW_TAG_restrict_type)
651 return Ty.getSizeInBits();
653 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
655 assert(BaseType.isValid() && "Unexpected invalid base type");
657 // If this is a derived type, go ahead and get the base type, unless it's a
658 // reference then it's just the size of the field. Pointer types have no need
659 // of this since they're a different type of qualification on the type.
660 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
661 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
662 return Ty.getSizeInBits();
664 if (BaseType.isDerivedType())
665 return getBaseTypeSize(DD, DIDerivedType(BaseType));
667 return BaseType.getSizeInBits();
670 /// addConstantFPValue - Add constant value entry in variable DIE.
671 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
672 assert(MO.isFPImm() && "Invalid machine operand!");
673 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
674 APFloat FPImm = MO.getFPImm()->getValueAPF();
676 // Get the raw data form of the floating point.
677 const APInt FltVal = FPImm.bitcastToAPInt();
678 const char *FltPtr = (const char *)FltVal.getRawData();
680 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
681 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
682 int Incr = (LittleEndian ? 1 : -1);
683 int Start = (LittleEndian ? 0 : NumBytes - 1);
684 int Stop = (LittleEndian ? NumBytes : -1);
686 // Output the constant to DWARF one byte at a time.
687 for (; Start != Stop; Start += Incr)
688 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
690 addBlock(Die, dwarf::DW_AT_const_value, Block);
693 /// addConstantFPValue - Add constant value entry in variable DIE.
694 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
695 // Pass this down to addConstantValue as an unsigned bag of bits.
696 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
699 /// addConstantValue - Add constant value entry in variable DIE.
700 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
701 addConstantValue(Die, CI->getValue(), Ty);
704 /// addConstantValue - Add constant value entry in variable DIE.
705 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
707 assert(MO.isImm() && "Invalid machine operand!");
709 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
712 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
713 // FIXME: This is a bit conservative/simple - it emits negative values always
714 // sign extended to 64 bits rather than minimizing the number of bytes.
715 addUInt(Die, dwarf::DW_AT_const_value,
716 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
719 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
720 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
723 // addConstantValue - Add constant value entry in variable DIE.
724 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
725 unsigned CIBitWidth = Val.getBitWidth();
726 if (CIBitWidth <= 64) {
727 addConstantValue(Die, Unsigned,
728 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
732 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
734 // Get the raw data form of the large APInt.
735 const uint64_t *Ptr64 = Val.getRawData();
737 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
738 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
740 // Output the constant to DWARF one byte at a time.
741 for (int i = 0; i < NumBytes; i++) {
744 c = Ptr64[i / 8] >> (8 * (i & 7));
746 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
747 addUInt(*Block, dwarf::DW_FORM_data1, c);
750 addBlock(Die, dwarf::DW_AT_const_value, Block);
753 /// addTemplateParams - Add template parameters into buffer.
754 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
755 // Add template parameters.
756 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
757 DIDescriptor Element = TParams.getElement(i);
758 if (Element.isTemplateTypeParameter())
759 constructTemplateTypeParameterDIE(Buffer,
760 DITemplateTypeParameter(Element));
761 else if (Element.isTemplateValueParameter())
762 constructTemplateValueParameterDIE(Buffer,
763 DITemplateValueParameter(Element));
767 /// getOrCreateContextDIE - Get context owner's DIE.
768 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
769 if (!Context || Context.isFile())
770 return &getUnitDie();
771 if (Context.isType())
772 return getOrCreateTypeDIE(DIType(Context));
773 if (Context.isNameSpace())
774 return getOrCreateNameSpace(DINameSpace(Context));
775 if (Context.isSubprogram())
776 return getOrCreateSubprogramDIE(DISubprogram(Context));
777 return getDIE(Context);
780 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
781 DIScope Context = resolve(Ty.getContext());
782 DIE *ContextDIE = getOrCreateContextDIE(Context);
784 if (DIE *TyDIE = getDIE(Ty))
788 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
790 constructTypeDIE(TyDIE, Ty);
792 updateAcceleratorTables(Context, Ty, TyDIE);
796 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
798 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
804 assert(Ty == resolve(Ty.getRef()) &&
805 "type was not uniqued, possible ODR violation.");
807 // DW_TAG_restrict_type is not supported in DWARF2
808 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
809 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
811 // Construct the context before querying for the existence of the DIE in case
812 // such construction creates the DIE.
813 DIScope Context = resolve(Ty.getContext());
814 DIE *ContextDIE = getOrCreateContextDIE(Context);
817 if (DIE *TyDIE = getDIE(Ty))
821 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
823 updateAcceleratorTables(Context, Ty, TyDIE);
825 if (Ty.isBasicType())
826 constructTypeDIE(TyDIE, DIBasicType(Ty));
827 else if (Ty.isCompositeType()) {
828 DICompositeType CTy(Ty);
829 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
830 if (MDString *TypeId = CTy.getIdentifier()) {
831 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
832 // Skip updating the accelerator tables since this is not the full type.
835 constructTypeDIE(TyDIE, CTy);
837 assert(Ty.isDerivedType() && "Unknown kind of DIType");
838 constructTypeDIE(TyDIE, DIDerivedType(Ty));
844 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
846 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
847 bool IsImplementation = 0;
848 if (Ty.isCompositeType()) {
849 DICompositeType CT(Ty);
850 // A runtime language of 0 actually means C/C++ and that any
851 // non-negative value is some version of Objective-C/C++.
852 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
854 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
855 DD->addAccelType(Ty.getName(), TyDIE, Flags);
857 if (!Context || Context.isCompileUnit() || Context.isFile() ||
858 Context.isNameSpace())
859 addGlobalType(Ty, TyDIE, Context);
863 /// addType - Add a new type attribute to the specified entity.
864 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
865 assert(Ty && "Trying to add a type that doesn't exist?");
867 // Check for pre-existence.
868 DIEEntry *Entry = getDIEEntry(Ty);
869 // If it exists then use the existing value.
871 addDIEEntry(Entity, Attribute, Entry);
876 DIE *Buffer = getOrCreateTypeDIE(Ty);
879 Entry = createDIEEntry(*Buffer);
880 insertDIEEntry(Ty, Entry);
881 addDIEEntry(Entity, Attribute, Entry);
884 /// getParentContextString - Walks the metadata parent chain in a language
885 /// specific manner (using the compile unit language) and returns
886 /// it as a string. This is done at the metadata level because DIEs may
887 /// not currently have been added to the parent context and walking the
888 /// DIEs looking for names is more expensive than walking the metadata.
889 std::string DwarfUnit::getParentContextString(DIScope Context) const {
893 // FIXME: Decide whether to implement this for non-C++ languages.
894 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
898 SmallVector<DIScope, 1> Parents;
899 while (!Context.isCompileUnit()) {
900 Parents.push_back(Context);
901 if (Context.getContext())
902 Context = resolve(Context.getContext());
904 // Structure, etc types will have a NULL context if they're at the top
909 // Reverse iterate over our list to go from the outermost construct to the
911 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
915 StringRef Name = Ctx.getName();
916 if (Name.empty() && Ctx.isNameSpace())
917 Name = "(anonymous namespace)";
926 /// constructTypeDIE - Construct basic type die from DIBasicType.
927 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
928 // Get core information.
929 StringRef Name = BTy.getName();
930 // Add name if not anonymous or intermediate type.
932 addString(Buffer, dwarf::DW_AT_name, Name);
934 // An unspecified type only has a name attribute.
935 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
938 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
941 uint64_t Size = BTy.getSizeInBits() >> 3;
942 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
945 /// constructTypeDIE - Construct derived type die from DIDerivedType.
946 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
947 // Get core information.
948 StringRef Name = DTy.getName();
949 uint64_t Size = DTy.getSizeInBits() >> 3;
950 uint16_t Tag = Buffer.getTag();
952 // Map to main type, void will not have a type.
953 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
955 addType(Buffer, FromTy);
957 // Add name if not anonymous or intermediate type.
959 addString(Buffer, dwarf::DW_AT_name, Name);
961 // Add size if non-zero (derived types might be zero-sized.)
962 if (Size && Tag != dwarf::DW_TAG_pointer_type
963 && Tag != dwarf::DW_TAG_ptr_to_member_type)
964 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
966 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
967 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
968 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
969 // Add source line info if available and TyDesc is not a forward declaration.
970 if (!DTy.isForwardDecl())
971 addSourceLine(Buffer, DTy);
974 /// constructSubprogramArguments - Construct function argument DIEs.
975 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
976 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
977 DIType Ty = resolve(Args.getElement(i));
979 assert(i == N-1 && "Unspecified parameter must be the last argument");
980 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
982 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
984 if (Ty.isArtificial())
985 addFlag(Arg, dwarf::DW_AT_artificial);
990 /// constructTypeDIE - Construct type DIE from DICompositeType.
991 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
992 // Add name if not anonymous or intermediate type.
993 StringRef Name = CTy.getName();
995 uint64_t Size = CTy.getSizeInBits() >> 3;
996 uint16_t Tag = Buffer.getTag();
999 case dwarf::DW_TAG_array_type:
1000 constructArrayTypeDIE(Buffer, CTy);
1002 case dwarf::DW_TAG_enumeration_type:
1003 constructEnumTypeDIE(Buffer, CTy);
1005 case dwarf::DW_TAG_subroutine_type: {
1006 // Add return type. A void return won't have a type.
1007 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1008 DIType RTy(resolve(Elements.getElement(0)));
1010 addType(Buffer, RTy);
1012 bool isPrototyped = true;
1013 if (Elements.getNumElements() == 2 &&
1014 !Elements.getElement(1))
1015 isPrototyped = false;
1017 constructSubprogramArguments(Buffer, Elements);
1019 // Add prototype flag if we're dealing with a C language and the
1020 // function has been prototyped.
1021 uint16_t Language = getLanguage();
1023 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1024 Language == dwarf::DW_LANG_ObjC))
1025 addFlag(Buffer, dwarf::DW_AT_prototyped);
1027 if (CTy.isLValueReference())
1028 addFlag(Buffer, dwarf::DW_AT_reference);
1030 if (CTy.isRValueReference())
1031 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1033 case dwarf::DW_TAG_structure_type:
1034 case dwarf::DW_TAG_union_type:
1035 case dwarf::DW_TAG_class_type: {
1036 // Add elements to structure type.
1037 DIArray Elements = CTy.getElements();
1038 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1039 DIDescriptor Element = Elements.getElement(i);
1040 if (Element.isSubprogram())
1041 getOrCreateSubprogramDIE(DISubprogram(Element));
1042 else if (Element.isDerivedType()) {
1043 DIDerivedType DDTy(Element);
1044 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1045 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1046 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1047 dwarf::DW_AT_friend);
1048 } else if (DDTy.isStaticMember()) {
1049 getOrCreateStaticMemberDIE(DDTy);
1051 constructMemberDIE(Buffer, DDTy);
1053 } else if (Element.isObjCProperty()) {
1054 DIObjCProperty Property(Element);
1055 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1056 StringRef PropertyName = Property.getObjCPropertyName();
1057 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1058 if (Property.getType())
1059 addType(ElemDie, Property.getType());
1060 addSourceLine(ElemDie, Property);
1061 StringRef GetterName = Property.getObjCPropertyGetterName();
1062 if (!GetterName.empty())
1063 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1064 StringRef SetterName = Property.getObjCPropertySetterName();
1065 if (!SetterName.empty())
1066 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1067 unsigned PropertyAttributes = 0;
1068 if (Property.isReadOnlyObjCProperty())
1069 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1070 if (Property.isReadWriteObjCProperty())
1071 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1072 if (Property.isAssignObjCProperty())
1073 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1074 if (Property.isRetainObjCProperty())
1075 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1076 if (Property.isCopyObjCProperty())
1077 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1078 if (Property.isNonAtomicObjCProperty())
1079 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1080 if (PropertyAttributes)
1081 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1082 PropertyAttributes);
1084 DIEEntry *Entry = getDIEEntry(Element);
1086 Entry = createDIEEntry(ElemDie);
1087 insertDIEEntry(Element, Entry);
1093 if (CTy.isAppleBlockExtension())
1094 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1096 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
1097 // inside C++ composite types to point to the base class with the vtable.
1098 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1100 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1101 *getOrCreateTypeDIE(ContainingType));
1103 if (CTy.isObjcClassComplete())
1104 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1106 // Add template parameters to a class, structure or union types.
1107 // FIXME: The support isn't in the metadata for this yet.
1108 if (Tag == dwarf::DW_TAG_class_type ||
1109 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1110 addTemplateParams(Buffer, CTy.getTemplateParams());
1118 // Add name if not anonymous or intermediate type.
1120 addString(Buffer, dwarf::DW_AT_name, Name);
1122 if (Tag == dwarf::DW_TAG_enumeration_type ||
1123 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1124 Tag == dwarf::DW_TAG_union_type) {
1125 // Add size if non-zero (derived types might be zero-sized.)
1126 // TODO: Do we care about size for enum forward declarations?
1128 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1129 else if (!CTy.isForwardDecl())
1130 // Add zero size if it is not a forward declaration.
1131 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1133 // If we're a forward decl, say so.
1134 if (CTy.isForwardDecl())
1135 addFlag(Buffer, dwarf::DW_AT_declaration);
1137 // Add source line info if available.
1138 if (!CTy.isForwardDecl())
1139 addSourceLine(Buffer, CTy);
1141 // No harm in adding the runtime language to the declaration.
1142 unsigned RLang = CTy.getRunTimeLang();
1144 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1149 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1150 /// DITemplateTypeParameter.
1151 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1152 DITemplateTypeParameter TP) {
1154 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1155 // Add the type if it exists, it could be void and therefore no type.
1157 addType(ParamDIE, resolve(TP.getType()));
1158 if (!TP.getName().empty())
1159 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1162 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1163 /// DITemplateValueParameter.
1165 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1166 DITemplateValueParameter VP) {
1167 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1169 // Add the type if there is one, template template and template parameter
1170 // packs will not have a type.
1171 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1172 addType(ParamDIE, resolve(VP.getType()));
1173 if (!VP.getName().empty())
1174 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1175 if (Metadata *Val = VP.getValue()) {
1176 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1177 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1178 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1179 // For declaration non-type template parameters (such as global values and
1181 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1182 addOpAddress(*Loc, Asm->getSymbol(GV));
1183 // Emit DW_OP_stack_value to use the address as the immediate value of the
1184 // parameter, rather than a pointer to it.
1185 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1186 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1187 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1188 assert(isa<MDString>(Val));
1189 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1190 cast<MDString>(Val)->getString());
1191 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1192 assert(isa<MDNode>(Val));
1193 DIArray A(cast<MDNode>(Val));
1194 addTemplateParams(ParamDIE, A);
1199 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1200 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1201 // Construct the context before querying for the existence of the DIE in case
1202 // such construction creates the DIE.
1203 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1205 if (DIE *NDie = getDIE(NS))
1207 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1209 StringRef Name = NS.getName();
1211 addString(NDie, dwarf::DW_AT_name, NS.getName());
1213 Name = "(anonymous namespace)";
1214 DD->addAccelNamespace(Name, NDie);
1215 addGlobalName(Name, NDie, NS.getContext());
1216 addSourceLine(NDie, NS);
1220 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1221 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP, bool Minimal) {
1222 // Construct the context before querying for the existence of the DIE in case
1223 // such construction creates the DIE (as is the case for member function
1226 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP.getContext()));
1228 if (DIE *SPDie = getDIE(SP))
1231 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1233 // Add subprogram definitions to the CU die directly.
1234 ContextDIE = &getUnitDie();
1235 // Build the decl now to ensure it precedes the definition.
1236 getOrCreateSubprogramDIE(SPDecl);
1240 // DW_TAG_inlined_subroutine may refer to this DIE.
1241 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1243 // Stop here and fill this in later, depending on whether or not this
1244 // subprogram turns out to have inlined instances or not.
1245 if (SP.isDefinition())
1248 applySubprogramAttributes(SP, SPDie);
1252 bool DwarfUnit::applySubprogramDefinitionAttributes(DISubprogram SP,
1254 DIE *DeclDie = nullptr;
1255 StringRef DeclLinkageName;
1256 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1257 DeclDie = getDIE(SPDecl);
1258 assert(DeclDie && "This DIE should've already been constructed when the "
1259 "definition DIE was created in "
1260 "getOrCreateSubprogramDIE");
1261 DeclLinkageName = SPDecl.getLinkageName();
1264 // Add function template parameters.
1265 addTemplateParams(SPDie, SP.getTemplateParams());
1267 // Add the linkage name if we have one and it isn't in the Decl.
1268 StringRef LinkageName = SP.getLinkageName();
1269 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1270 LinkageName == DeclLinkageName) &&
1271 "decl has a linkage name and it is different");
1272 if (!LinkageName.empty() && DeclLinkageName.empty())
1273 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1274 GlobalValue::getRealLinkageName(LinkageName));
1279 // Refer to the function declaration where all the other attributes will be
1281 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1285 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie,
1288 if (applySubprogramDefinitionAttributes(SP, SPDie))
1291 // Constructors and operators for anonymous aggregates do not have names.
1292 if (!SP.getName().empty())
1293 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1295 // Skip the rest of the attributes under -gmlt to save space.
1299 addSourceLine(SPDie, SP);
1301 // Add the prototype if we have a prototype and we have a C like
1303 uint16_t Language = getLanguage();
1304 if (SP.isPrototyped() &&
1305 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1306 Language == dwarf::DW_LANG_ObjC))
1307 addFlag(SPDie, dwarf::DW_AT_prototyped);
1309 DISubroutineType SPTy = SP.getType();
1310 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1311 "the type of a subprogram should be a subroutine");
1313 DITypeArray Args = SPTy.getTypeArray();
1314 // Add a return type. If this is a type like a C/C++ void type we don't add a
1316 if (resolve(Args.getElement(0)))
1317 addType(SPDie, DIType(resolve(Args.getElement(0))));
1319 unsigned VK = SP.getVirtuality();
1321 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1322 DIELoc *Block = getDIELoc();
1323 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1324 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1325 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1326 ContainingTypeMap.insert(
1327 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1330 if (!SP.isDefinition()) {
1331 addFlag(SPDie, dwarf::DW_AT_declaration);
1333 // Add arguments. Do not add arguments for subprogram definition. They will
1334 // be handled while processing variables.
1335 constructSubprogramArguments(SPDie, Args);
1338 if (SP.isArtificial())
1339 addFlag(SPDie, dwarf::DW_AT_artificial);
1341 if (!SP.isLocalToUnit())
1342 addFlag(SPDie, dwarf::DW_AT_external);
1344 if (SP.isOptimized())
1345 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1347 if (unsigned isa = Asm->getISAEncoding(SP.getFunction())) {
1348 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1351 if (SP.isLValueReference())
1352 addFlag(SPDie, dwarf::DW_AT_reference);
1354 if (SP.isRValueReference())
1355 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1357 if (SP.isProtected())
1358 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1359 dwarf::DW_ACCESS_protected);
1360 else if (SP.isPrivate())
1361 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1362 dwarf::DW_ACCESS_private);
1363 else if (SP.isPublic())
1364 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1365 dwarf::DW_ACCESS_public);
1367 if (SP.isExplicit())
1368 addFlag(SPDie, dwarf::DW_AT_explicit);
1371 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1372 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1373 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1374 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1376 // The LowerBound value defines the lower bounds which is typically zero for
1377 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1378 // Count == -1 then the array is unbounded and we do not emit
1379 // DW_AT_lower_bound and DW_AT_count attributes.
1380 int64_t LowerBound = SR.getLo();
1381 int64_t DefaultLowerBound = getDefaultLowerBound();
1382 int64_t Count = SR.getCount();
1384 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1385 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1388 // FIXME: An unbounded array should reference the expression that defines
1390 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1393 DIE *DwarfUnit::getIndexTyDie() {
1396 // Construct an integer type to use for indexes.
1397 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1398 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1399 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1400 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1401 dwarf::DW_ATE_unsigned);
1405 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1406 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1408 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1410 // Emit the element type.
1411 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1413 // Get an anonymous type for index type.
1414 // FIXME: This type should be passed down from the front end
1415 // as different languages may have different sizes for indexes.
1416 DIE *IdxTy = getIndexTyDie();
1418 // Add subranges to array type.
1419 DIArray Elements = CTy.getElements();
1420 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1421 DIDescriptor Element = Elements.getElement(i);
1422 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1423 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1427 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1428 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1429 DIArray Elements = CTy.getElements();
1431 // Add enumerators to enumeration type.
1432 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1433 DIEnumerator Enum(Elements.getElement(i));
1434 if (Enum.isEnumerator()) {
1435 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1436 StringRef Name = Enum.getName();
1437 addString(Enumerator, dwarf::DW_AT_name, Name);
1438 int64_t Value = Enum.getEnumValue();
1439 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1443 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1445 addType(Buffer, DTy);
1446 addFlag(Buffer, dwarf::DW_AT_enum_class);
1450 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1452 void DwarfUnit::constructContainingTypeDIEs() {
1453 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1454 CE = ContainingTypeMap.end();
1456 DIE &SPDie = *CI->first;
1457 DIDescriptor D(CI->second);
1460 DIE *NDie = getDIE(D);
1463 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1467 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1468 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1469 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1470 StringRef Name = DT.getName();
1472 addString(MemberDie, dwarf::DW_AT_name, Name);
1474 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1476 addSourceLine(MemberDie, DT);
1478 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1480 // For C++, virtual base classes are not at fixed offset. Use following
1481 // expression to extract appropriate offset from vtable.
1482 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1484 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1485 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1486 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1487 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1488 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1489 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1490 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1491 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1493 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1495 uint64_t Size = DT.getSizeInBits();
1496 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1497 uint64_t OffsetInBytes;
1499 if (FieldSize && Size != FieldSize) {
1500 // Handle bitfield, assume bytes are 8 bits.
1501 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1502 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1504 uint64_t Offset = DT.getOffsetInBits();
1505 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1506 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1507 uint64_t FieldOffset = (HiMark - FieldSize);
1508 Offset -= FieldOffset;
1510 // Maybe we need to work from the other end.
1511 if (Asm->getDataLayout().isLittleEndian())
1512 Offset = FieldSize - (Offset + Size);
1513 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1515 // Here DW_AT_data_member_location points to the anonymous
1516 // field that includes this bit field.
1517 OffsetInBytes = FieldOffset >> 3;
1519 // This is not a bitfield.
1520 OffsetInBytes = DT.getOffsetInBits() >> 3;
1522 if (DD->getDwarfVersion() <= 2) {
1523 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1524 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1525 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1526 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1528 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1532 if (DT.isProtected())
1533 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1534 dwarf::DW_ACCESS_protected);
1535 else if (DT.isPrivate())
1536 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1537 dwarf::DW_ACCESS_private);
1538 // Otherwise C++ member and base classes are considered public.
1539 else if (DT.isPublic())
1540 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1541 dwarf::DW_ACCESS_public);
1543 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1544 dwarf::DW_VIRTUALITY_virtual);
1546 // Objective-C properties.
1547 if (MDNode *PNode = DT.getObjCProperty())
1548 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1549 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1552 if (DT.isArtificial())
1553 addFlag(MemberDie, dwarf::DW_AT_artificial);
1556 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1557 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1561 // Construct the context before querying for the existence of the DIE in case
1562 // such construction creates the DIE.
1563 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1564 assert(dwarf::isType(ContextDIE->getTag()) &&
1565 "Static member should belong to a type.");
1567 if (DIE *StaticMemberDIE = getDIE(DT))
1568 return StaticMemberDIE;
1570 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1572 DIType Ty = resolve(DT.getTypeDerivedFrom());
1574 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1575 addType(StaticMemberDIE, Ty);
1576 addSourceLine(StaticMemberDIE, DT);
1577 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1578 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1580 // FIXME: We could omit private if the parent is a class_type, and
1581 // public if the parent is something else.
1582 if (DT.isProtected())
1583 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1584 dwarf::DW_ACCESS_protected);
1585 else if (DT.isPrivate())
1586 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1587 dwarf::DW_ACCESS_private);
1588 else if (DT.isPublic())
1589 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1590 dwarf::DW_ACCESS_public);
1592 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1593 addConstantValue(StaticMemberDIE, CI, Ty);
1594 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1595 addConstantFPValue(StaticMemberDIE, CFP);
1597 return &StaticMemberDIE;
1600 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
1601 // Emit size of content not including length itself
1602 Asm->OutStreamer.AddComment("Length of Unit");
1603 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1605 Asm->OutStreamer.AddComment("DWARF version number");
1606 Asm->EmitInt16(DD->getDwarfVersion());
1607 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1608 // We share one abbreviations table across all units so it's always at the
1609 // start of the section. Use a relocatable offset where needed to ensure
1610 // linking doesn't invalidate that offset.
1612 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1614 // Use a constant value when no symbol is provided.
1616 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1617 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1620 void DwarfUnit::initSection(const MCSection *Section) {
1621 assert(!this->Section);
1622 this->Section = Section;
1625 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
1626 DwarfUnit::emitHeader(ASectionSym);
1627 Asm->OutStreamer.AddComment("Type Signature");
1628 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1629 Asm->OutStreamer.AddComment("Type DIE Offset");
1630 // In a skeleton type unit there is no type DIE so emit a zero offset.
1631 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1632 sizeof(Ty->getOffset()));
1635 bool DwarfTypeUnit::isDwoUnit() const {
1636 // Since there are no skeleton type units, all type units are dwo type units
1637 // when split DWARF is being used.
1638 return DD->useSplitDwarf();