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),
52 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
53 UnitTag == dwarf::DW_TAG_type_unit);
54 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
57 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
58 DwarfDebug *DW, DwarfFile *DWU,
59 MCDwarfDwoLineTable *SplitLineTable)
60 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
61 CU(CU), SplitLineTable(SplitLineTable) {
63 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
66 /// ~Unit - Destructor for compile unit.
67 DwarfUnit::~DwarfUnit() {
68 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
69 DIEBlocks[j]->~DIEBlock();
70 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
71 DIELocs[j]->~DIELoc();
74 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
75 /// information entry.
76 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
77 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
81 /// getDefaultLowerBound - Return the default lower bound for an array. If the
82 /// DWARF version doesn't handle the language, return -1.
83 int64_t DwarfUnit::getDefaultLowerBound() const {
84 switch (getLanguage()) {
88 case dwarf::DW_LANG_C89:
89 case dwarf::DW_LANG_C99:
90 case dwarf::DW_LANG_C:
91 case dwarf::DW_LANG_C_plus_plus:
92 case dwarf::DW_LANG_ObjC:
93 case dwarf::DW_LANG_ObjC_plus_plus:
96 case dwarf::DW_LANG_Fortran77:
97 case dwarf::DW_LANG_Fortran90:
98 case dwarf::DW_LANG_Fortran95:
101 // The languages below have valid values only if the DWARF version >= 4.
102 case dwarf::DW_LANG_Java:
103 case dwarf::DW_LANG_Python:
104 case dwarf::DW_LANG_UPC:
105 case dwarf::DW_LANG_D:
106 if (dwarf::DWARF_VERSION >= 4)
110 case dwarf::DW_LANG_Ada83:
111 case dwarf::DW_LANG_Ada95:
112 case dwarf::DW_LANG_Cobol74:
113 case dwarf::DW_LANG_Cobol85:
114 case dwarf::DW_LANG_Modula2:
115 case dwarf::DW_LANG_Pascal83:
116 case dwarf::DW_LANG_PLI:
117 if (dwarf::DWARF_VERSION >= 4)
125 /// Check whether the DIE for this MDNode can be shared across CUs.
126 static bool isShareableAcrossCUs(DIDescriptor D) {
127 // When the MDNode can be part of the type system, the DIE can be shared
129 // Combining type units and cross-CU DIE sharing is lower value (since
130 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
131 // level already) but may be implementable for some value in projects
132 // building multiple independent libraries with LTO and then linking those
134 return (D.isType() ||
135 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
136 !GenerateDwarfTypeUnits;
139 /// getDIE - Returns the debug information entry map slot for the
140 /// specified debug variable. We delegate the request to DwarfDebug
141 /// when the DIE for this MDNode can be shared across CUs. The mappings
142 /// will be kept in DwarfDebug for shareable DIEs.
143 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
144 if (isShareableAcrossCUs(D))
145 return DD->getDIE(D);
146 return MDNodeToDieMap.lookup(D);
149 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
150 /// when the DIE for this MDNode can be shared across CUs. The mappings
151 /// will be kept in DwarfDebug for shareable DIEs.
152 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
153 if (isShareableAcrossCUs(Desc)) {
154 DD->insertDIE(Desc, D);
157 MDNodeToDieMap.insert(std::make_pair(Desc, D));
160 /// addFlag - Add a flag that is true.
161 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
162 if (DD->getDwarfVersion() >= 4)
163 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
165 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
168 /// addUInt - Add an unsigned integer attribute data and value.
170 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
171 Optional<dwarf::Form> Form, uint64_t Integer) {
173 Form = DIEInteger::BestForm(false, Integer);
174 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
176 Die.addValue(Attribute, *Form, Value);
179 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
180 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
183 /// addSInt - Add an signed integer attribute data and value.
185 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
186 Optional<dwarf::Form> Form, int64_t Integer) {
188 Form = DIEInteger::BestForm(true, Integer);
189 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
190 Die.addValue(Attribute, *Form, Value);
193 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
195 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
198 /// addString - Add a string attribute data and value. We always emit a
199 /// reference to the string pool instead of immediate strings so that DIEs have
200 /// more predictable sizes. In the case of split dwarf we emit an index
201 /// into another table which gets us the static offset into the string
203 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
206 if (!DD->useSplitDwarf())
207 return addLocalString(Die, Attribute, String);
209 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
210 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
211 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
212 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
215 /// addLocalString - Add a string attribute data and value. This is guaranteed
216 /// to be in the local string pool instead of indirected.
217 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
219 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
221 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
222 Value = new (DIEValueAllocator) DIELabel(Symb);
224 Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
225 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
226 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
229 /// addExpr - Add a Dwarf expression attribute data and value.
231 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
232 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
233 Die.addValue((dwarf::Attribute)0, Form, Value);
236 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
238 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
240 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
241 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
242 : dwarf::DW_FORM_data4;
243 Die.addValue(Attribute, Form, Value);
246 /// addLabel - Add a Dwarf label attribute data and value.
248 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
249 const MCSymbol *Label) {
250 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
251 Die.addValue(Attribute, Form, Value);
254 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
255 addLabel(Die, (dwarf::Attribute)0, Form, Label);
258 /// addSectionOffset - Add an offset into a section attribute data and value.
260 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
262 if (DD->getDwarfVersion() >= 4)
263 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
265 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
268 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
269 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
270 : getCU().getOrCreateSourceID(FileName, DirName);
273 /// addOpAddress - Add a dwarf op address data and value using the
274 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
276 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
277 if (!DD->useSplitDwarf()) {
278 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
279 addLabel(Die, dwarf::DW_FORM_udata, Sym);
281 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
282 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
283 DD->getAddressPool().getIndex(Sym));
287 /// addSectionDelta - Add a section label delta attribute data and value.
289 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
290 const MCSymbol *Hi, const MCSymbol *Lo) {
291 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
292 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
293 : dwarf::DW_FORM_data4,
297 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
298 const MCSymbol *Hi, const MCSymbol *Lo) {
299 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
300 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
303 /// addDIEEntry - Add a DIE attribute data and value.
305 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
306 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
309 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
310 // Flag the type unit reference as a declaration so that if it contains
311 // members (implicit special members, static data member definitions, member
312 // declarations for definitions in this CU, etc) consumers don't get confused
313 // and think this is a full definition.
314 addFlag(Die, dwarf::DW_AT_declaration);
316 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
317 new (DIEValueAllocator) DIETypeSignature(Type));
320 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
322 const DIE *DieCU = Die.getUnitOrNull();
323 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
325 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
326 DieCU = &getUnitDie();
328 EntryCU = &getUnitDie();
329 Die.addValue(Attribute,
330 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
334 /// Create a DIE with the given Tag, add the DIE to its parent, and
335 /// call insertDIE if MD is not null.
336 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
337 assert(Tag != dwarf::DW_TAG_auto_variable &&
338 Tag != dwarf::DW_TAG_arg_variable);
339 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
340 DIE &Die = *Parent.getChildren().back();
346 /// addBlock - Add block data.
348 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
349 Loc->ComputeSize(Asm);
350 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
351 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
354 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
356 Block->ComputeSize(Asm);
357 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
358 Die.addValue(Attribute, Block->BestForm(), Block);
361 /// addSourceLine - Add location information to specified debug information
363 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
364 StringRef Directory) {
368 unsigned FileID = getOrCreateSourceID(File, Directory);
369 assert(FileID && "Invalid file id");
370 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
371 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
374 /// addSourceLine - Add location information to specified debug information
376 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
377 assert(V.isVariable());
379 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
380 V.getContext().getDirectory());
383 /// addSourceLine - Add location information to specified debug information
385 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
386 assert(G.isGlobalVariable());
388 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
391 /// addSourceLine - Add location information to specified debug information
393 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
394 assert(SP.isSubprogram());
396 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
399 /// addSourceLine - Add location information to specified debug information
401 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
404 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
407 /// addSourceLine - Add location information to specified debug information
409 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
410 assert(Ty.isObjCProperty());
412 DIFile File = Ty.getFile();
413 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
414 File.getDirectory());
417 /// addSourceLine - Add location information to specified debug information
419 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
422 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
425 /// addVariableAddress - Add DW_AT_location attribute for a
426 /// DbgVariable based on provided MachineLocation.
427 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
428 MachineLocation Location) {
429 if (DV.variableHasComplexAddress())
430 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
431 else if (DV.isBlockByrefVariable())
432 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
434 addAddress(Die, dwarf::DW_AT_location, Location,
435 DV.getVariable().isIndirect());
438 /// addRegisterOp - Add register operand.
439 // FIXME: Ideally, this would share the implementation with
440 // AsmPrinter::EmitDwarfRegOpPiece.
441 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
442 unsigned SizeInBits, unsigned OffsetInBits) {
443 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
444 int DWReg = RI->getDwarfRegNum(Reg, false);
445 bool isSubRegister = DWReg < 0;
449 // Go up the super-register chain until we hit a valid dwarf register number.
450 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
451 DWReg = RI->getDwarfRegNum(*SR, false);
453 Idx = RI->getSubRegIndex(*SR, Reg);
457 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
458 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
464 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
466 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
467 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
471 bool isPiece = SizeInBits > 0;
472 if (isSubRegister || isPiece) {
473 const unsigned SizeOfByte = 8;
474 unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
475 unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
476 unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
477 unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
478 assert(RegSizeInBits >= SizeInBits && "register smaller than value");
480 if (RegOffsetInBits != PieceOffsetInBits) {
481 // Manually shift the value into place, since the DW_OP_piece
482 // describes the part of the variable, not the position of the
484 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
485 addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
486 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
489 if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
490 assert(PieceSizeInBits > 0 && "piece has zero size");
491 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
492 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
493 addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
495 assert(PieceSizeInBits > 0 && "piece has zero size");
496 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
497 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
502 /// addRegisterOffset - Add register offset.
503 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
505 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
506 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
507 const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
508 if (Reg == TRI->getFrameRegister(*Asm->MF))
509 // If variable offset is based in frame register then use fbreg.
510 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
512 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
514 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
515 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
517 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
520 /// addAddress - Add an address attribute to a die based on the location
522 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
523 const MachineLocation &Location, bool Indirect) {
524 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
526 if (Location.isReg() && !Indirect)
527 addRegisterOpPiece(*Loc, Location.getReg());
529 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
530 if (Indirect && !Location.isReg()) {
531 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
535 // Now attach the location information to the DIE.
536 addBlock(Die, Attribute, Loc);
539 /// addComplexAddress - Start with the address based on the location provided,
540 /// and generate the DWARF information necessary to find the actual variable
541 /// given the extra address information encoded in the DbgVariable, starting
542 /// from the starting location. Add the DWARF information to the die.
544 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
545 dwarf::Attribute Attribute,
546 const MachineLocation &Location) {
547 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
548 unsigned N = DV.getNumAddrElements();
550 if (Location.isReg()) {
551 if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_plus) {
552 assert(!DV.getVariable().isIndirect() &&
553 "double indirection not handled");
554 // If first address element is OpPlus then emit
555 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
556 addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
558 } else if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_deref) {
559 assert(!DV.getVariable().isIndirect() &&
560 "double indirection not handled");
561 addRegisterOpPiece(*Loc, Location.getReg(),
562 DV.getExpression().getPieceSize(),
563 DV.getExpression().getPieceOffset());
566 addRegisterOpPiece(*Loc, Location.getReg());
568 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
571 uint64_t Element = DV.getAddrElement(i);
572 if (Element == dwarf::DW_OP_plus) {
573 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
574 addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
576 } else if (Element == dwarf::DW_OP_deref) {
577 if (!Location.isReg())
578 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
580 } else if (Element == dwarf::DW_OP_piece) {
581 const unsigned SizeOfByte = 8;
582 unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
583 unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
584 // Emit DW_OP_bit_piece Size Offset.
585 assert(PieceSizeInBits > 0 && "piece has zero size");
586 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
587 addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
588 addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
591 llvm_unreachable("unknown DIBuilder Opcode");
594 // Now attach the location information to the DIE.
595 addBlock(Die, Attribute, Loc);
598 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
599 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
600 gives the variable VarName either the struct, or a pointer to the struct, as
601 its type. This is necessary for various behind-the-scenes things the
602 compiler needs to do with by-reference variables in Blocks.
604 However, as far as the original *programmer* is concerned, the variable
605 should still have type 'SomeType', as originally declared.
607 The function getBlockByrefType dives into the __Block_byref_x_VarName
608 struct to find the original type of the variable, which is then assigned to
609 the variable's Debug Information Entry as its real type. So far, so good.
610 However now the debugger will expect the variable VarName to have the type
611 SomeType. So we need the location attribute for the variable to be an
612 expression that explains to the debugger how to navigate through the
613 pointers and struct to find the actual variable of type SomeType.
615 The following function does just that. We start by getting
616 the "normal" location for the variable. This will be the location
617 of either the struct __Block_byref_x_VarName or the pointer to the
618 struct __Block_byref_x_VarName.
620 The struct will look something like:
622 struct __Block_byref_x_VarName {
624 struct __Block_byref_x_VarName *forwarding;
625 ... <various other fields>
627 ... <maybe more fields>
630 If we are given the struct directly (as our starting point) we
631 need to tell the debugger to:
633 1). Add the offset of the forwarding field.
635 2). Follow that pointer to get the real __Block_byref_x_VarName
636 struct to use (the real one may have been copied onto the heap).
638 3). Add the offset for the field VarName, to find the actual variable.
640 If we started with a pointer to the struct, then we need to
641 dereference that pointer first, before the other steps.
642 Translating this into DWARF ops, we will need to append the following
643 to the current location description for the variable:
645 DW_OP_deref -- optional, if we start with a pointer
646 DW_OP_plus_uconst <forward_fld_offset>
648 DW_OP_plus_uconst <varName_fld_offset>
650 That is what this function does. */
652 /// addBlockByrefAddress - Start with the address based on the location
653 /// provided, and generate the DWARF information necessary to find the
654 /// actual Block variable (navigating the Block struct) based on the
655 /// starting location. Add the DWARF information to the die. For
656 /// more information, read large comment just above here.
658 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
659 dwarf::Attribute Attribute,
660 const MachineLocation &Location) {
661 DIType Ty = DV.getType();
663 uint16_t Tag = Ty.getTag();
664 bool isPointer = false;
666 StringRef varName = DV.getName();
668 if (Tag == dwarf::DW_TAG_pointer_type) {
669 DIDerivedType DTy(Ty);
670 TmpTy = resolve(DTy.getTypeDerivedFrom());
674 DICompositeType blockStruct(TmpTy);
676 // Find the __forwarding field and the variable field in the __Block_byref
678 DIArray Fields = blockStruct.getElements();
679 DIDerivedType varField;
680 DIDerivedType forwardingField;
682 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
683 DIDerivedType DT(Fields.getElement(i));
684 StringRef fieldName = DT.getName();
685 if (fieldName == "__forwarding")
686 forwardingField = DT;
687 else if (fieldName == varName)
691 // Get the offsets for the forwarding field and the variable field.
692 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
693 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
695 // Decode the original location, and use that as the start of the byref
696 // variable's location.
697 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
699 if (Location.isReg())
700 addRegisterOpPiece(*Loc, Location.getReg());
702 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
704 // If we started with a pointer to the __Block_byref... struct, then
705 // the first thing we need to do is dereference the pointer (DW_OP_deref).
707 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
709 // Next add the offset for the '__forwarding' field:
710 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
711 // adding the offset if it's 0.
712 if (forwardingFieldOffset > 0) {
713 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
714 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
717 // Now dereference the __forwarding field to get to the real __Block_byref
718 // struct: DW_OP_deref.
719 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
721 // Now that we've got the real __Block_byref... struct, add the offset
722 // for the variable's field to get to the location of the actual variable:
723 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
724 if (varFieldOffset > 0) {
725 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
726 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
729 // Now attach the location information to the DIE.
730 addBlock(Die, Attribute, Loc);
733 /// Return true if type encoding is unsigned.
734 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
735 DIDerivedType DTy(Ty);
736 if (DTy.isDerivedType()) {
737 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
738 // Encode pointer constants as unsigned bytes. This is used at least for
739 // null pointer constant emission.
740 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
741 // here, but accept them for now due to a bug in SROA producing bogus
743 if (T == dwarf::DW_TAG_pointer_type ||
744 T == dwarf::DW_TAG_ptr_to_member_type ||
745 T == dwarf::DW_TAG_reference_type ||
746 T == dwarf::DW_TAG_rvalue_reference_type)
748 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
749 T == dwarf::DW_TAG_volatile_type ||
750 T == dwarf::DW_TAG_restrict_type ||
751 T == dwarf::DW_TAG_enumeration_type);
752 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
753 return isUnsignedDIType(DD, DD->resolve(Deriv));
754 // FIXME: Enums without a fixed underlying type have unknown signedness
755 // here, leading to incorrectly emitted constants.
756 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
761 assert(BTy.isBasicType());
762 unsigned Encoding = BTy.getEncoding();
763 assert((Encoding == dwarf::DW_ATE_unsigned ||
764 Encoding == dwarf::DW_ATE_unsigned_char ||
765 Encoding == dwarf::DW_ATE_signed ||
766 Encoding == dwarf::DW_ATE_signed_char ||
767 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
768 "Unsupported encoding");
769 return (Encoding == dwarf::DW_ATE_unsigned ||
770 Encoding == dwarf::DW_ATE_unsigned_char ||
771 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
774 /// If this type is derived from a base type then return base type size.
775 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
776 unsigned Tag = Ty.getTag();
778 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
779 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
780 Tag != dwarf::DW_TAG_restrict_type)
781 return Ty.getSizeInBits();
783 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
785 // If this type is not derived from any type or the type is a declaration then
786 // take conservative approach.
787 if (!BaseType.isValid() || BaseType.isForwardDecl())
788 return Ty.getSizeInBits();
790 // If this is a derived type, go ahead and get the base type, unless it's a
791 // reference then it's just the size of the field. Pointer types have no need
792 // of this since they're a different type of qualification on the type.
793 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
794 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
795 return Ty.getSizeInBits();
797 if (BaseType.isDerivedType())
798 return getBaseTypeSize(DD, DIDerivedType(BaseType));
800 return BaseType.getSizeInBits();
803 /// addConstantFPValue - Add constant value entry in variable DIE.
804 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
805 assert(MO.isFPImm() && "Invalid machine operand!");
806 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
807 APFloat FPImm = MO.getFPImm()->getValueAPF();
809 // Get the raw data form of the floating point.
810 const APInt FltVal = FPImm.bitcastToAPInt();
811 const char *FltPtr = (const char *)FltVal.getRawData();
813 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
814 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
815 int Incr = (LittleEndian ? 1 : -1);
816 int Start = (LittleEndian ? 0 : NumBytes - 1);
817 int Stop = (LittleEndian ? NumBytes : -1);
819 // Output the constant to DWARF one byte at a time.
820 for (; Start != Stop; Start += Incr)
821 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
823 addBlock(Die, dwarf::DW_AT_const_value, Block);
826 /// addConstantFPValue - Add constant value entry in variable DIE.
827 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
828 // Pass this down to addConstantValue as an unsigned bag of bits.
829 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
832 /// addConstantValue - Add constant value entry in variable DIE.
833 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
834 addConstantValue(Die, CI->getValue(), Ty);
837 /// addConstantValue - Add constant value entry in variable DIE.
838 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
840 assert(MO.isImm() && "Invalid machine operand!");
842 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
845 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
846 // FIXME: This is a bit conservative/simple - it emits negative values always
847 // sign extended to 64 bits rather than minimizing the number of bytes.
848 addUInt(Die, dwarf::DW_AT_const_value,
849 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
852 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
853 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
856 // addConstantValue - Add constant value entry in variable DIE.
857 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
858 unsigned CIBitWidth = Val.getBitWidth();
859 if (CIBitWidth <= 64) {
860 addConstantValue(Die, Unsigned,
861 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
865 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
867 // Get the raw data form of the large APInt.
868 const uint64_t *Ptr64 = Val.getRawData();
870 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
871 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
873 // Output the constant to DWARF one byte at a time.
874 for (int i = 0; i < NumBytes; i++) {
877 c = Ptr64[i / 8] >> (8 * (i & 7));
879 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
880 addUInt(*Block, dwarf::DW_FORM_data1, c);
883 addBlock(Die, dwarf::DW_AT_const_value, Block);
886 /// addTemplateParams - Add template parameters into buffer.
887 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
888 // Add template parameters.
889 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
890 DIDescriptor Element = TParams.getElement(i);
891 if (Element.isTemplateTypeParameter())
892 constructTemplateTypeParameterDIE(Buffer,
893 DITemplateTypeParameter(Element));
894 else if (Element.isTemplateValueParameter())
895 constructTemplateValueParameterDIE(Buffer,
896 DITemplateValueParameter(Element));
900 /// getOrCreateContextDIE - Get context owner's DIE.
901 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
902 if (!Context || Context.isFile())
903 return &getUnitDie();
904 if (Context.isType())
905 return getOrCreateTypeDIE(DIType(Context));
906 if (Context.isNameSpace())
907 return getOrCreateNameSpace(DINameSpace(Context));
908 if (Context.isSubprogram())
909 return getOrCreateSubprogramDIE(DISubprogram(Context));
910 return getDIE(Context);
913 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
914 DIScope Context = resolve(Ty.getContext());
915 DIE *ContextDIE = getOrCreateContextDIE(Context);
917 if (DIE *TyDIE = getDIE(Ty))
921 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
923 constructTypeDIE(TyDIE, Ty);
925 updateAcceleratorTables(Context, Ty, TyDIE);
929 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
931 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
937 assert(Ty == resolve(Ty.getRef()) &&
938 "type was not uniqued, possible ODR violation.");
940 // DW_TAG_restrict_type is not supported in DWARF2
941 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
942 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
944 // Construct the context before querying for the existence of the DIE in case
945 // such construction creates the DIE.
946 DIScope Context = resolve(Ty.getContext());
947 DIE *ContextDIE = getOrCreateContextDIE(Context);
950 if (DIE *TyDIE = getDIE(Ty))
954 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
956 updateAcceleratorTables(Context, Ty, TyDIE);
958 if (Ty.isBasicType())
959 constructTypeDIE(TyDIE, DIBasicType(Ty));
960 else if (Ty.isCompositeType()) {
961 DICompositeType CTy(Ty);
962 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
963 if (MDString *TypeId = CTy.getIdentifier()) {
964 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
965 // Skip updating the accelerator tables since this is not the full type.
968 constructTypeDIE(TyDIE, CTy);
970 assert(Ty.isDerivedType() && "Unknown kind of DIType");
971 constructTypeDIE(TyDIE, DIDerivedType(Ty));
977 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
979 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
980 bool IsImplementation = 0;
981 if (Ty.isCompositeType()) {
982 DICompositeType CT(Ty);
983 // A runtime language of 0 actually means C/C++ and that any
984 // non-negative value is some version of Objective-C/C++.
985 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
987 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
988 DD->addAccelType(Ty.getName(), TyDIE, Flags);
990 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
991 Context.isNameSpace()) &&
992 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
993 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
998 /// addType - Add a new type attribute to the specified entity.
999 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1000 assert(Ty && "Trying to add a type that doesn't exist?");
1002 // Check for pre-existence.
1003 DIEEntry *Entry = getDIEEntry(Ty);
1004 // If it exists then use the existing value.
1006 addDIEEntry(Entity, Attribute, Entry);
1011 DIE *Buffer = getOrCreateTypeDIE(Ty);
1014 Entry = createDIEEntry(*Buffer);
1015 insertDIEEntry(Ty, Entry);
1016 addDIEEntry(Entity, Attribute, Entry);
1019 /// addGlobalName - Add a new global name to the compile unit.
1020 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1021 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1023 std::string FullName = getParentContextString(Context) + Name.str();
1024 GlobalNames[FullName] = &Die;
1027 /// getParentContextString - Walks the metadata parent chain in a language
1028 /// specific manner (using the compile unit language) and returns
1029 /// it as a string. This is done at the metadata level because DIEs may
1030 /// not currently have been added to the parent context and walking the
1031 /// DIEs looking for names is more expensive than walking the metadata.
1032 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1036 // FIXME: Decide whether to implement this for non-C++ languages.
1037 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1041 SmallVector<DIScope, 1> Parents;
1042 while (!Context.isCompileUnit()) {
1043 Parents.push_back(Context);
1044 if (Context.getContext())
1045 Context = resolve(Context.getContext());
1047 // Structure, etc types will have a NULL context if they're at the top
1052 // Reverse iterate over our list to go from the outermost construct to the
1054 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1058 StringRef Name = Ctx.getName();
1059 if (Name.empty() && Ctx.isNameSpace())
1060 Name = "(anonymous namespace)";
1061 if (!Name.empty()) {
1069 /// constructTypeDIE - Construct basic type die from DIBasicType.
1070 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1071 // Get core information.
1072 StringRef Name = BTy.getName();
1073 // Add name if not anonymous or intermediate type.
1075 addString(Buffer, dwarf::DW_AT_name, Name);
1077 // An unspecified type only has a name attribute.
1078 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1081 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1084 uint64_t Size = BTy.getSizeInBits() >> 3;
1085 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1088 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1089 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1090 // Get core information.
1091 StringRef Name = DTy.getName();
1092 uint64_t Size = DTy.getSizeInBits() >> 3;
1093 uint16_t Tag = Buffer.getTag();
1095 // Map to main type, void will not have a type.
1096 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1098 addType(Buffer, FromTy);
1100 // Add name if not anonymous or intermediate type.
1102 addString(Buffer, dwarf::DW_AT_name, Name);
1104 // Add size if non-zero (derived types might be zero-sized.)
1105 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1106 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1108 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1109 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1110 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1111 // Add source line info if available and TyDesc is not a forward declaration.
1112 if (!DTy.isForwardDecl())
1113 addSourceLine(Buffer, DTy);
1116 /// constructSubprogramArguments - Construct function argument DIEs.
1117 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1118 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1119 DIType Ty = resolve(Args.getElement(i));
1121 assert(i == N-1 && "Unspecified parameter must be the last argument");
1122 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1124 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1125 addType(Arg, DIType(Ty));
1126 if (DIType(Ty).isArtificial())
1127 addFlag(Arg, dwarf::DW_AT_artificial);
1132 std::unique_ptr<DIE>
1133 DwarfUnit::constructImportedEntityDIE(const DIImportedEntity &Module) {
1134 assert(Module.Verify() &&
1135 "Use one of the MDNode * overloads to handle invalid metadata");
1136 std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
1137 insertDIE(Module, IMDie.get());
1139 DIDescriptor Entity = resolve(Module.getEntity());
1140 if (Entity.isNameSpace())
1141 EntityDie = getOrCreateNameSpace(DINameSpace(Entity));
1142 else if (Entity.isSubprogram())
1143 EntityDie = getOrCreateSubprogramDIE(DISubprogram(Entity));
1144 else if (Entity.isType())
1145 EntityDie = getOrCreateTypeDIE(DIType(Entity));
1147 EntityDie = getDIE(Entity);
1149 addSourceLine(*IMDie, Module.getLineNumber(),
1150 Module.getContext().getFilename(),
1151 Module.getContext().getDirectory());
1152 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1153 StringRef Name = Module.getName();
1155 addString(*IMDie, dwarf::DW_AT_name, Name);
1160 /// constructTypeDIE - Construct type DIE from DICompositeType.
1161 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1162 // Add name if not anonymous or intermediate type.
1163 StringRef Name = CTy.getName();
1165 uint64_t Size = CTy.getSizeInBits() >> 3;
1166 uint16_t Tag = Buffer.getTag();
1169 case dwarf::DW_TAG_array_type:
1170 constructArrayTypeDIE(Buffer, CTy);
1172 case dwarf::DW_TAG_enumeration_type:
1173 constructEnumTypeDIE(Buffer, CTy);
1175 case dwarf::DW_TAG_subroutine_type: {
1176 // Add return type. A void return won't have a type.
1177 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1178 DIType RTy(resolve(Elements.getElement(0)));
1180 addType(Buffer, RTy);
1182 bool isPrototyped = true;
1183 if (Elements.getNumElements() == 2 &&
1184 !Elements.getElement(1))
1185 isPrototyped = false;
1187 constructSubprogramArguments(Buffer, Elements);
1189 // Add prototype flag if we're dealing with a C language and the
1190 // function has been prototyped.
1191 uint16_t Language = getLanguage();
1193 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1194 Language == dwarf::DW_LANG_ObjC))
1195 addFlag(Buffer, dwarf::DW_AT_prototyped);
1197 if (CTy.isLValueReference())
1198 addFlag(Buffer, dwarf::DW_AT_reference);
1200 if (CTy.isRValueReference())
1201 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1203 case dwarf::DW_TAG_structure_type:
1204 case dwarf::DW_TAG_union_type:
1205 case dwarf::DW_TAG_class_type: {
1206 // Add elements to structure type.
1207 DIArray Elements = CTy.getElements();
1208 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1209 DIDescriptor Element = Elements.getElement(i);
1210 if (Element.isSubprogram())
1211 getOrCreateSubprogramDIE(DISubprogram(Element));
1212 else if (Element.isDerivedType()) {
1213 DIDerivedType DDTy(Element);
1214 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1215 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1216 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1217 dwarf::DW_AT_friend);
1218 } else if (DDTy.isStaticMember()) {
1219 getOrCreateStaticMemberDIE(DDTy);
1221 constructMemberDIE(Buffer, DDTy);
1223 } else if (Element.isObjCProperty()) {
1224 DIObjCProperty Property(Element);
1225 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1226 StringRef PropertyName = Property.getObjCPropertyName();
1227 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1228 if (Property.getType())
1229 addType(ElemDie, Property.getType());
1230 addSourceLine(ElemDie, Property);
1231 StringRef GetterName = Property.getObjCPropertyGetterName();
1232 if (!GetterName.empty())
1233 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1234 StringRef SetterName = Property.getObjCPropertySetterName();
1235 if (!SetterName.empty())
1236 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1237 unsigned PropertyAttributes = 0;
1238 if (Property.isReadOnlyObjCProperty())
1239 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1240 if (Property.isReadWriteObjCProperty())
1241 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1242 if (Property.isAssignObjCProperty())
1243 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1244 if (Property.isRetainObjCProperty())
1245 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1246 if (Property.isCopyObjCProperty())
1247 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1248 if (Property.isNonAtomicObjCProperty())
1249 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1250 if (PropertyAttributes)
1251 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1252 PropertyAttributes);
1254 DIEEntry *Entry = getDIEEntry(Element);
1256 Entry = createDIEEntry(ElemDie);
1257 insertDIEEntry(Element, Entry);
1263 if (CTy.isAppleBlockExtension())
1264 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1266 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1268 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1269 *getOrCreateTypeDIE(ContainingType));
1271 if (CTy.isObjcClassComplete())
1272 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1274 // Add template parameters to a class, structure or union types.
1275 // FIXME: The support isn't in the metadata for this yet.
1276 if (Tag == dwarf::DW_TAG_class_type ||
1277 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1278 addTemplateParams(Buffer, CTy.getTemplateParams());
1286 // Add name if not anonymous or intermediate type.
1288 addString(Buffer, dwarf::DW_AT_name, Name);
1290 if (Tag == dwarf::DW_TAG_enumeration_type ||
1291 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1292 Tag == dwarf::DW_TAG_union_type) {
1293 // Add size if non-zero (derived types might be zero-sized.)
1294 // TODO: Do we care about size for enum forward declarations?
1296 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1297 else if (!CTy.isForwardDecl())
1298 // Add zero size if it is not a forward declaration.
1299 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1301 // If we're a forward decl, say so.
1302 if (CTy.isForwardDecl())
1303 addFlag(Buffer, dwarf::DW_AT_declaration);
1305 // Add source line info if available.
1306 if (!CTy.isForwardDecl())
1307 addSourceLine(Buffer, CTy);
1309 // No harm in adding the runtime language to the declaration.
1310 unsigned RLang = CTy.getRunTimeLang();
1312 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1317 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1318 /// DITemplateTypeParameter.
1319 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1320 DITemplateTypeParameter TP) {
1322 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1323 // Add the type if it exists, it could be void and therefore no type.
1325 addType(ParamDIE, resolve(TP.getType()));
1326 if (!TP.getName().empty())
1327 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1330 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1331 /// DITemplateValueParameter.
1333 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1334 DITemplateValueParameter VP) {
1335 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1337 // Add the type if there is one, template template and template parameter
1338 // packs will not have a type.
1339 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1340 addType(ParamDIE, resolve(VP.getType()));
1341 if (!VP.getName().empty())
1342 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1343 if (Value *Val = VP.getValue()) {
1344 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1345 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1346 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1347 // For declaration non-type template parameters (such as global values and
1349 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1350 addOpAddress(*Loc, Asm->getSymbol(GV));
1351 // Emit DW_OP_stack_value to use the address as the immediate value of the
1352 // parameter, rather than a pointer to it.
1353 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1354 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1355 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1356 assert(isa<MDString>(Val));
1357 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1358 cast<MDString>(Val)->getString());
1359 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1360 assert(isa<MDNode>(Val));
1361 DIArray A(cast<MDNode>(Val));
1362 addTemplateParams(ParamDIE, A);
1367 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1368 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1369 // Construct the context before querying for the existence of the DIE in case
1370 // such construction creates the DIE.
1371 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1373 if (DIE *NDie = getDIE(NS))
1375 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1377 StringRef Name = NS.getName();
1379 addString(NDie, dwarf::DW_AT_name, NS.getName());
1381 Name = "(anonymous namespace)";
1382 DD->addAccelNamespace(Name, NDie);
1383 addGlobalName(Name, NDie, NS.getContext());
1384 addSourceLine(NDie, NS);
1388 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1389 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1390 // Construct the context before querying for the existence of the DIE in case
1391 // such construction creates the DIE (as is the case for member function
1393 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1395 if (DIE *SPDie = getDIE(SP))
1398 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1399 // Add subprogram definitions to the CU die directly.
1400 ContextDIE = &getUnitDie();
1401 // Build the decl now to ensure it precedes the definition.
1402 getOrCreateSubprogramDIE(SPDecl);
1405 // DW_TAG_inlined_subroutine may refer to this DIE.
1406 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1408 // Stop here and fill this in later, depending on whether or not this
1409 // subprogram turns out to have inlined instances or not.
1410 if (SP.isDefinition())
1413 applySubprogramAttributes(SP, SPDie);
1417 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1418 DISubprogram SPDecl = SP.getFunctionDeclaration();
1419 DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1420 applySubprogramAttributes(SP, SPDie);
1421 addGlobalName(SP.getName(), SPDie, Context);
1424 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1425 DIE *DeclDie = nullptr;
1426 StringRef DeclLinkageName;
1427 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1428 DeclDie = getDIE(SPDecl);
1429 assert(DeclDie && "This DIE should've already been constructed when the "
1430 "definition DIE was created in "
1431 "getOrCreateSubprogramDIE");
1432 DeclLinkageName = SPDecl.getLinkageName();
1435 // Add function template parameters.
1436 addTemplateParams(SPDie, SP.getTemplateParams());
1438 // Add the linkage name if we have one and it isn't in the Decl.
1439 StringRef LinkageName = SP.getLinkageName();
1440 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1441 LinkageName == DeclLinkageName) &&
1442 "decl has a linkage name and it is different");
1443 if (!LinkageName.empty() && DeclLinkageName.empty())
1444 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1445 GlobalValue::getRealLinkageName(LinkageName));
1448 // Refer to the function declaration where all the other attributes will be
1450 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1454 // Constructors and operators for anonymous aggregates do not have names.
1455 if (!SP.getName().empty())
1456 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1458 // Skip the rest of the attributes under -gmlt to save space.
1459 if(getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1462 addSourceLine(SPDie, SP);
1464 // Add the prototype if we have a prototype and we have a C like
1466 uint16_t Language = getLanguage();
1467 if (SP.isPrototyped() &&
1468 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1469 Language == dwarf::DW_LANG_ObjC))
1470 addFlag(SPDie, dwarf::DW_AT_prototyped);
1472 DISubroutineType SPTy = SP.getType();
1473 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1474 "the type of a subprogram should be a subroutine");
1476 DITypeArray Args = SPTy.getTypeArray();
1477 // Add a return type. If this is a type like a C/C++ void type we don't add a
1479 if (resolve(Args.getElement(0)))
1480 addType(SPDie, DIType(resolve(Args.getElement(0))));
1482 unsigned VK = SP.getVirtuality();
1484 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1485 DIELoc *Block = getDIELoc();
1486 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1487 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1488 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1489 ContainingTypeMap.insert(
1490 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1493 if (!SP.isDefinition()) {
1494 addFlag(SPDie, dwarf::DW_AT_declaration);
1496 // Add arguments. Do not add arguments for subprogram definition. They will
1497 // be handled while processing variables.
1498 constructSubprogramArguments(SPDie, Args);
1501 if (SP.isArtificial())
1502 addFlag(SPDie, dwarf::DW_AT_artificial);
1504 if (!SP.isLocalToUnit())
1505 addFlag(SPDie, dwarf::DW_AT_external);
1507 if (SP.isOptimized())
1508 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1510 if (unsigned isa = Asm->getISAEncoding()) {
1511 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1514 if (SP.isLValueReference())
1515 addFlag(SPDie, dwarf::DW_AT_reference);
1517 if (SP.isRValueReference())
1518 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1520 if (SP.isProtected())
1521 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1522 dwarf::DW_ACCESS_protected);
1523 else if (SP.isPrivate())
1524 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1525 dwarf::DW_ACCESS_private);
1526 else if (SP.isPublic())
1527 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1528 dwarf::DW_ACCESS_public);
1530 if (SP.isExplicit())
1531 addFlag(SPDie, dwarf::DW_AT_explicit);
1534 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1536 StringRef Name = Var.getName();
1538 addString(VariableDie, dwarf::DW_AT_name, Name);
1539 addSourceLine(VariableDie, Var.getVariable());
1540 addType(VariableDie, Var.getType());
1541 if (Var.isArtificial())
1542 addFlag(VariableDie, dwarf::DW_AT_artificial);
1545 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1546 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1547 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1548 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1550 // The LowerBound value defines the lower bounds which is typically zero for
1551 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1552 // Count == -1 then the array is unbounded and we do not emit
1553 // DW_AT_lower_bound and DW_AT_count attributes.
1554 int64_t LowerBound = SR.getLo();
1555 int64_t DefaultLowerBound = getDefaultLowerBound();
1556 int64_t Count = SR.getCount();
1558 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1559 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1562 // FIXME: An unbounded array should reference the expression that defines
1564 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1567 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1568 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1570 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1572 // Emit the element type.
1573 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1575 // Get an anonymous type for index type.
1576 // FIXME: This type should be passed down from the front end
1577 // as different languages may have different sizes for indexes.
1578 DIE *IdxTy = getIndexTyDie();
1580 // Construct an integer type to use for indexes.
1581 IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1582 addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1583 addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1584 addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1585 dwarf::DW_ATE_unsigned);
1586 setIndexTyDie(IdxTy);
1589 // Add subranges to array type.
1590 DIArray Elements = CTy.getElements();
1591 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1592 DIDescriptor Element = Elements.getElement(i);
1593 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1594 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1598 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1599 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1600 DIArray Elements = CTy.getElements();
1602 // Add enumerators to enumeration type.
1603 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1604 DIEnumerator Enum(Elements.getElement(i));
1605 if (Enum.isEnumerator()) {
1606 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1607 StringRef Name = Enum.getName();
1608 addString(Enumerator, dwarf::DW_AT_name, Name);
1609 int64_t Value = Enum.getEnumValue();
1610 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1614 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1616 addType(Buffer, DTy);
1617 addFlag(Buffer, dwarf::DW_AT_enum_class);
1621 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1623 void DwarfUnit::constructContainingTypeDIEs() {
1624 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1625 CE = ContainingTypeMap.end();
1627 DIE &SPDie = *CI->first;
1628 DIDescriptor D(CI->second);
1631 DIE *NDie = getDIE(D);
1634 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1638 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1639 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1641 auto D = constructVariableDIEImpl(DV, Abstract);
1646 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1648 // Define variable debug information entry.
1649 auto VariableDie = make_unique<DIE>(DV.getTag());
1652 applyVariableAttributes(DV, *VariableDie);
1656 // Add variable address.
1658 unsigned Offset = DV.getDotDebugLocOffset();
1659 if (Offset != ~0U) {
1660 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1664 // Check if variable is described by a DBG_VALUE instruction.
1665 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1666 assert(DVInsn->getNumOperands() == 4);
1667 if (DVInsn->getOperand(0).isReg()) {
1668 const MachineOperand RegOp = DVInsn->getOperand(0);
1669 // If the second operand is an immediate, this is an indirect value.
1670 if (DVInsn->getOperand(1).isImm()) {
1671 MachineLocation Location(RegOp.getReg(),
1672 DVInsn->getOperand(1).getImm());
1673 addVariableAddress(DV, *VariableDie, Location);
1674 } else if (RegOp.getReg())
1675 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1676 } else if (DVInsn->getOperand(0).isImm())
1677 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1678 else if (DVInsn->getOperand(0).isFPImm())
1679 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1680 else if (DVInsn->getOperand(0).isCImm())
1681 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1687 // .. else use frame index.
1688 int FI = DV.getFrameIndex();
1690 unsigned FrameReg = 0;
1691 const TargetFrameLowering *TFI =
1692 Asm->TM.getSubtargetImpl()->getFrameLowering();
1693 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1694 MachineLocation Location(FrameReg, Offset);
1695 addVariableAddress(DV, *VariableDie, Location);
1701 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1702 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1703 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1704 StringRef Name = DT.getName();
1706 addString(MemberDie, dwarf::DW_AT_name, Name);
1708 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1710 addSourceLine(MemberDie, DT);
1712 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1714 // For C++, virtual base classes are not at fixed offset. Use following
1715 // expression to extract appropriate offset from vtable.
1716 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1718 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1719 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1720 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1721 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1722 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1723 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1724 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1725 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1727 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1729 uint64_t Size = DT.getSizeInBits();
1730 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1731 uint64_t OffsetInBytes;
1733 if (Size != FieldSize) {
1734 // Handle bitfield, assume bytes are 8 bits.
1735 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1736 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1738 uint64_t Offset = DT.getOffsetInBits();
1739 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1740 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1741 uint64_t FieldOffset = (HiMark - FieldSize);
1742 Offset -= FieldOffset;
1744 // Maybe we need to work from the other end.
1745 if (Asm->getDataLayout().isLittleEndian())
1746 Offset = FieldSize - (Offset + Size);
1747 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1749 // Here DW_AT_data_member_location points to the anonymous
1750 // field that includes this bit field.
1751 OffsetInBytes = FieldOffset >> 3;
1753 // This is not a bitfield.
1754 OffsetInBytes = DT.getOffsetInBits() >> 3;
1756 if (DD->getDwarfVersion() <= 2) {
1757 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1758 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1759 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1760 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1762 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1766 if (DT.isProtected())
1767 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1768 dwarf::DW_ACCESS_protected);
1769 else if (DT.isPrivate())
1770 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1771 dwarf::DW_ACCESS_private);
1772 // Otherwise C++ member and base classes are considered public.
1773 else if (DT.isPublic())
1774 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1775 dwarf::DW_ACCESS_public);
1777 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1778 dwarf::DW_VIRTUALITY_virtual);
1780 // Objective-C properties.
1781 if (MDNode *PNode = DT.getObjCProperty())
1782 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1783 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1786 if (DT.isArtificial())
1787 addFlag(MemberDie, dwarf::DW_AT_artificial);
1790 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1791 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1795 // Construct the context before querying for the existence of the DIE in case
1796 // such construction creates the DIE.
1797 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1798 assert(dwarf::isType(ContextDIE->getTag()) &&
1799 "Static member should belong to a type.");
1801 if (DIE *StaticMemberDIE = getDIE(DT))
1802 return StaticMemberDIE;
1804 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1806 DIType Ty = resolve(DT.getTypeDerivedFrom());
1808 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1809 addType(StaticMemberDIE, Ty);
1810 addSourceLine(StaticMemberDIE, DT);
1811 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1812 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1814 // FIXME: We could omit private if the parent is a class_type, and
1815 // public if the parent is something else.
1816 if (DT.isProtected())
1817 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1818 dwarf::DW_ACCESS_protected);
1819 else if (DT.isPrivate())
1820 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1821 dwarf::DW_ACCESS_private);
1822 else if (DT.isPublic())
1823 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1824 dwarf::DW_ACCESS_public);
1826 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1827 addConstantValue(StaticMemberDIE, CI, Ty);
1828 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1829 addConstantFPValue(StaticMemberDIE, CFP);
1831 return &StaticMemberDIE;
1834 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
1835 Asm->OutStreamer.AddComment("DWARF version number");
1836 Asm->EmitInt16(DD->getDwarfVersion());
1837 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1838 // We share one abbreviations table across all units so it's always at the
1839 // start of the section. Use a relocatable offset where needed to ensure
1840 // linking doesn't invalidate that offset.
1842 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1844 // Use a constant value when no symbol is provided.
1846 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1847 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1850 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
1851 DwarfUnit::emitHeader(ASectionSym);
1852 Asm->OutStreamer.AddComment("Type Signature");
1853 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1854 Asm->OutStreamer.AddComment("Type DIE Offset");
1855 // In a skeleton type unit there is no type DIE so emit a zero offset.
1856 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1857 sizeof(Ty->getOffset()));
1860 void DwarfTypeUnit::initSection(const MCSection *Section) {
1861 assert(!this->Section);
1862 this->Section = Section;
1863 // Since each type unit is contained in its own COMDAT section, the begin
1864 // label and the section label are the same. Using the begin label emission in
1865 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
1866 // the only other alternative of lazily constructing start-of-section labels
1867 // and storing a mapping in DwarfDebug (or AsmPrinter).
1868 this->SectionSym = this->LabelBegin =
1869 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
1871 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());