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 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP,
47 DwarfUnit &DU, DIELoc &DIE)
48 : DwarfExpression(*AP.TM.getSubtargetImpl()->getRegisterInfo(),
49 AP.getDwarfDebug()->getDwarfVersion()),
50 AP(AP), DU(DU), DIE(DIE) {}
52 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
53 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
55 void DIEDwarfExpression::EmitSigned(int Value) {
56 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
58 void DIEDwarfExpression::EmitUnsigned(unsigned Value) {
59 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
61 bool DIEDwarfExpression::isFrameRegister(unsigned MachineReg) {
62 return MachineReg == TRI.getFrameRegister(*AP.MF);
66 /// Unit - Unit constructor.
67 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
68 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
69 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
70 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
71 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
72 UnitTag == dwarf::DW_TAG_type_unit);
73 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
76 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
77 DwarfDebug *DW, DwarfFile *DWU,
78 MCDwarfDwoLineTable *SplitLineTable)
79 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
80 CU(CU), SplitLineTable(SplitLineTable) {
82 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
85 /// ~Unit - Destructor for compile unit.
86 DwarfUnit::~DwarfUnit() {
87 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
88 DIEBlocks[j]->~DIEBlock();
89 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
90 DIELocs[j]->~DIELoc();
93 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
94 /// information entry.
95 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
96 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
100 /// getDefaultLowerBound - Return the default lower bound for an array. If the
101 /// DWARF version doesn't handle the language, return -1.
102 int64_t DwarfUnit::getDefaultLowerBound() const {
103 switch (getLanguage()) {
107 case dwarf::DW_LANG_C89:
108 case dwarf::DW_LANG_C99:
109 case dwarf::DW_LANG_C:
110 case dwarf::DW_LANG_C_plus_plus:
111 case dwarf::DW_LANG_ObjC:
112 case dwarf::DW_LANG_ObjC_plus_plus:
115 case dwarf::DW_LANG_Fortran77:
116 case dwarf::DW_LANG_Fortran90:
117 case dwarf::DW_LANG_Fortran95:
120 // The languages below have valid values only if the DWARF version >= 4.
121 case dwarf::DW_LANG_Java:
122 case dwarf::DW_LANG_Python:
123 case dwarf::DW_LANG_UPC:
124 case dwarf::DW_LANG_D:
125 if (dwarf::DWARF_VERSION >= 4)
129 case dwarf::DW_LANG_Ada83:
130 case dwarf::DW_LANG_Ada95:
131 case dwarf::DW_LANG_Cobol74:
132 case dwarf::DW_LANG_Cobol85:
133 case dwarf::DW_LANG_Modula2:
134 case dwarf::DW_LANG_Pascal83:
135 case dwarf::DW_LANG_PLI:
136 if (dwarf::DWARF_VERSION >= 4)
140 // The languages below have valid values only if the DWARF version >= 5.
141 case dwarf::DW_LANG_OpenCL:
142 case dwarf::DW_LANG_Go:
143 case dwarf::DW_LANG_Haskell:
144 case dwarf::DW_LANG_C_plus_plus_03:
145 case dwarf::DW_LANG_C_plus_plus_11:
146 case dwarf::DW_LANG_OCaml:
147 case dwarf::DW_LANG_Rust:
148 case dwarf::DW_LANG_C11:
149 case dwarf::DW_LANG_Swift:
150 case dwarf::DW_LANG_Dylan:
151 case dwarf::DW_LANG_C_plus_plus_14:
152 if (dwarf::DWARF_VERSION >= 5)
156 case dwarf::DW_LANG_Modula3:
157 case dwarf::DW_LANG_Julia:
158 case dwarf::DW_LANG_Fortran03:
159 case dwarf::DW_LANG_Fortran08:
160 if (dwarf::DWARF_VERSION >= 5)
168 /// Check whether the DIE for this MDNode can be shared across CUs.
169 static bool isShareableAcrossCUs(DIDescriptor D) {
170 // When the MDNode can be part of the type system, the DIE can be shared
172 // Combining type units and cross-CU DIE sharing is lower value (since
173 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
174 // level already) but may be implementable for some value in projects
175 // building multiple independent libraries with LTO and then linking those
177 return (D.isType() ||
178 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
179 !GenerateDwarfTypeUnits;
182 /// getDIE - Returns the debug information entry map slot for the
183 /// specified debug variable. We delegate the request to DwarfDebug
184 /// when the DIE for this MDNode can be shared across CUs. The mappings
185 /// will be kept in DwarfDebug for shareable DIEs.
186 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
187 if (isShareableAcrossCUs(D))
188 return DU->getDIE(D);
189 return MDNodeToDieMap.lookup(D);
192 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
193 /// when the DIE for this MDNode can be shared across CUs. The mappings
194 /// will be kept in DwarfDebug for shareable DIEs.
195 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
196 if (isShareableAcrossCUs(Desc)) {
197 DU->insertDIE(Desc, D);
200 MDNodeToDieMap.insert(std::make_pair(Desc, D));
203 /// addFlag - Add a flag that is true.
204 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
205 if (DD->getDwarfVersion() >= 4)
206 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
208 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
211 /// addUInt - Add an unsigned integer attribute data and value.
213 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
214 Optional<dwarf::Form> Form, uint64_t Integer) {
216 Form = DIEInteger::BestForm(false, Integer);
217 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
219 Die.addValue(Attribute, *Form, Value);
222 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
223 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
226 /// addSInt - Add an signed integer attribute data and value.
228 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
229 Optional<dwarf::Form> Form, int64_t Integer) {
231 Form = DIEInteger::BestForm(true, Integer);
232 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
233 Die.addValue(Attribute, *Form, Value);
236 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
238 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
241 /// addString - Add a string attribute data and value. We always emit a
242 /// reference to the string pool instead of immediate strings so that DIEs have
243 /// more predictable sizes. In the case of split dwarf we emit an index
244 /// into another table which gets us the static offset into the string
246 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
249 return addLocalString(Die, Attribute, String);
251 addIndexedString(Die, Attribute, String);
254 void DwarfUnit::addIndexedString(DIE &Die, dwarf::Attribute Attribute,
256 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
257 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
258 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
259 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
262 /// addLocalString - Add a string attribute data and value. This is guaranteed
263 /// to be in the local string pool instead of indirected.
264 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
266 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
268 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
269 Value = new (DIEValueAllocator) DIELabel(Symb);
271 Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
272 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
273 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
276 /// addLabel - Add a Dwarf label attribute data and value.
278 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
279 const MCSymbol *Label) {
280 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
281 Die.addValue(Attribute, Form, Value);
284 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
285 addLabel(Die, (dwarf::Attribute)0, Form, Label);
288 /// addSectionOffset - Add an offset into a section attribute data and value.
290 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
292 if (DD->getDwarfVersion() >= 4)
293 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
295 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
298 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
299 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
300 : getCU().getOrCreateSourceID(FileName, DirName);
303 /// addOpAddress - Add a dwarf op address data and value using the
304 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
306 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
307 if (!DD->useSplitDwarf()) {
308 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
309 addLabel(Die, dwarf::DW_FORM_udata, Sym);
311 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
312 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
313 DD->getAddressPool().getIndex(Sym));
317 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
318 const MCSymbol *Hi, const MCSymbol *Lo) {
319 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
320 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
323 /// addDIEEntry - Add a DIE attribute data and value.
325 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
326 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
329 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
330 // Flag the type unit reference as a declaration so that if it contains
331 // members (implicit special members, static data member definitions, member
332 // declarations for definitions in this CU, etc) consumers don't get confused
333 // and think this is a full definition.
334 addFlag(Die, dwarf::DW_AT_declaration);
336 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
337 new (DIEValueAllocator) DIETypeSignature(Type));
340 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
342 const DIE *DieCU = Die.getUnitOrNull();
343 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
345 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
346 DieCU = &getUnitDie();
348 EntryCU = &getUnitDie();
349 Die.addValue(Attribute,
350 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
354 /// Create a DIE with the given Tag, add the DIE to its parent, and
355 /// call insertDIE if MD is not null.
356 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
357 assert(Tag != dwarf::DW_TAG_auto_variable &&
358 Tag != dwarf::DW_TAG_arg_variable);
359 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
360 DIE &Die = *Parent.getChildren().back();
366 /// addBlock - Add block data.
368 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
369 Loc->ComputeSize(Asm);
370 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
371 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
374 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
376 Block->ComputeSize(Asm);
377 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
378 Die.addValue(Attribute, Block->BestForm(), Block);
381 /// addSourceLine - Add location information to specified debug information
383 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
384 StringRef Directory) {
388 unsigned FileID = getOrCreateSourceID(File, Directory);
389 assert(FileID && "Invalid file id");
390 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
391 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
394 /// addSourceLine - Add location information to specified debug information
396 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
397 assert(V.isVariable());
399 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
400 V.getContext().getDirectory());
403 /// addSourceLine - Add location information to specified debug information
405 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
406 assert(G.isGlobalVariable());
408 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
411 /// addSourceLine - Add location information to specified debug information
413 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
414 assert(SP.isSubprogram());
416 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
419 /// addSourceLine - Add location information to specified debug information
421 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
424 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
427 /// addSourceLine - Add location information to specified debug information
429 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
430 assert(Ty.isObjCProperty());
432 DIFile File = Ty.getFile();
433 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
434 File.getDirectory());
437 /// addSourceLine - Add location information to specified debug information
439 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
442 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
445 /// addRegisterOp - Add register operand.
446 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
447 unsigned SizeInBits, unsigned OffsetInBits) {
448 DIEDwarfExpression Expr(*Asm, *this, TheDie);
449 Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
453 /// addRegisterOffset - Add register offset.
454 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
456 DIEDwarfExpression Expr(*Asm, *this, TheDie);
457 return Expr.AddMachineRegIndirect(Reg, Offset);
460 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
461 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
462 gives the variable VarName either the struct, or a pointer to the struct, as
463 its type. This is necessary for various behind-the-scenes things the
464 compiler needs to do with by-reference variables in Blocks.
466 However, as far as the original *programmer* is concerned, the variable
467 should still have type 'SomeType', as originally declared.
469 The function getBlockByrefType dives into the __Block_byref_x_VarName
470 struct to find the original type of the variable, which is then assigned to
471 the variable's Debug Information Entry as its real type. So far, so good.
472 However now the debugger will expect the variable VarName to have the type
473 SomeType. So we need the location attribute for the variable to be an
474 expression that explains to the debugger how to navigate through the
475 pointers and struct to find the actual variable of type SomeType.
477 The following function does just that. We start by getting
478 the "normal" location for the variable. This will be the location
479 of either the struct __Block_byref_x_VarName or the pointer to the
480 struct __Block_byref_x_VarName.
482 The struct will look something like:
484 struct __Block_byref_x_VarName {
486 struct __Block_byref_x_VarName *forwarding;
487 ... <various other fields>
489 ... <maybe more fields>
492 If we are given the struct directly (as our starting point) we
493 need to tell the debugger to:
495 1). Add the offset of the forwarding field.
497 2). Follow that pointer to get the real __Block_byref_x_VarName
498 struct to use (the real one may have been copied onto the heap).
500 3). Add the offset for the field VarName, to find the actual variable.
502 If we started with a pointer to the struct, then we need to
503 dereference that pointer first, before the other steps.
504 Translating this into DWARF ops, we will need to append the following
505 to the current location description for the variable:
507 DW_OP_deref -- optional, if we start with a pointer
508 DW_OP_plus_uconst <forward_fld_offset>
510 DW_OP_plus_uconst <varName_fld_offset>
512 That is what this function does. */
514 /// addBlockByrefAddress - Start with the address based on the location
515 /// provided, and generate the DWARF information necessary to find the
516 /// actual Block variable (navigating the Block struct) based on the
517 /// starting location. Add the DWARF information to the die. For
518 /// more information, read large comment just above here.
520 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
521 dwarf::Attribute Attribute,
522 const MachineLocation &Location) {
523 DIType Ty = DV.getType();
525 uint16_t Tag = Ty.getTag();
526 bool isPointer = false;
528 StringRef varName = DV.getName();
530 if (Tag == dwarf::DW_TAG_pointer_type) {
531 DIDerivedType DTy(Ty);
532 TmpTy = resolve(DTy.getTypeDerivedFrom());
536 DICompositeType blockStruct(TmpTy);
538 // Find the __forwarding field and the variable field in the __Block_byref
540 DIArray Fields = blockStruct.getElements();
541 DIDerivedType varField;
542 DIDerivedType forwardingField;
544 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
545 DIDerivedType DT(Fields.getElement(i));
546 StringRef fieldName = DT.getName();
547 if (fieldName == "__forwarding")
548 forwardingField = DT;
549 else if (fieldName == varName)
553 // Get the offsets for the forwarding field and the variable field.
554 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
555 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
557 // Decode the original location, and use that as the start of the byref
558 // variable's location.
559 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
562 if (Location.isReg())
563 validReg = addRegisterOpPiece(*Loc, Location.getReg());
565 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
570 // If we started with a pointer to the __Block_byref... struct, then
571 // the first thing we need to do is dereference the pointer (DW_OP_deref).
573 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
575 // Next add the offset for the '__forwarding' field:
576 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
577 // adding the offset if it's 0.
578 if (forwardingFieldOffset > 0) {
579 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
580 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
583 // Now dereference the __forwarding field to get to the real __Block_byref
584 // struct: DW_OP_deref.
585 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
587 // Now that we've got the real __Block_byref... struct, add the offset
588 // for the variable's field to get to the location of the actual variable:
589 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
590 if (varFieldOffset > 0) {
591 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
592 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
595 // Now attach the location information to the DIE.
596 addBlock(Die, Attribute, Loc);
599 /// Return true if type encoding is unsigned.
600 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
601 DIDerivedType DTy(Ty);
602 if (DTy.isDerivedType()) {
603 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
604 // Encode pointer constants as unsigned bytes. This is used at least for
605 // null pointer constant emission.
606 // (Pieces of) aggregate types that get hacked apart by SROA may also be
607 // represented by a constant. Encode them as unsigned bytes.
608 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
609 // here, but accept them for now due to a bug in SROA producing bogus
611 if (T == dwarf::DW_TAG_array_type ||
612 T == dwarf::DW_TAG_class_type ||
613 T == dwarf::DW_TAG_pointer_type ||
614 T == dwarf::DW_TAG_ptr_to_member_type ||
615 T == dwarf::DW_TAG_reference_type ||
616 T == dwarf::DW_TAG_rvalue_reference_type ||
617 T == dwarf::DW_TAG_structure_type ||
618 T == dwarf::DW_TAG_union_type)
620 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
621 T == dwarf::DW_TAG_volatile_type ||
622 T == dwarf::DW_TAG_restrict_type ||
623 T == dwarf::DW_TAG_enumeration_type);
624 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
625 return isUnsignedDIType(DD, DD->resolve(Deriv));
626 // FIXME: Enums without a fixed underlying type have unknown signedness
627 // here, leading to incorrectly emitted constants.
628 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
633 assert(BTy.isBasicType());
634 unsigned Encoding = BTy.getEncoding();
635 assert((Encoding == dwarf::DW_ATE_unsigned ||
636 Encoding == dwarf::DW_ATE_unsigned_char ||
637 Encoding == dwarf::DW_ATE_signed ||
638 Encoding == dwarf::DW_ATE_signed_char ||
639 Encoding == dwarf::DW_ATE_float ||
640 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
641 (Ty.getTag() == dwarf::DW_TAG_unspecified_type &&
642 Ty.getName() == "decltype(nullptr)")) &&
643 "Unsupported encoding");
644 return (Encoding == dwarf::DW_ATE_unsigned ||
645 Encoding == dwarf::DW_ATE_unsigned_char ||
646 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
647 Ty.getTag() == dwarf::DW_TAG_unspecified_type);
650 /// If this type is derived from a base type then return base type size.
651 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
652 unsigned Tag = Ty.getTag();
654 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
655 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
656 Tag != dwarf::DW_TAG_restrict_type)
657 return Ty.getSizeInBits();
659 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
661 assert(BaseType.isValid() && "Unexpected invalid base type");
663 // If this is a derived type, go ahead and get the base type, unless it's a
664 // reference then it's just the size of the field. Pointer types have no need
665 // of this since they're a different type of qualification on the type.
666 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
667 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
668 return Ty.getSizeInBits();
670 if (BaseType.isDerivedType())
671 return getBaseTypeSize(DD, DIDerivedType(BaseType));
673 return BaseType.getSizeInBits();
676 /// addConstantFPValue - Add constant value entry in variable DIE.
677 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
678 assert(MO.isFPImm() && "Invalid machine operand!");
679 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
680 APFloat FPImm = MO.getFPImm()->getValueAPF();
682 // Get the raw data form of the floating point.
683 const APInt FltVal = FPImm.bitcastToAPInt();
684 const char *FltPtr = (const char *)FltVal.getRawData();
686 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
687 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
688 int Incr = (LittleEndian ? 1 : -1);
689 int Start = (LittleEndian ? 0 : NumBytes - 1);
690 int Stop = (LittleEndian ? NumBytes : -1);
692 // Output the constant to DWARF one byte at a time.
693 for (; Start != Stop; Start += Incr)
694 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
696 addBlock(Die, dwarf::DW_AT_const_value, Block);
699 /// addConstantFPValue - Add constant value entry in variable DIE.
700 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
701 // Pass this down to addConstantValue as an unsigned bag of bits.
702 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
705 /// addConstantValue - Add constant value entry in variable DIE.
706 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
707 addConstantValue(Die, CI->getValue(), Ty);
710 /// addConstantValue - Add constant value entry in variable DIE.
711 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
713 assert(MO.isImm() && "Invalid machine operand!");
715 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
718 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
719 // FIXME: This is a bit conservative/simple - it emits negative values always
720 // sign extended to 64 bits rather than minimizing the number of bytes.
721 addUInt(Die, dwarf::DW_AT_const_value,
722 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
725 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
726 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
729 // addConstantValue - Add constant value entry in variable DIE.
730 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
731 unsigned CIBitWidth = Val.getBitWidth();
732 if (CIBitWidth <= 64) {
733 addConstantValue(Die, Unsigned,
734 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
738 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
740 // Get the raw data form of the large APInt.
741 const uint64_t *Ptr64 = Val.getRawData();
743 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
744 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
746 // Output the constant to DWARF one byte at a time.
747 for (int i = 0; i < NumBytes; i++) {
750 c = Ptr64[i / 8] >> (8 * (i & 7));
752 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
753 addUInt(*Block, dwarf::DW_FORM_data1, c);
756 addBlock(Die, dwarf::DW_AT_const_value, Block);
759 /// addTemplateParams - Add template parameters into buffer.
760 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
761 // Add template parameters.
762 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
763 DIDescriptor Element = TParams.getElement(i);
764 if (Element.isTemplateTypeParameter())
765 constructTemplateTypeParameterDIE(Buffer,
766 DITemplateTypeParameter(Element));
767 else if (Element.isTemplateValueParameter())
768 constructTemplateValueParameterDIE(Buffer,
769 DITemplateValueParameter(Element));
773 /// getOrCreateContextDIE - Get context owner's DIE.
774 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
775 if (!Context || Context.isFile())
776 return &getUnitDie();
777 if (Context.isType())
778 return getOrCreateTypeDIE(DIType(Context));
779 if (Context.isNameSpace())
780 return getOrCreateNameSpace(DINameSpace(Context));
781 if (Context.isSubprogram())
782 return getOrCreateSubprogramDIE(DISubprogram(Context));
783 return getDIE(Context);
786 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
787 DIScope Context = resolve(Ty.getContext());
788 DIE *ContextDIE = getOrCreateContextDIE(Context);
790 if (DIE *TyDIE = getDIE(Ty))
794 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
796 constructTypeDIE(TyDIE, Ty);
798 updateAcceleratorTables(Context, Ty, TyDIE);
802 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
804 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
810 assert(Ty == resolve(Ty.getRef()) &&
811 "type was not uniqued, possible ODR violation.");
813 // DW_TAG_restrict_type is not supported in DWARF2
814 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
815 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
817 // Construct the context before querying for the existence of the DIE in case
818 // such construction creates the DIE.
819 DIScope Context = resolve(Ty.getContext());
820 DIE *ContextDIE = getOrCreateContextDIE(Context);
823 if (DIE *TyDIE = getDIE(Ty))
827 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
829 updateAcceleratorTables(Context, Ty, TyDIE);
831 if (Ty.isBasicType())
832 constructTypeDIE(TyDIE, DIBasicType(Ty));
833 else if (Ty.isCompositeType()) {
834 DICompositeType CTy(Ty);
835 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
836 if (MDString *TypeId = CTy.getIdentifier()) {
837 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
838 // Skip updating the accelerator tables since this is not the full type.
841 constructTypeDIE(TyDIE, CTy);
843 assert(Ty.isDerivedType() && "Unknown kind of DIType");
844 constructTypeDIE(TyDIE, DIDerivedType(Ty));
850 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
852 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
853 bool IsImplementation = 0;
854 if (Ty.isCompositeType()) {
855 DICompositeType CT(Ty);
856 // A runtime language of 0 actually means C/C++ and that any
857 // non-negative value is some version of Objective-C/C++.
858 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
860 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
861 DD->addAccelType(Ty.getName(), TyDIE, Flags);
863 if (!Context || Context.isCompileUnit() || Context.isFile() ||
864 Context.isNameSpace())
865 addGlobalType(Ty, TyDIE, Context);
869 /// addType - Add a new type attribute to the specified entity.
870 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
871 assert(Ty && "Trying to add a type that doesn't exist?");
873 // Check for pre-existence.
874 DIEEntry *Entry = getDIEEntry(Ty);
875 // If it exists then use the existing value.
877 addDIEEntry(Entity, Attribute, Entry);
882 DIE *Buffer = getOrCreateTypeDIE(Ty);
885 Entry = createDIEEntry(*Buffer);
886 insertDIEEntry(Ty, Entry);
887 addDIEEntry(Entity, Attribute, Entry);
890 /// getParentContextString - Walks the metadata parent chain in a language
891 /// specific manner (using the compile unit language) and returns
892 /// it as a string. This is done at the metadata level because DIEs may
893 /// not currently have been added to the parent context and walking the
894 /// DIEs looking for names is more expensive than walking the metadata.
895 std::string DwarfUnit::getParentContextString(DIScope Context) const {
899 // FIXME: Decide whether to implement this for non-C++ languages.
900 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
904 SmallVector<DIScope, 1> Parents;
905 while (!Context.isCompileUnit()) {
906 Parents.push_back(Context);
907 if (Context.getContext())
908 Context = resolve(Context.getContext());
910 // Structure, etc types will have a NULL context if they're at the top
915 // Reverse iterate over our list to go from the outermost construct to the
917 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
921 StringRef Name = Ctx.getName();
922 if (Name.empty() && Ctx.isNameSpace())
923 Name = "(anonymous namespace)";
932 /// constructTypeDIE - Construct basic type die from DIBasicType.
933 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
934 // Get core information.
935 StringRef Name = BTy.getName();
936 // Add name if not anonymous or intermediate type.
938 addString(Buffer, dwarf::DW_AT_name, Name);
940 // An unspecified type only has a name attribute.
941 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
944 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
947 uint64_t Size = BTy.getSizeInBits() >> 3;
948 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
951 /// constructTypeDIE - Construct derived type die from DIDerivedType.
952 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
953 // Get core information.
954 StringRef Name = DTy.getName();
955 uint64_t Size = DTy.getSizeInBits() >> 3;
956 uint16_t Tag = Buffer.getTag();
958 // Map to main type, void will not have a type.
959 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
961 addType(Buffer, FromTy);
963 // Add name if not anonymous or intermediate type.
965 addString(Buffer, dwarf::DW_AT_name, Name);
967 // Add size if non-zero (derived types might be zero-sized.)
968 if (Size && Tag != dwarf::DW_TAG_pointer_type
969 && Tag != dwarf::DW_TAG_ptr_to_member_type)
970 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
972 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
973 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
974 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
975 // Add source line info if available and TyDesc is not a forward declaration.
976 if (!DTy.isForwardDecl())
977 addSourceLine(Buffer, DTy);
980 /// constructSubprogramArguments - Construct function argument DIEs.
981 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
982 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
983 DIType Ty = resolve(Args.getElement(i));
985 assert(i == N-1 && "Unspecified parameter must be the last argument");
986 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
988 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
990 if (Ty.isArtificial())
991 addFlag(Arg, dwarf::DW_AT_artificial);
996 /// constructTypeDIE - Construct type DIE from DICompositeType.
997 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
998 // Add name if not anonymous or intermediate type.
999 StringRef Name = CTy.getName();
1001 uint64_t Size = CTy.getSizeInBits() >> 3;
1002 uint16_t Tag = Buffer.getTag();
1005 case dwarf::DW_TAG_array_type:
1006 constructArrayTypeDIE(Buffer, CTy);
1008 case dwarf::DW_TAG_enumeration_type:
1009 constructEnumTypeDIE(Buffer, CTy);
1011 case dwarf::DW_TAG_subroutine_type: {
1012 // Add return type. A void return won't have a type.
1013 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1014 DIType RTy(resolve(Elements.getElement(0)));
1016 addType(Buffer, RTy);
1018 bool isPrototyped = true;
1019 if (Elements.getNumElements() == 2 &&
1020 !Elements.getElement(1))
1021 isPrototyped = false;
1023 constructSubprogramArguments(Buffer, Elements);
1025 // Add prototype flag if we're dealing with a C language and the
1026 // function has been prototyped.
1027 uint16_t Language = getLanguage();
1029 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1030 Language == dwarf::DW_LANG_ObjC))
1031 addFlag(Buffer, dwarf::DW_AT_prototyped);
1033 if (CTy.isLValueReference())
1034 addFlag(Buffer, dwarf::DW_AT_reference);
1036 if (CTy.isRValueReference())
1037 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1039 case dwarf::DW_TAG_structure_type:
1040 case dwarf::DW_TAG_union_type:
1041 case dwarf::DW_TAG_class_type: {
1042 // Add elements to structure type.
1043 DIArray Elements = CTy.getElements();
1044 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1045 DIDescriptor Element = Elements.getElement(i);
1046 if (Element.isSubprogram())
1047 getOrCreateSubprogramDIE(DISubprogram(Element));
1048 else if (Element.isDerivedType()) {
1049 DIDerivedType DDTy(Element);
1050 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1051 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1052 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1053 dwarf::DW_AT_friend);
1054 } else if (DDTy.isStaticMember()) {
1055 getOrCreateStaticMemberDIE(DDTy);
1057 constructMemberDIE(Buffer, DDTy);
1059 } else if (Element.isObjCProperty()) {
1060 DIObjCProperty Property(Element);
1061 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1062 StringRef PropertyName = Property.getObjCPropertyName();
1063 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1064 if (Property.getType())
1065 addType(ElemDie, Property.getType());
1066 addSourceLine(ElemDie, Property);
1067 StringRef GetterName = Property.getObjCPropertyGetterName();
1068 if (!GetterName.empty())
1069 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1070 StringRef SetterName = Property.getObjCPropertySetterName();
1071 if (!SetterName.empty())
1072 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1073 unsigned PropertyAttributes = 0;
1074 if (Property.isReadOnlyObjCProperty())
1075 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1076 if (Property.isReadWriteObjCProperty())
1077 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1078 if (Property.isAssignObjCProperty())
1079 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1080 if (Property.isRetainObjCProperty())
1081 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1082 if (Property.isCopyObjCProperty())
1083 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1084 if (Property.isNonAtomicObjCProperty())
1085 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1086 if (PropertyAttributes)
1087 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1088 PropertyAttributes);
1090 DIEEntry *Entry = getDIEEntry(Element);
1092 Entry = createDIEEntry(ElemDie);
1093 insertDIEEntry(Element, Entry);
1099 if (CTy.isAppleBlockExtension())
1100 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1102 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
1103 // inside C++ composite types to point to the base class with the vtable.
1104 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1106 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1107 *getOrCreateTypeDIE(ContainingType));
1109 if (CTy.isObjcClassComplete())
1110 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1112 // Add template parameters to a class, structure or union types.
1113 // FIXME: The support isn't in the metadata for this yet.
1114 if (Tag == dwarf::DW_TAG_class_type ||
1115 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1116 addTemplateParams(Buffer, CTy.getTemplateParams());
1124 // Add name if not anonymous or intermediate type.
1126 addString(Buffer, dwarf::DW_AT_name, Name);
1128 if (Tag == dwarf::DW_TAG_enumeration_type ||
1129 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1130 Tag == dwarf::DW_TAG_union_type) {
1131 // Add size if non-zero (derived types might be zero-sized.)
1132 // TODO: Do we care about size for enum forward declarations?
1134 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1135 else if (!CTy.isForwardDecl())
1136 // Add zero size if it is not a forward declaration.
1137 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1139 // If we're a forward decl, say so.
1140 if (CTy.isForwardDecl())
1141 addFlag(Buffer, dwarf::DW_AT_declaration);
1143 // Add source line info if available.
1144 if (!CTy.isForwardDecl())
1145 addSourceLine(Buffer, CTy);
1147 // No harm in adding the runtime language to the declaration.
1148 unsigned RLang = CTy.getRunTimeLang();
1150 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1155 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1156 /// DITemplateTypeParameter.
1157 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1158 DITemplateTypeParameter TP) {
1160 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1161 // Add the type if it exists, it could be void and therefore no type.
1163 addType(ParamDIE, resolve(TP.getType()));
1164 if (!TP.getName().empty())
1165 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1168 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1169 /// DITemplateValueParameter.
1171 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1172 DITemplateValueParameter VP) {
1173 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1175 // Add the type if there is one, template template and template parameter
1176 // packs will not have a type.
1177 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1178 addType(ParamDIE, resolve(VP.getType()));
1179 if (!VP.getName().empty())
1180 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1181 if (Metadata *Val = VP.getValue()) {
1182 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1183 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1184 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1185 // For declaration non-type template parameters (such as global values and
1187 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1188 addOpAddress(*Loc, Asm->getSymbol(GV));
1189 // Emit DW_OP_stack_value to use the address as the immediate value of the
1190 // parameter, rather than a pointer to it.
1191 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1192 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1193 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1194 assert(isa<MDString>(Val));
1195 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1196 cast<MDString>(Val)->getString());
1197 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1198 assert(isa<MDNode>(Val));
1199 DIArray A(cast<MDNode>(Val));
1200 addTemplateParams(ParamDIE, A);
1205 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1206 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1207 // Construct the context before querying for the existence of the DIE in case
1208 // such construction creates the DIE.
1209 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1211 if (DIE *NDie = getDIE(NS))
1213 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1215 StringRef Name = NS.getName();
1217 addString(NDie, dwarf::DW_AT_name, NS.getName());
1219 Name = "(anonymous namespace)";
1220 DD->addAccelNamespace(Name, NDie);
1221 addGlobalName(Name, NDie, NS.getContext());
1222 addSourceLine(NDie, NS);
1226 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1227 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP, bool Minimal) {
1228 // Construct the context before querying for the existence of the DIE in case
1229 // such construction creates the DIE (as is the case for member function
1232 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP.getContext()));
1234 if (DIE *SPDie = getDIE(SP))
1237 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1239 // Add subprogram definitions to the CU die directly.
1240 ContextDIE = &getUnitDie();
1241 // Build the decl now to ensure it precedes the definition.
1242 getOrCreateSubprogramDIE(SPDecl);
1246 // DW_TAG_inlined_subroutine may refer to this DIE.
1247 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1249 // Stop here and fill this in later, depending on whether or not this
1250 // subprogram turns out to have inlined instances or not.
1251 if (SP.isDefinition())
1254 applySubprogramAttributes(SP, SPDie);
1258 bool DwarfUnit::applySubprogramDefinitionAttributes(DISubprogram SP,
1260 DIE *DeclDie = nullptr;
1261 StringRef DeclLinkageName;
1262 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1263 DeclDie = getDIE(SPDecl);
1264 assert(DeclDie && "This DIE should've already been constructed when the "
1265 "definition DIE was created in "
1266 "getOrCreateSubprogramDIE");
1267 DeclLinkageName = SPDecl.getLinkageName();
1270 // Add function template parameters.
1271 addTemplateParams(SPDie, SP.getTemplateParams());
1273 // Add the linkage name if we have one and it isn't in the Decl.
1274 StringRef LinkageName = SP.getLinkageName();
1275 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1276 LinkageName == DeclLinkageName) &&
1277 "decl has a linkage name and it is different");
1278 if (!LinkageName.empty() && DeclLinkageName.empty())
1279 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1280 GlobalValue::getRealLinkageName(LinkageName));
1285 // Refer to the function declaration where all the other attributes will be
1287 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1291 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie,
1294 if (applySubprogramDefinitionAttributes(SP, SPDie))
1297 // Constructors and operators for anonymous aggregates do not have names.
1298 if (!SP.getName().empty())
1299 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1301 // Skip the rest of the attributes under -gmlt to save space.
1305 addSourceLine(SPDie, SP);
1307 // Add the prototype if we have a prototype and we have a C like
1309 uint16_t Language = getLanguage();
1310 if (SP.isPrototyped() &&
1311 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1312 Language == dwarf::DW_LANG_ObjC))
1313 addFlag(SPDie, dwarf::DW_AT_prototyped);
1315 DISubroutineType SPTy = SP.getType();
1316 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1317 "the type of a subprogram should be a subroutine");
1319 DITypeArray Args = SPTy.getTypeArray();
1320 // Add a return type. If this is a type like a C/C++ void type we don't add a
1322 if (resolve(Args.getElement(0)))
1323 addType(SPDie, DIType(resolve(Args.getElement(0))));
1325 unsigned VK = SP.getVirtuality();
1327 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1328 DIELoc *Block = getDIELoc();
1329 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1330 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1331 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1332 ContainingTypeMap.insert(
1333 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1336 if (!SP.isDefinition()) {
1337 addFlag(SPDie, dwarf::DW_AT_declaration);
1339 // Add arguments. Do not add arguments for subprogram definition. They will
1340 // be handled while processing variables.
1341 constructSubprogramArguments(SPDie, Args);
1344 if (SP.isArtificial())
1345 addFlag(SPDie, dwarf::DW_AT_artificial);
1347 if (!SP.isLocalToUnit())
1348 addFlag(SPDie, dwarf::DW_AT_external);
1350 if (SP.isOptimized())
1351 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1353 if (unsigned isa = Asm->getISAEncoding(SP.getFunction())) {
1354 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1357 if (SP.isLValueReference())
1358 addFlag(SPDie, dwarf::DW_AT_reference);
1360 if (SP.isRValueReference())
1361 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1363 if (SP.isProtected())
1364 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1365 dwarf::DW_ACCESS_protected);
1366 else if (SP.isPrivate())
1367 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1368 dwarf::DW_ACCESS_private);
1369 else if (SP.isPublic())
1370 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1371 dwarf::DW_ACCESS_public);
1373 if (SP.isExplicit())
1374 addFlag(SPDie, dwarf::DW_AT_explicit);
1377 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1378 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1379 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1380 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1382 // The LowerBound value defines the lower bounds which is typically zero for
1383 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1384 // Count == -1 then the array is unbounded and we do not emit
1385 // DW_AT_lower_bound and DW_AT_count attributes.
1386 int64_t LowerBound = SR.getLo();
1387 int64_t DefaultLowerBound = getDefaultLowerBound();
1388 int64_t Count = SR.getCount();
1390 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1391 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1394 // FIXME: An unbounded array should reference the expression that defines
1396 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1399 DIE *DwarfUnit::getIndexTyDie() {
1402 // Construct an integer type to use for indexes.
1403 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1404 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1405 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1406 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1407 dwarf::DW_ATE_unsigned);
1411 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1412 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1414 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1416 // Emit the element type.
1417 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1419 // Get an anonymous type for index type.
1420 // FIXME: This type should be passed down from the front end
1421 // as different languages may have different sizes for indexes.
1422 DIE *IdxTy = getIndexTyDie();
1424 // Add subranges to array type.
1425 DIArray Elements = CTy.getElements();
1426 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1427 DIDescriptor Element = Elements.getElement(i);
1428 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1429 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1433 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1434 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1435 DIArray Elements = CTy.getElements();
1437 // Add enumerators to enumeration type.
1438 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1439 DIEnumerator Enum(Elements.getElement(i));
1440 if (Enum.isEnumerator()) {
1441 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1442 StringRef Name = Enum.getName();
1443 addString(Enumerator, dwarf::DW_AT_name, Name);
1444 int64_t Value = Enum.getEnumValue();
1445 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1449 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1451 addType(Buffer, DTy);
1452 addFlag(Buffer, dwarf::DW_AT_enum_class);
1456 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1458 void DwarfUnit::constructContainingTypeDIEs() {
1459 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1460 CE = ContainingTypeMap.end();
1462 DIE &SPDie = *CI->first;
1463 DIDescriptor D(CI->second);
1466 DIE *NDie = getDIE(D);
1469 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1473 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1474 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1475 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1476 StringRef Name = DT.getName();
1478 addString(MemberDie, dwarf::DW_AT_name, Name);
1480 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1482 addSourceLine(MemberDie, DT);
1484 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1486 // For C++, virtual base classes are not at fixed offset. Use following
1487 // expression to extract appropriate offset from vtable.
1488 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1490 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1491 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1492 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1493 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1494 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1495 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1496 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1497 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1499 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1501 uint64_t Size = DT.getSizeInBits();
1502 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1503 uint64_t OffsetInBytes;
1505 if (FieldSize && Size != FieldSize) {
1506 // Handle bitfield, assume bytes are 8 bits.
1507 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1508 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1510 uint64_t Offset = DT.getOffsetInBits();
1511 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1512 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1513 uint64_t FieldOffset = (HiMark - FieldSize);
1514 Offset -= FieldOffset;
1516 // Maybe we need to work from the other end.
1517 if (Asm->getDataLayout().isLittleEndian())
1518 Offset = FieldSize - (Offset + Size);
1519 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1521 // Here DW_AT_data_member_location points to the anonymous
1522 // field that includes this bit field.
1523 OffsetInBytes = FieldOffset >> 3;
1525 // This is not a bitfield.
1526 OffsetInBytes = DT.getOffsetInBits() >> 3;
1528 if (DD->getDwarfVersion() <= 2) {
1529 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1530 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1531 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1532 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1534 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1538 if (DT.isProtected())
1539 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1540 dwarf::DW_ACCESS_protected);
1541 else if (DT.isPrivate())
1542 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1543 dwarf::DW_ACCESS_private);
1544 // Otherwise C++ member and base classes are considered public.
1545 else if (DT.isPublic())
1546 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1547 dwarf::DW_ACCESS_public);
1549 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1550 dwarf::DW_VIRTUALITY_virtual);
1552 // Objective-C properties.
1553 if (MDNode *PNode = DT.getObjCProperty())
1554 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1555 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1558 if (DT.isArtificial())
1559 addFlag(MemberDie, dwarf::DW_AT_artificial);
1562 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1563 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1567 // Construct the context before querying for the existence of the DIE in case
1568 // such construction creates the DIE.
1569 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1570 assert(dwarf::isType(ContextDIE->getTag()) &&
1571 "Static member should belong to a type.");
1573 if (DIE *StaticMemberDIE = getDIE(DT))
1574 return StaticMemberDIE;
1576 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1578 DIType Ty = resolve(DT.getTypeDerivedFrom());
1580 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1581 addType(StaticMemberDIE, Ty);
1582 addSourceLine(StaticMemberDIE, DT);
1583 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1584 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1586 // FIXME: We could omit private if the parent is a class_type, and
1587 // public if the parent is something else.
1588 if (DT.isProtected())
1589 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1590 dwarf::DW_ACCESS_protected);
1591 else if (DT.isPrivate())
1592 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1593 dwarf::DW_ACCESS_private);
1594 else if (DT.isPublic())
1595 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1596 dwarf::DW_ACCESS_public);
1598 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1599 addConstantValue(StaticMemberDIE, CI, Ty);
1600 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1601 addConstantFPValue(StaticMemberDIE, CFP);
1603 return &StaticMemberDIE;
1606 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
1607 // Emit size of content not including length itself
1608 Asm->OutStreamer.AddComment("Length of Unit");
1609 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1611 Asm->OutStreamer.AddComment("DWARF version number");
1612 Asm->EmitInt16(DD->getDwarfVersion());
1613 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1614 // We share one abbreviations table across all units so it's always at the
1615 // start of the section. Use a relocatable offset where needed to ensure
1616 // linking doesn't invalidate that offset.
1618 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1620 // Use a constant value when no symbol is provided.
1622 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1623 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1626 void DwarfUnit::initSection(const MCSection *Section) {
1627 assert(!this->Section);
1628 this->Section = Section;
1631 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
1632 DwarfUnit::emitHeader(ASectionSym);
1633 Asm->OutStreamer.AddComment("Type Signature");
1634 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1635 Asm->OutStreamer.AddComment("Type DIE Offset");
1636 // In a skeleton type unit there is no type DIE so emit a zero offset.
1637 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1638 sizeof(Ty->getOffset()));
1641 bool DwarfTypeUnit::isDwoUnit() const {
1642 // Since there are no skeleton type units, all type units are dwo type units
1643 // when split DWARF is being used.
1644 return DD->useSplitDwarf();