1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfUnit.h"
16 #include "DwarfAccelTable.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfDebug.h"
19 #include "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 /// Unit - Unit constructor.
47 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
48 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
49 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
50 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
51 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
52 UnitTag == dwarf::DW_TAG_type_unit);
53 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
56 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
57 DwarfDebug *DW, DwarfFile *DWU,
58 MCDwarfDwoLineTable *SplitLineTable)
59 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
60 CU(CU), SplitLineTable(SplitLineTable) {
62 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
65 /// ~Unit - Destructor for compile unit.
66 DwarfUnit::~DwarfUnit() {
67 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
68 DIEBlocks[j]->~DIEBlock();
69 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
70 DIELocs[j]->~DIELoc();
73 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
74 /// information entry.
75 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
76 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
80 /// getDefaultLowerBound - Return the default lower bound for an array. If the
81 /// DWARF version doesn't handle the language, return -1.
82 int64_t DwarfUnit::getDefaultLowerBound() const {
83 switch (getLanguage()) {
87 case dwarf::DW_LANG_C89:
88 case dwarf::DW_LANG_C99:
89 case dwarf::DW_LANG_C:
90 case dwarf::DW_LANG_C_plus_plus:
91 case dwarf::DW_LANG_ObjC:
92 case dwarf::DW_LANG_ObjC_plus_plus:
95 case dwarf::DW_LANG_Fortran77:
96 case dwarf::DW_LANG_Fortran90:
97 case dwarf::DW_LANG_Fortran95:
100 // The languages below have valid values only if the DWARF version >= 4.
101 case dwarf::DW_LANG_Java:
102 case dwarf::DW_LANG_Python:
103 case dwarf::DW_LANG_UPC:
104 case dwarf::DW_LANG_D:
105 if (dwarf::DWARF_VERSION >= 4)
109 case dwarf::DW_LANG_Ada83:
110 case dwarf::DW_LANG_Ada95:
111 case dwarf::DW_LANG_Cobol74:
112 case dwarf::DW_LANG_Cobol85:
113 case dwarf::DW_LANG_Modula2:
114 case dwarf::DW_LANG_Pascal83:
115 case dwarf::DW_LANG_PLI:
116 if (dwarf::DWARF_VERSION >= 4)
124 /// Check whether the DIE for this MDNode can be shared across CUs.
125 static bool isShareableAcrossCUs(DIDescriptor D) {
126 // When the MDNode can be part of the type system, the DIE can be shared
128 // Combining type units and cross-CU DIE sharing is lower value (since
129 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
130 // level already) but may be implementable for some value in projects
131 // building multiple independent libraries with LTO and then linking those
133 return (D.isType() ||
134 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
135 !GenerateDwarfTypeUnits;
138 /// getDIE - Returns the debug information entry map slot for the
139 /// specified debug variable. We delegate the request to DwarfDebug
140 /// when the DIE for this MDNode can be shared across CUs. The mappings
141 /// will be kept in DwarfDebug for shareable DIEs.
142 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
143 if (isShareableAcrossCUs(D))
144 return DD->getDIE(D);
145 return MDNodeToDieMap.lookup(D);
148 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
149 /// when the DIE for this MDNode can be shared across CUs. The mappings
150 /// will be kept in DwarfDebug for shareable DIEs.
151 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
152 if (isShareableAcrossCUs(Desc)) {
153 DD->insertDIE(Desc, D);
156 MDNodeToDieMap.insert(std::make_pair(Desc, D));
159 /// addFlag - Add a flag that is true.
160 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
161 if (DD->getDwarfVersion() >= 4)
162 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
164 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
167 /// addUInt - Add an unsigned integer attribute data and value.
169 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
170 Optional<dwarf::Form> Form, uint64_t Integer) {
172 Form = DIEInteger::BestForm(false, Integer);
173 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
175 Die.addValue(Attribute, *Form, Value);
178 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
179 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
182 /// addSInt - Add an signed integer attribute data and value.
184 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
185 Optional<dwarf::Form> Form, int64_t Integer) {
187 Form = DIEInteger::BestForm(true, Integer);
188 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
189 Die.addValue(Attribute, *Form, Value);
192 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
194 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
197 /// addString - Add a string attribute data and value. We always emit a
198 /// reference to the string pool instead of immediate strings so that DIEs have
199 /// more predictable sizes. In the case of split dwarf we emit an index
200 /// into another table which gets us the static offset into the string
202 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
205 if (!DD->useSplitDwarf())
206 return addLocalString(Die, Attribute, String);
208 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
209 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
210 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
211 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
214 /// addLocalString - Add a string attribute data and value. This is guaranteed
215 /// to be in the local string pool instead of indirected.
216 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
218 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
220 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
221 Value = new (DIEValueAllocator) DIELabel(Symb);
223 Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
224 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
225 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
228 /// addExpr - Add a Dwarf expression attribute data and value.
230 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
231 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
232 Die.addValue((dwarf::Attribute)0, Form, Value);
235 /// addLabel - Add a Dwarf label attribute data and value.
237 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
238 const MCSymbol *Label) {
239 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
240 Die.addValue(Attribute, Form, Value);
243 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
244 addLabel(Die, (dwarf::Attribute)0, Form, Label);
247 /// addSectionOffset - Add an offset into a section attribute data and value.
249 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
251 if (DD->getDwarfVersion() >= 4)
252 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
254 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
257 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
258 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
259 : getCU().getOrCreateSourceID(FileName, DirName);
262 /// addOpAddress - Add a dwarf op address data and value using the
263 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
265 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
266 if (!DD->useSplitDwarf()) {
267 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
268 addLabel(Die, dwarf::DW_FORM_udata, Sym);
270 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
271 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
272 DD->getAddressPool().getIndex(Sym));
276 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
277 const MCSymbol *Hi, const MCSymbol *Lo) {
278 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
279 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
282 /// addDIEEntry - Add a DIE attribute data and value.
284 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
285 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
288 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
289 // Flag the type unit reference as a declaration so that if it contains
290 // members (implicit special members, static data member definitions, member
291 // declarations for definitions in this CU, etc) consumers don't get confused
292 // and think this is a full definition.
293 addFlag(Die, dwarf::DW_AT_declaration);
295 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
296 new (DIEValueAllocator) DIETypeSignature(Type));
299 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
301 const DIE *DieCU = Die.getUnitOrNull();
302 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
304 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
305 DieCU = &getUnitDie();
307 EntryCU = &getUnitDie();
308 Die.addValue(Attribute,
309 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
313 /// Create a DIE with the given Tag, add the DIE to its parent, and
314 /// call insertDIE if MD is not null.
315 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
316 assert(Tag != dwarf::DW_TAG_auto_variable &&
317 Tag != dwarf::DW_TAG_arg_variable);
318 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
319 DIE &Die = *Parent.getChildren().back();
325 /// addBlock - Add block data.
327 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
328 Loc->ComputeSize(Asm);
329 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
330 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
333 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
335 Block->ComputeSize(Asm);
336 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
337 Die.addValue(Attribute, Block->BestForm(), Block);
340 /// addSourceLine - Add location information to specified debug information
342 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
343 StringRef Directory) {
347 unsigned FileID = getOrCreateSourceID(File, Directory);
348 assert(FileID && "Invalid file id");
349 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
350 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
353 /// addSourceLine - Add location information to specified debug information
355 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
356 assert(V.isVariable());
358 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
359 V.getContext().getDirectory());
362 /// addSourceLine - Add location information to specified debug information
364 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
365 assert(G.isGlobalVariable());
367 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
370 /// addSourceLine - Add location information to specified debug information
372 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
373 assert(SP.isSubprogram());
375 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
378 /// addSourceLine - Add location information to specified debug information
380 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
383 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
386 /// addSourceLine - Add location information to specified debug information
388 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
389 assert(Ty.isObjCProperty());
391 DIFile File = Ty.getFile();
392 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
393 File.getDirectory());
396 /// addSourceLine - Add location information to specified debug information
398 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
401 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
404 /// addRegisterOp - Add register operand.
405 // FIXME: Ideally, this would share the implementation with
406 // AsmPrinter::EmitDwarfRegOpPiece.
407 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
408 unsigned SizeInBits, unsigned OffsetInBits) {
409 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
410 int DWReg = RI->getDwarfRegNum(Reg, false);
411 bool isSubRegister = DWReg < 0;
415 // Go up the super-register chain until we hit a valid dwarf register number.
416 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
417 DWReg = RI->getDwarfRegNum(*SR, false);
419 Idx = RI->getSubRegIndex(*SR, Reg);
423 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
424 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
430 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
432 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
433 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
437 bool isPiece = SizeInBits > 0;
438 if (isSubRegister || isPiece) {
439 const unsigned SizeOfByte = 8;
440 unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
441 unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
442 unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
443 unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
444 assert(RegSizeInBits >= SizeInBits && "register smaller than value");
446 if (RegOffsetInBits != PieceOffsetInBits) {
447 // Manually shift the value into place, since the DW_OP_piece
448 // describes the part of the variable, not the position of the
450 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
451 addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
452 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
455 if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
456 assert(PieceSizeInBits > 0 && "piece has zero size");
457 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
458 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
459 addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
461 assert(PieceSizeInBits > 0 && "piece has zero size");
462 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
463 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
468 /// addRegisterOffset - Add register offset.
469 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
471 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
472 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
473 const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
474 if (Reg == TRI->getFrameRegister(*Asm->MF))
475 // If variable offset is based in frame register then use fbreg.
476 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
478 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
480 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
481 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
483 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
486 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
487 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
488 gives the variable VarName either the struct, or a pointer to the struct, as
489 its type. This is necessary for various behind-the-scenes things the
490 compiler needs to do with by-reference variables in Blocks.
492 However, as far as the original *programmer* is concerned, the variable
493 should still have type 'SomeType', as originally declared.
495 The function getBlockByrefType dives into the __Block_byref_x_VarName
496 struct to find the original type of the variable, which is then assigned to
497 the variable's Debug Information Entry as its real type. So far, so good.
498 However now the debugger will expect the variable VarName to have the type
499 SomeType. So we need the location attribute for the variable to be an
500 expression that explains to the debugger how to navigate through the
501 pointers and struct to find the actual variable of type SomeType.
503 The following function does just that. We start by getting
504 the "normal" location for the variable. This will be the location
505 of either the struct __Block_byref_x_VarName or the pointer to the
506 struct __Block_byref_x_VarName.
508 The struct will look something like:
510 struct __Block_byref_x_VarName {
512 struct __Block_byref_x_VarName *forwarding;
513 ... <various other fields>
515 ... <maybe more fields>
518 If we are given the struct directly (as our starting point) we
519 need to tell the debugger to:
521 1). Add the offset of the forwarding field.
523 2). Follow that pointer to get the real __Block_byref_x_VarName
524 struct to use (the real one may have been copied onto the heap).
526 3). Add the offset for the field VarName, to find the actual variable.
528 If we started with a pointer to the struct, then we need to
529 dereference that pointer first, before the other steps.
530 Translating this into DWARF ops, we will need to append the following
531 to the current location description for the variable:
533 DW_OP_deref -- optional, if we start with a pointer
534 DW_OP_plus_uconst <forward_fld_offset>
536 DW_OP_plus_uconst <varName_fld_offset>
538 That is what this function does. */
540 /// addBlockByrefAddress - Start with the address based on the location
541 /// provided, and generate the DWARF information necessary to find the
542 /// actual Block variable (navigating the Block struct) based on the
543 /// starting location. Add the DWARF information to the die. For
544 /// more information, read large comment just above here.
546 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
547 dwarf::Attribute Attribute,
548 const MachineLocation &Location) {
549 DIType Ty = DV.getType();
551 uint16_t Tag = Ty.getTag();
552 bool isPointer = false;
554 StringRef varName = DV.getName();
556 if (Tag == dwarf::DW_TAG_pointer_type) {
557 DIDerivedType DTy(Ty);
558 TmpTy = resolve(DTy.getTypeDerivedFrom());
562 DICompositeType blockStruct(TmpTy);
564 // Find the __forwarding field and the variable field in the __Block_byref
566 DIArray Fields = blockStruct.getElements();
567 DIDerivedType varField;
568 DIDerivedType forwardingField;
570 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
571 DIDerivedType DT(Fields.getElement(i));
572 StringRef fieldName = DT.getName();
573 if (fieldName == "__forwarding")
574 forwardingField = DT;
575 else if (fieldName == varName)
579 // Get the offsets for the forwarding field and the variable field.
580 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
581 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
583 // Decode the original location, and use that as the start of the byref
584 // variable's location.
585 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
587 if (Location.isReg())
588 addRegisterOpPiece(*Loc, Location.getReg());
590 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
592 // If we started with a pointer to the __Block_byref... struct, then
593 // the first thing we need to do is dereference the pointer (DW_OP_deref).
595 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
597 // Next add the offset for the '__forwarding' field:
598 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
599 // adding the offset if it's 0.
600 if (forwardingFieldOffset > 0) {
601 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
602 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
605 // Now dereference the __forwarding field to get to the real __Block_byref
606 // struct: DW_OP_deref.
607 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
609 // Now that we've got the real __Block_byref... struct, add the offset
610 // for the variable's field to get to the location of the actual variable:
611 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
612 if (varFieldOffset > 0) {
613 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
614 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
617 // Now attach the location information to the DIE.
618 addBlock(Die, Attribute, Loc);
621 /// Return true if type encoding is unsigned.
622 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
623 DIDerivedType DTy(Ty);
624 if (DTy.isDerivedType()) {
625 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
626 // Encode pointer constants as unsigned bytes. This is used at least for
627 // null pointer constant emission.
628 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
629 // here, but accept them for now due to a bug in SROA producing bogus
631 if (T == dwarf::DW_TAG_pointer_type ||
632 T == dwarf::DW_TAG_ptr_to_member_type ||
633 T == dwarf::DW_TAG_reference_type ||
634 T == dwarf::DW_TAG_rvalue_reference_type)
636 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
637 T == dwarf::DW_TAG_volatile_type ||
638 T == dwarf::DW_TAG_restrict_type ||
639 T == dwarf::DW_TAG_enumeration_type);
640 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
641 return isUnsignedDIType(DD, DD->resolve(Deriv));
642 // FIXME: Enums without a fixed underlying type have unknown signedness
643 // here, leading to incorrectly emitted constants.
644 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
649 assert(BTy.isBasicType());
650 unsigned Encoding = BTy.getEncoding();
651 assert((Encoding == dwarf::DW_ATE_unsigned ||
652 Encoding == dwarf::DW_ATE_unsigned_char ||
653 Encoding == dwarf::DW_ATE_signed ||
654 Encoding == dwarf::DW_ATE_signed_char ||
655 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
656 "Unsupported encoding");
657 return (Encoding == dwarf::DW_ATE_unsigned ||
658 Encoding == dwarf::DW_ATE_unsigned_char ||
659 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
662 /// If this type is derived from a base type then return base type size.
663 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
664 unsigned Tag = Ty.getTag();
666 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
667 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
668 Tag != dwarf::DW_TAG_restrict_type)
669 return Ty.getSizeInBits();
671 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
673 // If this type is not derived from any type or the type is a declaration then
674 // take conservative approach.
675 if (!BaseType.isValid() || BaseType.isForwardDecl())
676 return Ty.getSizeInBits();
678 // If this is a derived type, go ahead and get the base type, unless it's a
679 // reference then it's just the size of the field. Pointer types have no need
680 // of this since they're a different type of qualification on the type.
681 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
682 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
683 return Ty.getSizeInBits();
685 if (BaseType.isDerivedType())
686 return getBaseTypeSize(DD, DIDerivedType(BaseType));
688 return BaseType.getSizeInBits();
691 /// addConstantFPValue - Add constant value entry in variable DIE.
692 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
693 assert(MO.isFPImm() && "Invalid machine operand!");
694 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
695 APFloat FPImm = MO.getFPImm()->getValueAPF();
697 // Get the raw data form of the floating point.
698 const APInt FltVal = FPImm.bitcastToAPInt();
699 const char *FltPtr = (const char *)FltVal.getRawData();
701 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
702 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
703 int Incr = (LittleEndian ? 1 : -1);
704 int Start = (LittleEndian ? 0 : NumBytes - 1);
705 int Stop = (LittleEndian ? NumBytes : -1);
707 // Output the constant to DWARF one byte at a time.
708 for (; Start != Stop; Start += Incr)
709 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
711 addBlock(Die, dwarf::DW_AT_const_value, Block);
714 /// addConstantFPValue - Add constant value entry in variable DIE.
715 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
716 // Pass this down to addConstantValue as an unsigned bag of bits.
717 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
720 /// addConstantValue - Add constant value entry in variable DIE.
721 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
722 addConstantValue(Die, CI->getValue(), Ty);
725 /// addConstantValue - Add constant value entry in variable DIE.
726 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
728 assert(MO.isImm() && "Invalid machine operand!");
730 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
733 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
734 // FIXME: This is a bit conservative/simple - it emits negative values always
735 // sign extended to 64 bits rather than minimizing the number of bytes.
736 addUInt(Die, dwarf::DW_AT_const_value,
737 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
740 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
741 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
744 // addConstantValue - Add constant value entry in variable DIE.
745 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
746 unsigned CIBitWidth = Val.getBitWidth();
747 if (CIBitWidth <= 64) {
748 addConstantValue(Die, Unsigned,
749 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
753 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
755 // Get the raw data form of the large APInt.
756 const uint64_t *Ptr64 = Val.getRawData();
758 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
759 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
761 // Output the constant to DWARF one byte at a time.
762 for (int i = 0; i < NumBytes; i++) {
765 c = Ptr64[i / 8] >> (8 * (i & 7));
767 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
768 addUInt(*Block, dwarf::DW_FORM_data1, c);
771 addBlock(Die, dwarf::DW_AT_const_value, Block);
774 /// addTemplateParams - Add template parameters into buffer.
775 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
776 // Add template parameters.
777 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
778 DIDescriptor Element = TParams.getElement(i);
779 if (Element.isTemplateTypeParameter())
780 constructTemplateTypeParameterDIE(Buffer,
781 DITemplateTypeParameter(Element));
782 else if (Element.isTemplateValueParameter())
783 constructTemplateValueParameterDIE(Buffer,
784 DITemplateValueParameter(Element));
788 /// getOrCreateContextDIE - Get context owner's DIE.
789 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
790 if (!Context || Context.isFile())
791 return &getUnitDie();
792 if (Context.isType())
793 return getOrCreateTypeDIE(DIType(Context));
794 if (Context.isNameSpace())
795 return getOrCreateNameSpace(DINameSpace(Context));
796 if (Context.isSubprogram())
797 return getOrCreateSubprogramDIE(DISubprogram(Context));
798 return getDIE(Context);
801 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
802 DIScope Context = resolve(Ty.getContext());
803 DIE *ContextDIE = getOrCreateContextDIE(Context);
805 if (DIE *TyDIE = getDIE(Ty))
809 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
811 constructTypeDIE(TyDIE, Ty);
813 updateAcceleratorTables(Context, Ty, TyDIE);
817 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
819 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
825 assert(Ty == resolve(Ty.getRef()) &&
826 "type was not uniqued, possible ODR violation.");
828 // DW_TAG_restrict_type is not supported in DWARF2
829 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
830 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
832 // Construct the context before querying for the existence of the DIE in case
833 // such construction creates the DIE.
834 DIScope Context = resolve(Ty.getContext());
835 DIE *ContextDIE = getOrCreateContextDIE(Context);
838 if (DIE *TyDIE = getDIE(Ty))
842 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
844 updateAcceleratorTables(Context, Ty, TyDIE);
846 if (Ty.isBasicType())
847 constructTypeDIE(TyDIE, DIBasicType(Ty));
848 else if (Ty.isCompositeType()) {
849 DICompositeType CTy(Ty);
850 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
851 if (MDString *TypeId = CTy.getIdentifier()) {
852 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
853 // Skip updating the accelerator tables since this is not the full type.
856 constructTypeDIE(TyDIE, CTy);
858 assert(Ty.isDerivedType() && "Unknown kind of DIType");
859 constructTypeDIE(TyDIE, DIDerivedType(Ty));
865 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
867 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
868 bool IsImplementation = 0;
869 if (Ty.isCompositeType()) {
870 DICompositeType CT(Ty);
871 // A runtime language of 0 actually means C/C++ and that any
872 // non-negative value is some version of Objective-C/C++.
873 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
875 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
876 DD->addAccelType(Ty.getName(), TyDIE, Flags);
878 if (!Context || Context.isCompileUnit() || Context.isFile() ||
879 Context.isNameSpace())
880 addGlobalType(Ty, TyDIE, Context);
884 /// addType - Add a new type attribute to the specified entity.
885 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
886 assert(Ty && "Trying to add a type that doesn't exist?");
888 // Check for pre-existence.
889 DIEEntry *Entry = getDIEEntry(Ty);
890 // If it exists then use the existing value.
892 addDIEEntry(Entity, Attribute, Entry);
897 DIE *Buffer = getOrCreateTypeDIE(Ty);
900 Entry = createDIEEntry(*Buffer);
901 insertDIEEntry(Ty, Entry);
902 addDIEEntry(Entity, Attribute, Entry);
905 /// getParentContextString - Walks the metadata parent chain in a language
906 /// specific manner (using the compile unit language) and returns
907 /// it as a string. This is done at the metadata level because DIEs may
908 /// not currently have been added to the parent context and walking the
909 /// DIEs looking for names is more expensive than walking the metadata.
910 std::string DwarfUnit::getParentContextString(DIScope Context) const {
914 // FIXME: Decide whether to implement this for non-C++ languages.
915 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
919 SmallVector<DIScope, 1> Parents;
920 while (!Context.isCompileUnit()) {
921 Parents.push_back(Context);
922 if (Context.getContext())
923 Context = resolve(Context.getContext());
925 // Structure, etc types will have a NULL context if they're at the top
930 // Reverse iterate over our list to go from the outermost construct to the
932 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
936 StringRef Name = Ctx.getName();
937 if (Name.empty() && Ctx.isNameSpace())
938 Name = "(anonymous namespace)";
947 /// constructTypeDIE - Construct basic type die from DIBasicType.
948 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
949 // Get core information.
950 StringRef Name = BTy.getName();
951 // Add name if not anonymous or intermediate type.
953 addString(Buffer, dwarf::DW_AT_name, Name);
955 // An unspecified type only has a name attribute.
956 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
959 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
962 uint64_t Size = BTy.getSizeInBits() >> 3;
963 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
966 /// constructTypeDIE - Construct derived type die from DIDerivedType.
967 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
968 // Get core information.
969 StringRef Name = DTy.getName();
970 uint64_t Size = DTy.getSizeInBits() >> 3;
971 uint16_t Tag = Buffer.getTag();
973 // Map to main type, void will not have a type.
974 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
976 addType(Buffer, FromTy);
978 // Add name if not anonymous or intermediate type.
980 addString(Buffer, dwarf::DW_AT_name, Name);
982 // Add size if non-zero (derived types might be zero-sized.)
983 if (Size && Tag != dwarf::DW_TAG_pointer_type)
984 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
986 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
987 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
988 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
989 // Add source line info if available and TyDesc is not a forward declaration.
990 if (!DTy.isForwardDecl())
991 addSourceLine(Buffer, DTy);
994 /// constructSubprogramArguments - Construct function argument DIEs.
995 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
996 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
997 DIType Ty = resolve(Args.getElement(i));
999 assert(i == N-1 && "Unspecified parameter must be the last argument");
1000 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1002 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1004 if (Ty.isArtificial())
1005 addFlag(Arg, dwarf::DW_AT_artificial);
1010 /// constructTypeDIE - Construct type DIE from DICompositeType.
1011 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1012 // Add name if not anonymous or intermediate type.
1013 StringRef Name = CTy.getName();
1015 uint64_t Size = CTy.getSizeInBits() >> 3;
1016 uint16_t Tag = Buffer.getTag();
1019 case dwarf::DW_TAG_array_type:
1020 constructArrayTypeDIE(Buffer, CTy);
1022 case dwarf::DW_TAG_enumeration_type:
1023 constructEnumTypeDIE(Buffer, CTy);
1025 case dwarf::DW_TAG_subroutine_type: {
1026 // Add return type. A void return won't have a type.
1027 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1028 DIType RTy(resolve(Elements.getElement(0)));
1030 addType(Buffer, RTy);
1032 bool isPrototyped = true;
1033 if (Elements.getNumElements() == 2 &&
1034 !Elements.getElement(1))
1035 isPrototyped = false;
1037 constructSubprogramArguments(Buffer, Elements);
1039 // Add prototype flag if we're dealing with a C language and the
1040 // function has been prototyped.
1041 uint16_t Language = getLanguage();
1043 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1044 Language == dwarf::DW_LANG_ObjC))
1045 addFlag(Buffer, dwarf::DW_AT_prototyped);
1047 if (CTy.isLValueReference())
1048 addFlag(Buffer, dwarf::DW_AT_reference);
1050 if (CTy.isRValueReference())
1051 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1053 case dwarf::DW_TAG_structure_type:
1054 case dwarf::DW_TAG_union_type:
1055 case dwarf::DW_TAG_class_type: {
1056 // Add elements to structure type.
1057 DIArray Elements = CTy.getElements();
1058 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1059 DIDescriptor Element = Elements.getElement(i);
1060 if (Element.isSubprogram())
1061 getOrCreateSubprogramDIE(DISubprogram(Element));
1062 else if (Element.isDerivedType()) {
1063 DIDerivedType DDTy(Element);
1064 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1065 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1066 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1067 dwarf::DW_AT_friend);
1068 } else if (DDTy.isStaticMember()) {
1069 getOrCreateStaticMemberDIE(DDTy);
1071 constructMemberDIE(Buffer, DDTy);
1073 } else if (Element.isObjCProperty()) {
1074 DIObjCProperty Property(Element);
1075 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1076 StringRef PropertyName = Property.getObjCPropertyName();
1077 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1078 if (Property.getType())
1079 addType(ElemDie, Property.getType());
1080 addSourceLine(ElemDie, Property);
1081 StringRef GetterName = Property.getObjCPropertyGetterName();
1082 if (!GetterName.empty())
1083 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1084 StringRef SetterName = Property.getObjCPropertySetterName();
1085 if (!SetterName.empty())
1086 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1087 unsigned PropertyAttributes = 0;
1088 if (Property.isReadOnlyObjCProperty())
1089 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1090 if (Property.isReadWriteObjCProperty())
1091 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1092 if (Property.isAssignObjCProperty())
1093 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1094 if (Property.isRetainObjCProperty())
1095 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1096 if (Property.isCopyObjCProperty())
1097 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1098 if (Property.isNonAtomicObjCProperty())
1099 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1100 if (PropertyAttributes)
1101 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1102 PropertyAttributes);
1104 DIEEntry *Entry = getDIEEntry(Element);
1106 Entry = createDIEEntry(ElemDie);
1107 insertDIEEntry(Element, Entry);
1113 if (CTy.isAppleBlockExtension())
1114 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1116 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1118 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1119 *getOrCreateTypeDIE(ContainingType));
1121 if (CTy.isObjcClassComplete())
1122 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1124 // Add template parameters to a class, structure or union types.
1125 // FIXME: The support isn't in the metadata for this yet.
1126 if (Tag == dwarf::DW_TAG_class_type ||
1127 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1128 addTemplateParams(Buffer, CTy.getTemplateParams());
1136 // Add name if not anonymous or intermediate type.
1138 addString(Buffer, dwarf::DW_AT_name, Name);
1140 if (Tag == dwarf::DW_TAG_enumeration_type ||
1141 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1142 Tag == dwarf::DW_TAG_union_type) {
1143 // Add size if non-zero (derived types might be zero-sized.)
1144 // TODO: Do we care about size for enum forward declarations?
1146 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1147 else if (!CTy.isForwardDecl())
1148 // Add zero size if it is not a forward declaration.
1149 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1151 // If we're a forward decl, say so.
1152 if (CTy.isForwardDecl())
1153 addFlag(Buffer, dwarf::DW_AT_declaration);
1155 // Add source line info if available.
1156 if (!CTy.isForwardDecl())
1157 addSourceLine(Buffer, CTy);
1159 // No harm in adding the runtime language to the declaration.
1160 unsigned RLang = CTy.getRunTimeLang();
1162 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1167 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1168 /// DITemplateTypeParameter.
1169 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1170 DITemplateTypeParameter TP) {
1172 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1173 // Add the type if it exists, it could be void and therefore no type.
1175 addType(ParamDIE, resolve(TP.getType()));
1176 if (!TP.getName().empty())
1177 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1180 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1181 /// DITemplateValueParameter.
1183 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1184 DITemplateValueParameter VP) {
1185 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1187 // Add the type if there is one, template template and template parameter
1188 // packs will not have a type.
1189 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1190 addType(ParamDIE, resolve(VP.getType()));
1191 if (!VP.getName().empty())
1192 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1193 if (Value *Val = VP.getValue()) {
1194 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1195 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1196 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1197 // For declaration non-type template parameters (such as global values and
1199 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1200 addOpAddress(*Loc, Asm->getSymbol(GV));
1201 // Emit DW_OP_stack_value to use the address as the immediate value of the
1202 // parameter, rather than a pointer to it.
1203 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1204 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1205 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1206 assert(isa<MDString>(Val));
1207 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1208 cast<MDString>(Val)->getString());
1209 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1210 assert(isa<MDNode>(Val));
1211 DIArray A(cast<MDNode>(Val));
1212 addTemplateParams(ParamDIE, A);
1217 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1218 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1219 // Construct the context before querying for the existence of the DIE in case
1220 // such construction creates the DIE.
1221 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1223 if (DIE *NDie = getDIE(NS))
1225 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1227 StringRef Name = NS.getName();
1229 addString(NDie, dwarf::DW_AT_name, NS.getName());
1231 Name = "(anonymous namespace)";
1232 DD->addAccelNamespace(Name, NDie);
1233 addGlobalName(Name, NDie, NS.getContext());
1234 addSourceLine(NDie, NS);
1238 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1239 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1240 // Construct the context before querying for the existence of the DIE in case
1241 // such construction creates the DIE (as is the case for member function
1243 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1245 if (DIE *SPDie = getDIE(SP))
1248 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1249 // Add subprogram definitions to the CU die directly.
1250 ContextDIE = &getUnitDie();
1251 // Build the decl now to ensure it precedes the definition.
1252 getOrCreateSubprogramDIE(SPDecl);
1255 // DW_TAG_inlined_subroutine may refer to this DIE.
1256 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1258 // Stop here and fill this in later, depending on whether or not this
1259 // subprogram turns out to have inlined instances or not.
1260 if (SP.isDefinition())
1263 applySubprogramAttributes(SP, SPDie);
1267 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1268 DISubprogram SPDecl = SP.getFunctionDeclaration();
1269 DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1270 applySubprogramAttributes(SP, SPDie);
1271 addGlobalName(SP.getName(), SPDie, Context);
1274 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1275 DIE *DeclDie = nullptr;
1276 StringRef DeclLinkageName;
1277 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1278 DeclDie = getDIE(SPDecl);
1279 assert(DeclDie && "This DIE should've already been constructed when the "
1280 "definition DIE was created in "
1281 "getOrCreateSubprogramDIE");
1282 DeclLinkageName = SPDecl.getLinkageName();
1285 // Add function template parameters.
1286 addTemplateParams(SPDie, SP.getTemplateParams());
1288 // Add the linkage name if we have one and it isn't in the Decl.
1289 StringRef LinkageName = SP.getLinkageName();
1290 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1291 LinkageName == DeclLinkageName) &&
1292 "decl has a linkage name and it is different");
1293 if (!LinkageName.empty() && DeclLinkageName.empty())
1294 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1295 GlobalValue::getRealLinkageName(LinkageName));
1298 // Refer to the function declaration where all the other attributes will be
1300 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1304 // Constructors and operators for anonymous aggregates do not have names.
1305 if (!SP.getName().empty())
1306 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1308 // Skip the rest of the attributes under -gmlt to save space.
1309 if(getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1312 addSourceLine(SPDie, SP);
1314 // Add the prototype if we have a prototype and we have a C like
1316 uint16_t Language = getLanguage();
1317 if (SP.isPrototyped() &&
1318 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1319 Language == dwarf::DW_LANG_ObjC))
1320 addFlag(SPDie, dwarf::DW_AT_prototyped);
1322 DISubroutineType SPTy = SP.getType();
1323 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1324 "the type of a subprogram should be a subroutine");
1326 DITypeArray Args = SPTy.getTypeArray();
1327 // Add a return type. If this is a type like a C/C++ void type we don't add a
1329 if (resolve(Args.getElement(0)))
1330 addType(SPDie, DIType(resolve(Args.getElement(0))));
1332 unsigned VK = SP.getVirtuality();
1334 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1335 DIELoc *Block = getDIELoc();
1336 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1337 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1338 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1339 ContainingTypeMap.insert(
1340 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1343 if (!SP.isDefinition()) {
1344 addFlag(SPDie, dwarf::DW_AT_declaration);
1346 // Add arguments. Do not add arguments for subprogram definition. They will
1347 // be handled while processing variables.
1348 constructSubprogramArguments(SPDie, Args);
1351 if (SP.isArtificial())
1352 addFlag(SPDie, dwarf::DW_AT_artificial);
1354 if (!SP.isLocalToUnit())
1355 addFlag(SPDie, dwarf::DW_AT_external);
1357 if (SP.isOptimized())
1358 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1360 if (unsigned isa = Asm->getISAEncoding()) {
1361 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1364 if (SP.isLValueReference())
1365 addFlag(SPDie, dwarf::DW_AT_reference);
1367 if (SP.isRValueReference())
1368 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1370 if (SP.isProtected())
1371 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1372 dwarf::DW_ACCESS_protected);
1373 else if (SP.isPrivate())
1374 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1375 dwarf::DW_ACCESS_private);
1376 else if (SP.isPublic())
1377 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1378 dwarf::DW_ACCESS_public);
1380 if (SP.isExplicit())
1381 addFlag(SPDie, dwarf::DW_AT_explicit);
1384 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1385 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1386 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1387 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1389 // The LowerBound value defines the lower bounds which is typically zero for
1390 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1391 // Count == -1 then the array is unbounded and we do not emit
1392 // DW_AT_lower_bound and DW_AT_count attributes.
1393 int64_t LowerBound = SR.getLo();
1394 int64_t DefaultLowerBound = getDefaultLowerBound();
1395 int64_t Count = SR.getCount();
1397 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1398 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1401 // FIXME: An unbounded array should reference the expression that defines
1403 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1406 DIE *DwarfUnit::getIndexTyDie() {
1409 // Construct an integer type to use for indexes.
1410 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1411 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1412 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1413 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1414 dwarf::DW_ATE_unsigned);
1418 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1419 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1421 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1423 // Emit the element type.
1424 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1426 // Get an anonymous type for index type.
1427 // FIXME: This type should be passed down from the front end
1428 // as different languages may have different sizes for indexes.
1429 DIE *IdxTy = getIndexTyDie();
1431 // Add subranges to array type.
1432 DIArray Elements = CTy.getElements();
1433 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1434 DIDescriptor Element = Elements.getElement(i);
1435 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1436 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1440 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1441 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1442 DIArray Elements = CTy.getElements();
1444 // Add enumerators to enumeration type.
1445 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1446 DIEnumerator Enum(Elements.getElement(i));
1447 if (Enum.isEnumerator()) {
1448 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1449 StringRef Name = Enum.getName();
1450 addString(Enumerator, dwarf::DW_AT_name, Name);
1451 int64_t Value = Enum.getEnumValue();
1452 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1456 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1458 addType(Buffer, DTy);
1459 addFlag(Buffer, dwarf::DW_AT_enum_class);
1463 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1465 void DwarfUnit::constructContainingTypeDIEs() {
1466 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1467 CE = ContainingTypeMap.end();
1469 DIE &SPDie = *CI->first;
1470 DIDescriptor D(CI->second);
1473 DIE *NDie = getDIE(D);
1476 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1480 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1481 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1482 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1483 StringRef Name = DT.getName();
1485 addString(MemberDie, dwarf::DW_AT_name, Name);
1487 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1489 addSourceLine(MemberDie, DT);
1491 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1493 // For C++, virtual base classes are not at fixed offset. Use following
1494 // expression to extract appropriate offset from vtable.
1495 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1497 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1498 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1499 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1500 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1501 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1502 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1503 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1504 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1506 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1508 uint64_t Size = DT.getSizeInBits();
1509 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1510 uint64_t OffsetInBytes;
1512 if (Size != FieldSize) {
1513 // Handle bitfield, assume bytes are 8 bits.
1514 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1515 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1517 uint64_t Offset = DT.getOffsetInBits();
1518 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1519 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1520 uint64_t FieldOffset = (HiMark - FieldSize);
1521 Offset -= FieldOffset;
1523 // Maybe we need to work from the other end.
1524 if (Asm->getDataLayout().isLittleEndian())
1525 Offset = FieldSize - (Offset + Size);
1526 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1528 // Here DW_AT_data_member_location points to the anonymous
1529 // field that includes this bit field.
1530 OffsetInBytes = FieldOffset >> 3;
1532 // This is not a bitfield.
1533 OffsetInBytes = DT.getOffsetInBits() >> 3;
1535 if (DD->getDwarfVersion() <= 2) {
1536 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1537 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1538 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1539 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1541 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1545 if (DT.isProtected())
1546 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1547 dwarf::DW_ACCESS_protected);
1548 else if (DT.isPrivate())
1549 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1550 dwarf::DW_ACCESS_private);
1551 // Otherwise C++ member and base classes are considered public.
1552 else if (DT.isPublic())
1553 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1554 dwarf::DW_ACCESS_public);
1556 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1557 dwarf::DW_VIRTUALITY_virtual);
1559 // Objective-C properties.
1560 if (MDNode *PNode = DT.getObjCProperty())
1561 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1562 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1565 if (DT.isArtificial())
1566 addFlag(MemberDie, dwarf::DW_AT_artificial);
1569 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1570 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1574 // Construct the context before querying for the existence of the DIE in case
1575 // such construction creates the DIE.
1576 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1577 assert(dwarf::isType(ContextDIE->getTag()) &&
1578 "Static member should belong to a type.");
1580 if (DIE *StaticMemberDIE = getDIE(DT))
1581 return StaticMemberDIE;
1583 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1585 DIType Ty = resolve(DT.getTypeDerivedFrom());
1587 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1588 addType(StaticMemberDIE, Ty);
1589 addSourceLine(StaticMemberDIE, DT);
1590 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1591 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1593 // FIXME: We could omit private if the parent is a class_type, and
1594 // public if the parent is something else.
1595 if (DT.isProtected())
1596 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1597 dwarf::DW_ACCESS_protected);
1598 else if (DT.isPrivate())
1599 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1600 dwarf::DW_ACCESS_private);
1601 else if (DT.isPublic())
1602 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1603 dwarf::DW_ACCESS_public);
1605 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1606 addConstantValue(StaticMemberDIE, CI, Ty);
1607 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1608 addConstantFPValue(StaticMemberDIE, CFP);
1610 return &StaticMemberDIE;
1613 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
1614 // Emit size of content not including length itself
1615 Asm->OutStreamer.AddComment("Length of Unit");
1616 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1618 Asm->OutStreamer.AddComment("DWARF version number");
1619 Asm->EmitInt16(DD->getDwarfVersion());
1620 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1621 // We share one abbreviations table across all units so it's always at the
1622 // start of the section. Use a relocatable offset where needed to ensure
1623 // linking doesn't invalidate that offset.
1625 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1627 // Use a constant value when no symbol is provided.
1629 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1630 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1633 void DwarfUnit::initSection(const MCSection *Section) {
1634 assert(!this->Section);
1635 this->Section = Section;
1638 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
1639 DwarfUnit::emitHeader(ASectionSym);
1640 Asm->OutStreamer.AddComment("Type Signature");
1641 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1642 Asm->OutStreamer.AddComment("Type DIE Offset");
1643 // In a skeleton type unit there is no type DIE so emit a zero offset.
1644 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1645 sizeof(Ty->getOffset()));