1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfUnit.h"
15 #include "DwarfAccelTable.h"
16 #include "DwarfDebug.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
37 #define DEBUG_TYPE "dwarfdebug"
40 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
41 cl::desc("Generate DWARF4 type units."),
44 /// Unit - Unit constructor.
45 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
46 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
47 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
48 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr),
50 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
51 UnitTag == dwarf::DW_TAG_type_unit);
52 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
55 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
56 AsmPrinter *A, DwarfDebug *DW,
58 : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU) {
59 insertDIE(Node, &getUnitDie());
62 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
63 DwarfDebug *DW, DwarfFile *DWU,
64 MCDwarfDwoLineTable *SplitLineTable)
65 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
66 CU(CU), SplitLineTable(SplitLineTable) {
68 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
71 /// ~Unit - Destructor for compile unit.
72 DwarfUnit::~DwarfUnit() {
73 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
74 DIEBlocks[j]->~DIEBlock();
75 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
76 DIELocs[j]->~DIELoc();
79 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
80 /// information entry.
81 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
82 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
86 /// getDefaultLowerBound - Return the default lower bound for an array. If the
87 /// DWARF version doesn't handle the language, return -1.
88 int64_t DwarfUnit::getDefaultLowerBound() const {
89 switch (getLanguage()) {
93 case dwarf::DW_LANG_C89:
94 case dwarf::DW_LANG_C99:
95 case dwarf::DW_LANG_C:
96 case dwarf::DW_LANG_C_plus_plus:
97 case dwarf::DW_LANG_ObjC:
98 case dwarf::DW_LANG_ObjC_plus_plus:
101 case dwarf::DW_LANG_Fortran77:
102 case dwarf::DW_LANG_Fortran90:
103 case dwarf::DW_LANG_Fortran95:
106 // The languages below have valid values only if the DWARF version >= 4.
107 case dwarf::DW_LANG_Java:
108 case dwarf::DW_LANG_Python:
109 case dwarf::DW_LANG_UPC:
110 case dwarf::DW_LANG_D:
111 if (dwarf::DWARF_VERSION >= 4)
115 case dwarf::DW_LANG_Ada83:
116 case dwarf::DW_LANG_Ada95:
117 case dwarf::DW_LANG_Cobol74:
118 case dwarf::DW_LANG_Cobol85:
119 case dwarf::DW_LANG_Modula2:
120 case dwarf::DW_LANG_Pascal83:
121 case dwarf::DW_LANG_PLI:
122 if (dwarf::DWARF_VERSION >= 4)
130 /// Check whether the DIE for this MDNode can be shared across CUs.
131 static bool isShareableAcrossCUs(DIDescriptor D) {
132 // When the MDNode can be part of the type system, the DIE can be shared
134 // Combining type units and cross-CU DIE sharing is lower value (since
135 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
136 // level already) but may be implementable for some value in projects
137 // building multiple independent libraries with LTO and then linking those
139 return (D.isType() ||
140 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
141 !GenerateDwarfTypeUnits;
144 /// getDIE - Returns the debug information entry map slot for the
145 /// specified debug variable. We delegate the request to DwarfDebug
146 /// when the DIE for this MDNode can be shared across CUs. The mappings
147 /// will be kept in DwarfDebug for shareable DIEs.
148 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
149 if (isShareableAcrossCUs(D))
150 return DD->getDIE(D);
151 return MDNodeToDieMap.lookup(D);
154 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
155 /// when the DIE for this MDNode can be shared across CUs. The mappings
156 /// will be kept in DwarfDebug for shareable DIEs.
157 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
158 if (isShareableAcrossCUs(Desc)) {
159 DD->insertDIE(Desc, D);
162 MDNodeToDieMap.insert(std::make_pair(Desc, D));
165 /// addFlag - Add a flag that is true.
166 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
167 if (DD->getDwarfVersion() >= 4)
168 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
170 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
173 /// addUInt - Add an unsigned integer attribute data and value.
175 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
176 Optional<dwarf::Form> Form, uint64_t Integer) {
178 Form = DIEInteger::BestForm(false, Integer);
179 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
181 Die.addValue(Attribute, *Form, Value);
184 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
185 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
188 /// addSInt - Add an signed integer attribute data and value.
190 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
191 Optional<dwarf::Form> Form, int64_t Integer) {
193 Form = DIEInteger::BestForm(true, Integer);
194 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
195 Die.addValue(Attribute, *Form, Value);
198 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
200 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
203 /// addString - Add a string attribute data and value. We always emit a
204 /// reference to the string pool instead of immediate strings so that DIEs have
205 /// more predictable sizes. In the case of split dwarf we emit an index
206 /// into another table which gets us the static offset into the string
208 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
211 if (!DD->useSplitDwarf())
212 return addLocalString(Die, Attribute, String);
214 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
215 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
216 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
217 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
220 /// addLocalString - Add a string attribute data and value. This is guaranteed
221 /// to be in the local string pool instead of indirected.
222 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
224 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
226 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
227 Value = new (DIEValueAllocator) DIELabel(Symb);
229 Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
230 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
231 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
234 /// addExpr - Add a Dwarf expression attribute data and value.
236 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
237 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
238 Die.addValue((dwarf::Attribute)0, Form, Value);
241 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
243 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
245 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
246 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
247 : dwarf::DW_FORM_data4;
248 Die.addValue(Attribute, Form, Value);
251 /// addLabel - Add a Dwarf label attribute data and value.
253 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
254 const MCSymbol *Label) {
255 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
256 Die.addValue(Attribute, Form, Value);
259 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
260 addLabel(Die, (dwarf::Attribute)0, Form, Label);
263 /// addSectionLabel - Add a Dwarf section label attribute data and value.
265 void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
266 const MCSymbol *Label) {
267 if (DD->getDwarfVersion() >= 4)
268 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
270 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
273 /// addSectionOffset - Add an offset into a section attribute data and value.
275 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
277 if (DD->getDwarfVersion() >= 4)
278 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
280 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
283 /// addLabelAddress - Add a dwarf label attribute data and value using
284 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
286 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
287 const MCSymbol *Label) {
289 if (!DD->useSplitDwarf() || !Skeleton)
290 return addLocalLabelAddress(Die, Attribute, Label);
293 DD->addArangeLabel(SymbolCU(this, Label));
295 unsigned idx = DD->getAddressPool().getIndex(Label);
296 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
297 Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
300 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
301 dwarf::Attribute Attribute,
302 const MCSymbol *Label) {
304 DD->addArangeLabel(SymbolCU(this, Label));
306 Die.addValue(Attribute, dwarf::DW_FORM_addr,
307 Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
308 : new (DIEValueAllocator) DIEInteger(0));
311 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
312 // If we print assembly, we can't separate .file entries according to
313 // compile units. Thus all files will belong to the default compile unit.
315 // FIXME: add a better feature test than hasRawTextSupport. Even better,
316 // extend .file to support this.
317 return Asm->OutStreamer.EmitDwarfFileDirective(
318 0, DirName, FileName,
319 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
322 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
323 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
324 : getCU().getOrCreateSourceID(FileName, DirName);
327 /// addOpAddress - Add a dwarf op address data and value using the
328 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
330 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
331 if (!DD->useSplitDwarf()) {
332 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
333 addLabel(Die, dwarf::DW_FORM_udata, Sym);
335 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
336 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
337 DD->getAddressPool().getIndex(Sym));
341 /// addSectionDelta - Add a section label delta attribute data and value.
343 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
344 const MCSymbol *Hi, const MCSymbol *Lo) {
345 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
346 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
347 : dwarf::DW_FORM_data4,
351 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
352 const MCSymbol *Hi, const MCSymbol *Lo) {
353 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
354 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
357 /// addDIEEntry - Add a DIE attribute data and value.
359 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
360 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
363 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
364 // Flag the type unit reference as a declaration so that if it contains
365 // members (implicit special members, static data member definitions, member
366 // declarations for definitions in this CU, etc) consumers don't get confused
367 // and think this is a full definition.
368 addFlag(Die, dwarf::DW_AT_declaration);
370 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
371 new (DIEValueAllocator) DIETypeSignature(Type));
374 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
376 const DIE *DieCU = Die.getUnitOrNull();
377 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
379 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
380 DieCU = &getUnitDie();
382 EntryCU = &getUnitDie();
383 Die.addValue(Attribute,
384 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
388 /// Create a DIE with the given Tag, add the DIE to its parent, and
389 /// call insertDIE if MD is not null.
390 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
391 assert(Tag != dwarf::DW_TAG_auto_variable &&
392 Tag != dwarf::DW_TAG_arg_variable);
393 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
394 DIE &Die = *Parent.getChildren().back();
400 /// addBlock - Add block data.
402 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
403 Loc->ComputeSize(Asm);
404 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
405 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
408 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
410 Block->ComputeSize(Asm);
411 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
412 Die.addValue(Attribute, Block->BestForm(), Block);
415 /// addSourceLine - Add location information to specified debug information
417 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
418 StringRef Directory) {
422 unsigned FileID = getOrCreateSourceID(File, Directory);
423 assert(FileID && "Invalid file id");
424 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
425 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
428 /// addSourceLine - Add location information to specified debug information
430 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
431 assert(V.isVariable());
433 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
434 V.getContext().getDirectory());
437 /// addSourceLine - Add location information to specified debug information
439 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
440 assert(G.isGlobalVariable());
442 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
445 /// addSourceLine - Add location information to specified debug information
447 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
448 assert(SP.isSubprogram());
450 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
453 /// addSourceLine - Add location information to specified debug information
455 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
458 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
461 /// addSourceLine - Add location information to specified debug information
463 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
464 assert(Ty.isObjCProperty());
466 DIFile File = Ty.getFile();
467 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
468 File.getDirectory());
471 /// addSourceLine - Add location information to specified debug information
473 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
476 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
479 /// addVariableAddress - Add DW_AT_location attribute for a
480 /// DbgVariable based on provided MachineLocation.
481 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
482 MachineLocation Location) {
483 if (DV.variableHasComplexAddress())
484 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
485 else if (DV.isBlockByrefVariable())
486 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
488 addAddress(Die, dwarf::DW_AT_location, Location,
489 DV.getVariable().isIndirect());
492 /// addRegisterOp - Add register operand.
493 // FIXME: Ideally, this would share the implementation with
494 // AsmPrinter::EmitDwarfRegOpPiece.
495 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
496 unsigned SizeInBits, unsigned OffsetInBits) {
497 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
498 int DWReg = RI->getDwarfRegNum(Reg, false);
499 bool isSubRegister = DWReg < 0;
503 // Go up the super-register chain until we hit a valid dwarf register number.
504 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
505 DWReg = RI->getDwarfRegNum(*SR, false);
507 Idx = RI->getSubRegIndex(*SR, Reg);
511 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
512 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
518 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
520 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
521 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
525 bool isPiece = SizeInBits > 0;
526 if (isSubRegister || isPiece) {
527 const unsigned SizeOfByte = 8;
528 unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
529 unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
530 unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
531 unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
532 assert(RegSizeInBits >= SizeInBits && "register smaller than value");
534 if (RegOffsetInBits != PieceOffsetInBits) {
535 // Manually shift the value into place, since the DW_OP_piece
536 // describes the part of the variable, not the position of the
538 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
539 addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
540 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
543 if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
544 assert(PieceSizeInBits > 0 && "piece has zero size");
545 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
546 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
547 addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
549 assert(PieceSizeInBits > 0 && "piece has zero size");
550 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
551 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
556 /// addRegisterOffset - Add register offset.
557 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
559 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
560 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
561 const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
562 if (Reg == TRI->getFrameRegister(*Asm->MF))
563 // If variable offset is based in frame register then use fbreg.
564 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
566 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
568 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
569 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
571 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
574 /// addAddress - Add an address attribute to a die based on the location
576 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
577 const MachineLocation &Location, bool Indirect) {
578 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
580 if (Location.isReg() && !Indirect)
581 addRegisterOpPiece(*Loc, Location.getReg());
583 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
584 if (Indirect && !Location.isReg()) {
585 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
589 // Now attach the location information to the DIE.
590 addBlock(Die, Attribute, Loc);
593 /// addComplexAddress - Start with the address based on the location provided,
594 /// and generate the DWARF information necessary to find the actual variable
595 /// given the extra address information encoded in the DbgVariable, starting
596 /// from the starting location. Add the DWARF information to the die.
598 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
599 dwarf::Attribute Attribute,
600 const MachineLocation &Location) {
601 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
602 unsigned N = DV.getNumAddrElements();
604 if (Location.isReg()) {
605 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
606 // If first address element is OpPlus then emit
607 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
608 addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
610 } else if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpDeref) {
611 addRegisterOpPiece(*Loc, Location.getReg(),
612 DV.getVariable().getPieceSize(),
613 DV.getVariable().getPieceOffset());
616 addRegisterOpPiece(*Loc, Location.getReg());
618 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
621 uint64_t Element = DV.getAddrElement(i);
622 if (Element == DIBuilder::OpPlus) {
623 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
624 addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
626 } else if (Element == DIBuilder::OpDeref) {
627 if (!Location.isReg())
628 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
630 } else if (Element == DIBuilder::OpPiece) {
631 const unsigned SizeOfByte = 8;
632 unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
633 unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
634 // Emit DW_OP_bit_piece Size Offset.
635 assert(PieceSizeInBits > 0 && "piece has zero size");
636 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
637 addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
638 addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
641 llvm_unreachable("unknown DIBuilder Opcode");
644 // Now attach the location information to the DIE.
645 addBlock(Die, Attribute, Loc);
648 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
649 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
650 gives the variable VarName either the struct, or a pointer to the struct, as
651 its type. This is necessary for various behind-the-scenes things the
652 compiler needs to do with by-reference variables in Blocks.
654 However, as far as the original *programmer* is concerned, the variable
655 should still have type 'SomeType', as originally declared.
657 The function getBlockByrefType dives into the __Block_byref_x_VarName
658 struct to find the original type of the variable, which is then assigned to
659 the variable's Debug Information Entry as its real type. So far, so good.
660 However now the debugger will expect the variable VarName to have the type
661 SomeType. So we need the location attribute for the variable to be an
662 expression that explains to the debugger how to navigate through the
663 pointers and struct to find the actual variable of type SomeType.
665 The following function does just that. We start by getting
666 the "normal" location for the variable. This will be the location
667 of either the struct __Block_byref_x_VarName or the pointer to the
668 struct __Block_byref_x_VarName.
670 The struct will look something like:
672 struct __Block_byref_x_VarName {
674 struct __Block_byref_x_VarName *forwarding;
675 ... <various other fields>
677 ... <maybe more fields>
680 If we are given the struct directly (as our starting point) we
681 need to tell the debugger to:
683 1). Add the offset of the forwarding field.
685 2). Follow that pointer to get the real __Block_byref_x_VarName
686 struct to use (the real one may have been copied onto the heap).
688 3). Add the offset for the field VarName, to find the actual variable.
690 If we started with a pointer to the struct, then we need to
691 dereference that pointer first, before the other steps.
692 Translating this into DWARF ops, we will need to append the following
693 to the current location description for the variable:
695 DW_OP_deref -- optional, if we start with a pointer
696 DW_OP_plus_uconst <forward_fld_offset>
698 DW_OP_plus_uconst <varName_fld_offset>
700 That is what this function does. */
702 /// addBlockByrefAddress - Start with the address based on the location
703 /// provided, and generate the DWARF information necessary to find the
704 /// actual Block variable (navigating the Block struct) based on the
705 /// starting location. Add the DWARF information to the die. For
706 /// more information, read large comment just above here.
708 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
709 dwarf::Attribute Attribute,
710 const MachineLocation &Location) {
711 DIType Ty = DV.getType();
713 uint16_t Tag = Ty.getTag();
714 bool isPointer = false;
716 StringRef varName = DV.getName();
718 if (Tag == dwarf::DW_TAG_pointer_type) {
719 DIDerivedType DTy(Ty);
720 TmpTy = resolve(DTy.getTypeDerivedFrom());
724 DICompositeType blockStruct(TmpTy);
726 // Find the __forwarding field and the variable field in the __Block_byref
728 DIArray Fields = blockStruct.getElements();
729 DIDerivedType varField;
730 DIDerivedType forwardingField;
732 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
733 DIDerivedType DT(Fields.getElement(i));
734 StringRef fieldName = DT.getName();
735 if (fieldName == "__forwarding")
736 forwardingField = DT;
737 else if (fieldName == varName)
741 // Get the offsets for the forwarding field and the variable field.
742 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
743 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
745 // Decode the original location, and use that as the start of the byref
746 // variable's location.
747 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
749 if (Location.isReg())
750 addRegisterOpPiece(*Loc, Location.getReg());
752 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
754 // If we started with a pointer to the __Block_byref... struct, then
755 // the first thing we need to do is dereference the pointer (DW_OP_deref).
757 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
759 // Next add the offset for the '__forwarding' field:
760 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
761 // adding the offset if it's 0.
762 if (forwardingFieldOffset > 0) {
763 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
764 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
767 // Now dereference the __forwarding field to get to the real __Block_byref
768 // struct: DW_OP_deref.
769 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
771 // Now that we've got the real __Block_byref... struct, add the offset
772 // for the variable's field to get to the location of the actual variable:
773 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
774 if (varFieldOffset > 0) {
775 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
776 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
779 // Now attach the location information to the DIE.
780 addBlock(Die, Attribute, Loc);
783 /// Return true if type encoding is unsigned.
784 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
785 DIDerivedType DTy(Ty);
786 if (DTy.isDerivedType()) {
787 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
788 // Encode pointer constants as unsigned bytes. This is used at least for
789 // null pointer constant emission.
790 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
791 // here, but accept them for now due to a bug in SROA producing bogus
793 if (T == dwarf::DW_TAG_pointer_type ||
794 T == dwarf::DW_TAG_ptr_to_member_type ||
795 T == dwarf::DW_TAG_reference_type ||
796 T == dwarf::DW_TAG_rvalue_reference_type)
798 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
799 T == dwarf::DW_TAG_volatile_type ||
800 T == dwarf::DW_TAG_restrict_type ||
801 T == dwarf::DW_TAG_enumeration_type);
802 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
803 return isUnsignedDIType(DD, DD->resolve(Deriv));
804 // FIXME: Enums without a fixed underlying type have unknown signedness
805 // here, leading to incorrectly emitted constants.
806 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
811 assert(BTy.isBasicType());
812 unsigned Encoding = BTy.getEncoding();
813 assert((Encoding == dwarf::DW_ATE_unsigned ||
814 Encoding == dwarf::DW_ATE_unsigned_char ||
815 Encoding == dwarf::DW_ATE_signed ||
816 Encoding == dwarf::DW_ATE_signed_char ||
817 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
818 "Unsupported encoding");
819 return (Encoding == dwarf::DW_ATE_unsigned ||
820 Encoding == dwarf::DW_ATE_unsigned_char ||
821 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
824 /// If this type is derived from a base type then return base type size.
825 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
826 unsigned Tag = Ty.getTag();
828 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
829 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
830 Tag != dwarf::DW_TAG_restrict_type)
831 return Ty.getSizeInBits();
833 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
835 // If this type is not derived from any type or the type is a declaration then
836 // take conservative approach.
837 if (!BaseType.isValid() || BaseType.isForwardDecl())
838 return Ty.getSizeInBits();
840 // If this is a derived type, go ahead and get the base type, unless it's a
841 // reference then it's just the size of the field. Pointer types have no need
842 // of this since they're a different type of qualification on the type.
843 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
844 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
845 return Ty.getSizeInBits();
847 if (BaseType.isDerivedType())
848 return getBaseTypeSize(DD, DIDerivedType(BaseType));
850 return BaseType.getSizeInBits();
853 /// addConstantFPValue - Add constant value entry in variable DIE.
854 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
855 assert(MO.isFPImm() && "Invalid machine operand!");
856 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
857 APFloat FPImm = MO.getFPImm()->getValueAPF();
859 // Get the raw data form of the floating point.
860 const APInt FltVal = FPImm.bitcastToAPInt();
861 const char *FltPtr = (const char *)FltVal.getRawData();
863 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
864 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
865 int Incr = (LittleEndian ? 1 : -1);
866 int Start = (LittleEndian ? 0 : NumBytes - 1);
867 int Stop = (LittleEndian ? NumBytes : -1);
869 // Output the constant to DWARF one byte at a time.
870 for (; Start != Stop; Start += Incr)
871 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
873 addBlock(Die, dwarf::DW_AT_const_value, Block);
876 /// addConstantFPValue - Add constant value entry in variable DIE.
877 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
878 // Pass this down to addConstantValue as an unsigned bag of bits.
879 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
882 /// addConstantValue - Add constant value entry in variable DIE.
883 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
884 addConstantValue(Die, CI->getValue(), Ty);
887 /// addConstantValue - Add constant value entry in variable DIE.
888 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
890 assert(MO.isImm() && "Invalid machine operand!");
892 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
895 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
896 // FIXME: This is a bit conservative/simple - it emits negative values always
897 // sign extended to 64 bits rather than minimizing the number of bytes.
898 addUInt(Die, dwarf::DW_AT_const_value,
899 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
902 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
903 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
906 // addConstantValue - Add constant value entry in variable DIE.
907 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
908 unsigned CIBitWidth = Val.getBitWidth();
909 if (CIBitWidth <= 64) {
910 addConstantValue(Die, Unsigned,
911 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
915 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
917 // Get the raw data form of the large APInt.
918 const uint64_t *Ptr64 = Val.getRawData();
920 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
921 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
923 // Output the constant to DWARF one byte at a time.
924 for (int i = 0; i < NumBytes; i++) {
927 c = Ptr64[i / 8] >> (8 * (i & 7));
929 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
930 addUInt(*Block, dwarf::DW_FORM_data1, c);
933 addBlock(Die, dwarf::DW_AT_const_value, Block);
936 /// addTemplateParams - Add template parameters into buffer.
937 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
938 // Add template parameters.
939 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
940 DIDescriptor Element = TParams.getElement(i);
941 if (Element.isTemplateTypeParameter())
942 constructTemplateTypeParameterDIE(Buffer,
943 DITemplateTypeParameter(Element));
944 else if (Element.isTemplateValueParameter())
945 constructTemplateValueParameterDIE(Buffer,
946 DITemplateValueParameter(Element));
950 /// getOrCreateContextDIE - Get context owner's DIE.
951 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
952 if (!Context || Context.isFile())
953 return &getUnitDie();
954 if (Context.isType())
955 return getOrCreateTypeDIE(DIType(Context));
956 if (Context.isNameSpace())
957 return getOrCreateNameSpace(DINameSpace(Context));
958 if (Context.isSubprogram())
959 return getOrCreateSubprogramDIE(DISubprogram(Context));
960 return getDIE(Context);
963 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
964 DIScope Context = resolve(Ty.getContext());
965 DIE *ContextDIE = getOrCreateContextDIE(Context);
967 if (DIE *TyDIE = getDIE(Ty))
971 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
973 constructTypeDIE(TyDIE, Ty);
975 updateAcceleratorTables(Context, Ty, TyDIE);
979 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
981 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
987 assert(Ty == resolve(Ty.getRef()) &&
988 "type was not uniqued, possible ODR violation.");
990 // DW_TAG_restrict_type is not supported in DWARF2
991 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
992 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
994 // Construct the context before querying for the existence of the DIE in case
995 // such construction creates the DIE.
996 DIScope Context = resolve(Ty.getContext());
997 DIE *ContextDIE = getOrCreateContextDIE(Context);
1000 if (DIE *TyDIE = getDIE(Ty))
1004 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1006 updateAcceleratorTables(Context, Ty, TyDIE);
1008 if (Ty.isBasicType())
1009 constructTypeDIE(TyDIE, DIBasicType(Ty));
1010 else if (Ty.isCompositeType()) {
1011 DICompositeType CTy(Ty);
1012 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1013 if (MDString *TypeId = CTy.getIdentifier()) {
1014 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1015 // Skip updating the accelerator tables since this is not the full type.
1018 constructTypeDIE(TyDIE, CTy);
1020 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1021 constructTypeDIE(TyDIE, DIDerivedType(Ty));
1027 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1029 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1030 bool IsImplementation = 0;
1031 if (Ty.isCompositeType()) {
1032 DICompositeType CT(Ty);
1033 // A runtime language of 0 actually means C/C++ and that any
1034 // non-negative value is some version of Objective-C/C++.
1035 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1037 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1038 DD->addAccelType(Ty.getName(), TyDIE, Flags);
1040 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1041 Context.isNameSpace()) &&
1042 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1043 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
1048 /// addType - Add a new type attribute to the specified entity.
1049 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1050 assert(Ty && "Trying to add a type that doesn't exist?");
1052 // Check for pre-existence.
1053 DIEEntry *Entry = getDIEEntry(Ty);
1054 // If it exists then use the existing value.
1056 addDIEEntry(Entity, Attribute, Entry);
1061 DIE *Buffer = getOrCreateTypeDIE(Ty);
1064 Entry = createDIEEntry(*Buffer);
1065 insertDIEEntry(Ty, Entry);
1066 addDIEEntry(Entity, Attribute, Entry);
1069 /// addGlobalName - Add a new global name to the compile unit.
1070 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1071 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1073 std::string FullName = getParentContextString(Context) + Name.str();
1074 GlobalNames[FullName] = &Die;
1077 /// getParentContextString - Walks the metadata parent chain in a language
1078 /// specific manner (using the compile unit language) and returns
1079 /// it as a string. This is done at the metadata level because DIEs may
1080 /// not currently have been added to the parent context and walking the
1081 /// DIEs looking for names is more expensive than walking the metadata.
1082 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1086 // FIXME: Decide whether to implement this for non-C++ languages.
1087 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1091 SmallVector<DIScope, 1> Parents;
1092 while (!Context.isCompileUnit()) {
1093 Parents.push_back(Context);
1094 if (Context.getContext())
1095 Context = resolve(Context.getContext());
1097 // Structure, etc types will have a NULL context if they're at the top
1102 // Reverse iterate over our list to go from the outermost construct to the
1104 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1108 StringRef Name = Ctx.getName();
1109 if (Name.empty() && Ctx.isNameSpace())
1110 Name = "(anonymous namespace)";
1111 if (!Name.empty()) {
1119 /// constructTypeDIE - Construct basic type die from DIBasicType.
1120 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1121 // Get core information.
1122 StringRef Name = BTy.getName();
1123 // Add name if not anonymous or intermediate type.
1125 addString(Buffer, dwarf::DW_AT_name, Name);
1127 // An unspecified type only has a name attribute.
1128 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1131 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1134 uint64_t Size = BTy.getSizeInBits() >> 3;
1135 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1138 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1139 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1140 // Get core information.
1141 StringRef Name = DTy.getName();
1142 uint64_t Size = DTy.getSizeInBits() >> 3;
1143 uint16_t Tag = Buffer.getTag();
1145 // Map to main type, void will not have a type.
1146 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1148 addType(Buffer, FromTy);
1150 // Add name if not anonymous or intermediate type.
1152 addString(Buffer, dwarf::DW_AT_name, Name);
1154 // Add size if non-zero (derived types might be zero-sized.)
1155 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1156 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1158 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1159 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1160 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1161 // Add source line info if available and TyDesc is not a forward declaration.
1162 if (!DTy.isForwardDecl())
1163 addSourceLine(Buffer, DTy);
1166 /// constructSubprogramArguments - Construct function argument DIEs.
1167 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1168 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1169 DIType Ty = resolve(Args.getElement(i));
1171 assert(i == N-1 && "Unspecified parameter must be the last argument");
1172 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1174 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1175 addType(Arg, DIType(Ty));
1176 if (DIType(Ty).isArtificial())
1177 addFlag(Arg, dwarf::DW_AT_artificial);
1182 /// constructTypeDIE - Construct type DIE from DICompositeType.
1183 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1184 // Add name if not anonymous or intermediate type.
1185 StringRef Name = CTy.getName();
1187 uint64_t Size = CTy.getSizeInBits() >> 3;
1188 uint16_t Tag = Buffer.getTag();
1191 case dwarf::DW_TAG_array_type:
1192 constructArrayTypeDIE(Buffer, CTy);
1194 case dwarf::DW_TAG_enumeration_type:
1195 constructEnumTypeDIE(Buffer, CTy);
1197 case dwarf::DW_TAG_subroutine_type: {
1198 // Add return type. A void return won't have a type.
1199 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1200 DIType RTy(resolve(Elements.getElement(0)));
1202 addType(Buffer, RTy);
1204 bool isPrototyped = true;
1205 if (Elements.getNumElements() == 2 &&
1206 !Elements.getElement(1))
1207 isPrototyped = false;
1209 constructSubprogramArguments(Buffer, Elements);
1211 // Add prototype flag if we're dealing with a C language and the
1212 // function has been prototyped.
1213 uint16_t Language = getLanguage();
1215 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1216 Language == dwarf::DW_LANG_ObjC))
1217 addFlag(Buffer, dwarf::DW_AT_prototyped);
1219 if (CTy.isLValueReference())
1220 addFlag(Buffer, dwarf::DW_AT_reference);
1222 if (CTy.isRValueReference())
1223 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1225 case dwarf::DW_TAG_structure_type:
1226 case dwarf::DW_TAG_union_type:
1227 case dwarf::DW_TAG_class_type: {
1228 // Add elements to structure type.
1229 DIArray Elements = CTy.getElements();
1230 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1231 DIDescriptor Element = Elements.getElement(i);
1232 if (Element.isSubprogram())
1233 getOrCreateSubprogramDIE(DISubprogram(Element));
1234 else if (Element.isDerivedType()) {
1235 DIDerivedType DDTy(Element);
1236 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1237 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1238 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1239 dwarf::DW_AT_friend);
1240 } else if (DDTy.isStaticMember()) {
1241 getOrCreateStaticMemberDIE(DDTy);
1243 constructMemberDIE(Buffer, DDTy);
1245 } else if (Element.isObjCProperty()) {
1246 DIObjCProperty Property(Element);
1247 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1248 StringRef PropertyName = Property.getObjCPropertyName();
1249 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1250 if (Property.getType())
1251 addType(ElemDie, Property.getType());
1252 addSourceLine(ElemDie, Property);
1253 StringRef GetterName = Property.getObjCPropertyGetterName();
1254 if (!GetterName.empty())
1255 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1256 StringRef SetterName = Property.getObjCPropertySetterName();
1257 if (!SetterName.empty())
1258 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1259 unsigned PropertyAttributes = 0;
1260 if (Property.isReadOnlyObjCProperty())
1261 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1262 if (Property.isReadWriteObjCProperty())
1263 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1264 if (Property.isAssignObjCProperty())
1265 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1266 if (Property.isRetainObjCProperty())
1267 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1268 if (Property.isCopyObjCProperty())
1269 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1270 if (Property.isNonAtomicObjCProperty())
1271 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1272 if (PropertyAttributes)
1273 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1274 PropertyAttributes);
1276 DIEEntry *Entry = getDIEEntry(Element);
1278 Entry = createDIEEntry(ElemDie);
1279 insertDIEEntry(Element, Entry);
1285 if (CTy.isAppleBlockExtension())
1286 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1288 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1290 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1291 *getOrCreateTypeDIE(ContainingType));
1293 if (CTy.isObjcClassComplete())
1294 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1296 // Add template parameters to a class, structure or union types.
1297 // FIXME: The support isn't in the metadata for this yet.
1298 if (Tag == dwarf::DW_TAG_class_type ||
1299 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1300 addTemplateParams(Buffer, CTy.getTemplateParams());
1308 // Add name if not anonymous or intermediate type.
1310 addString(Buffer, dwarf::DW_AT_name, Name);
1312 if (Tag == dwarf::DW_TAG_enumeration_type ||
1313 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1314 Tag == dwarf::DW_TAG_union_type) {
1315 // Add size if non-zero (derived types might be zero-sized.)
1316 // TODO: Do we care about size for enum forward declarations?
1318 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1319 else if (!CTy.isForwardDecl())
1320 // Add zero size if it is not a forward declaration.
1321 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1323 // If we're a forward decl, say so.
1324 if (CTy.isForwardDecl())
1325 addFlag(Buffer, dwarf::DW_AT_declaration);
1327 // Add source line info if available.
1328 if (!CTy.isForwardDecl())
1329 addSourceLine(Buffer, CTy);
1331 // No harm in adding the runtime language to the declaration.
1332 unsigned RLang = CTy.getRunTimeLang();
1334 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1339 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1340 /// DITemplateTypeParameter.
1341 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1342 DITemplateTypeParameter TP) {
1344 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1345 // Add the type if it exists, it could be void and therefore no type.
1347 addType(ParamDIE, resolve(TP.getType()));
1348 if (!TP.getName().empty())
1349 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1352 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1353 /// DITemplateValueParameter.
1355 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1356 DITemplateValueParameter VP) {
1357 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1359 // Add the type if there is one, template template and template parameter
1360 // packs will not have a type.
1361 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1362 addType(ParamDIE, resolve(VP.getType()));
1363 if (!VP.getName().empty())
1364 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1365 if (Value *Val = VP.getValue()) {
1366 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1367 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1368 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1369 // For declaration non-type template parameters (such as global values and
1371 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1372 addOpAddress(*Loc, Asm->getSymbol(GV));
1373 // Emit DW_OP_stack_value to use the address as the immediate value of the
1374 // parameter, rather than a pointer to it.
1375 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1376 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1377 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1378 assert(isa<MDString>(Val));
1379 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1380 cast<MDString>(Val)->getString());
1381 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1382 assert(isa<MDNode>(Val));
1383 DIArray A(cast<MDNode>(Val));
1384 addTemplateParams(ParamDIE, A);
1389 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1390 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1391 // Construct the context before querying for the existence of the DIE in case
1392 // such construction creates the DIE.
1393 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1395 if (DIE *NDie = getDIE(NS))
1397 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1399 StringRef Name = NS.getName();
1401 addString(NDie, dwarf::DW_AT_name, NS.getName());
1403 Name = "(anonymous namespace)";
1404 DD->addAccelNamespace(Name, NDie);
1405 addGlobalName(Name, NDie, NS.getContext());
1406 addSourceLine(NDie, NS);
1410 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1411 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1412 // Construct the context before querying for the existence of the DIE in case
1413 // such construction creates the DIE (as is the case for member function
1415 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1417 if (DIE *SPDie = getDIE(SP))
1420 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1421 // Add subprogram definitions to the CU die directly.
1422 ContextDIE = &getUnitDie();
1423 // Build the decl now to ensure it precedes the definition.
1424 getOrCreateSubprogramDIE(SPDecl);
1427 // DW_TAG_inlined_subroutine may refer to this DIE.
1428 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1430 // Stop here and fill this in later, depending on whether or not this
1431 // subprogram turns out to have inlined instances or not.
1432 if (SP.isDefinition())
1435 applySubprogramAttributes(SP, SPDie);
1439 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1440 DISubprogram SPDecl = SP.getFunctionDeclaration();
1441 DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1442 applySubprogramAttributes(SP, SPDie);
1443 addGlobalName(SP.getName(), SPDie, Context);
1446 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1447 DIE *DeclDie = nullptr;
1448 StringRef DeclLinkageName;
1449 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1450 DeclDie = getDIE(SPDecl);
1451 assert(DeclDie && "This DIE should've already been constructed when the "
1452 "definition DIE was created in "
1453 "getOrCreateSubprogramDIE");
1454 DeclLinkageName = SPDecl.getLinkageName();
1457 // Add function template parameters.
1458 addTemplateParams(SPDie, SP.getTemplateParams());
1460 // Add the linkage name if we have one and it isn't in the Decl.
1461 StringRef LinkageName = SP.getLinkageName();
1462 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1463 LinkageName == DeclLinkageName) &&
1464 "decl has a linkage name and it is different");
1465 if (!LinkageName.empty() && DeclLinkageName.empty())
1466 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1467 GlobalValue::getRealLinkageName(LinkageName));
1470 // Refer to the function declaration where all the other attributes will be
1472 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1476 // Constructors and operators for anonymous aggregates do not have names.
1477 if (!SP.getName().empty())
1478 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1480 addSourceLine(SPDie, SP);
1482 // Add the prototype if we have a prototype and we have a C like
1484 uint16_t Language = getLanguage();
1485 if (SP.isPrototyped() &&
1486 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1487 Language == dwarf::DW_LANG_ObjC))
1488 addFlag(SPDie, dwarf::DW_AT_prototyped);
1490 DISubroutineType SPTy = SP.getType();
1491 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1492 "the type of a subprogram should be a subroutine");
1494 DITypeArray Args = SPTy.getTypeArray();
1495 // Add a return type. If this is a type like a C/C++ void type we don't add a
1497 if (resolve(Args.getElement(0)))
1498 addType(SPDie, DIType(resolve(Args.getElement(0))));
1500 unsigned VK = SP.getVirtuality();
1502 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1503 DIELoc *Block = getDIELoc();
1504 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1505 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1506 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1507 ContainingTypeMap.insert(
1508 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1511 if (!SP.isDefinition()) {
1512 addFlag(SPDie, dwarf::DW_AT_declaration);
1514 // Add arguments. Do not add arguments for subprogram definition. They will
1515 // be handled while processing variables.
1516 constructSubprogramArguments(SPDie, Args);
1519 if (SP.isArtificial())
1520 addFlag(SPDie, dwarf::DW_AT_artificial);
1522 if (!SP.isLocalToUnit())
1523 addFlag(SPDie, dwarf::DW_AT_external);
1525 if (SP.isOptimized())
1526 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1528 if (unsigned isa = Asm->getISAEncoding()) {
1529 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1532 if (SP.isLValueReference())
1533 addFlag(SPDie, dwarf::DW_AT_reference);
1535 if (SP.isRValueReference())
1536 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1538 if (SP.isProtected())
1539 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1540 dwarf::DW_ACCESS_protected);
1541 else if (SP.isPrivate())
1542 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1543 dwarf::DW_ACCESS_private);
1544 else if (SP.isPublic())
1545 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1546 dwarf::DW_ACCESS_public);
1548 if (SP.isExplicit())
1549 addFlag(SPDie, dwarf::DW_AT_explicit);
1552 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1554 StringRef Name = Var.getName();
1556 addString(VariableDie, dwarf::DW_AT_name, Name);
1557 addSourceLine(VariableDie, Var.getVariable());
1558 addType(VariableDie, Var.getType());
1559 if (Var.isArtificial())
1560 addFlag(VariableDie, dwarf::DW_AT_artificial);
1563 // Return const expression if value is a GEP to access merged global
1565 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1566 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1567 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1568 if (!CE || CE->getNumOperands() != 3 ||
1569 CE->getOpcode() != Instruction::GetElementPtr)
1572 // First operand points to a global struct.
1573 Value *Ptr = CE->getOperand(0);
1574 if (!isa<GlobalValue>(Ptr) ||
1575 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1578 // Second operand is zero.
1579 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1580 if (!CI || !CI->isZero())
1583 // Third operand is offset.
1584 if (!isa<ConstantInt>(CE->getOperand(2)))
1590 /// createGlobalVariableDIE - create global variable DIE.
1591 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1592 // Check for pre-existence.
1596 assert(GV.isGlobalVariable());
1598 DIScope GVContext = GV.getContext();
1599 DIType GTy = DD->resolve(GV.getType());
1601 // If this is a static data member definition, some attributes belong
1602 // to the declaration DIE.
1603 DIE *VariableDIE = nullptr;
1604 bool IsStaticMember = false;
1605 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1606 if (SDMDecl.Verify()) {
1607 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1608 // We need the declaration DIE that is in the static member's class.
1609 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1610 IsStaticMember = true;
1613 // If this is not a static data member definition, create the variable
1614 // DIE and add the initial set of attributes to it.
1616 // Construct the context before querying for the existence of the DIE in
1617 // case such construction creates the DIE.
1618 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1621 VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1623 // Add name and type.
1624 addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1625 addType(*VariableDIE, GTy);
1627 // Add scoping info.
1628 if (!GV.isLocalToUnit())
1629 addFlag(*VariableDIE, dwarf::DW_AT_external);
1631 // Add line number info.
1632 addSourceLine(*VariableDIE, GV);
1636 bool addToAccelTable = false;
1637 DIE *VariableSpecDIE = nullptr;
1638 bool isGlobalVariable = GV.getGlobal() != nullptr;
1639 if (isGlobalVariable) {
1640 addToAccelTable = true;
1641 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1642 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1643 if (GV.getGlobal()->isThreadLocal()) {
1644 // FIXME: Make this work with -gsplit-dwarf.
1645 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1646 assert((PointerSize == 4 || PointerSize == 8) &&
1647 "Add support for other sizes if necessary");
1648 // Based on GCC's support for TLS:
1649 if (!DD->useSplitDwarf()) {
1650 // 1) Start with a constNu of the appropriate pointer size
1651 addUInt(*Loc, dwarf::DW_FORM_data1,
1652 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1653 // 2) containing the (relocated) offset of the TLS variable
1654 // within the module's TLS block.
1655 addExpr(*Loc, dwarf::DW_FORM_udata,
1656 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1658 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1659 addUInt(*Loc, dwarf::DW_FORM_udata,
1660 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1662 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1663 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1665 DD->addArangeLabel(SymbolCU(this, Sym));
1666 addOpAddress(*Loc, Sym);
1668 // Do not create specification DIE if context is either compile unit
1670 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1671 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1672 // Create specification DIE.
1673 VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
1674 addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
1675 addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1676 // A static member's declaration is already flagged as such.
1677 if (!SDMDecl.Verify())
1678 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1680 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1682 // Add the linkage name.
1683 StringRef LinkageName = GV.getLinkageName();
1684 if (!LinkageName.empty())
1685 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1686 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1688 addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1690 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1691 : dwarf::DW_AT_MIPS_linkage_name,
1692 GlobalValue::getRealLinkageName(LinkageName));
1693 } else if (const ConstantInt *CI =
1694 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1695 // AT_const_value was added when the static member was created. To avoid
1696 // emitting AT_const_value multiple times, we only add AT_const_value when
1697 // it is not a static member.
1698 if (!IsStaticMember)
1699 addConstantValue(*VariableDIE, CI, GTy);
1700 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1701 addToAccelTable = true;
1702 // GV is a merged global.
1703 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1704 Value *Ptr = CE->getOperand(0);
1705 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1706 DD->addArangeLabel(SymbolCU(this, Sym));
1707 addOpAddress(*Loc, Sym);
1708 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1709 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1710 addUInt(*Loc, dwarf::DW_FORM_udata,
1711 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1712 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1713 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1716 if (addToAccelTable) {
1717 DIE &AddrDIE = VariableSpecDIE ? *VariableSpecDIE : *VariableDIE;
1718 DD->addAccelName(GV.getName(), AddrDIE);
1720 // If the linkage name is different than the name, go ahead and output
1721 // that as well into the name table.
1722 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1723 DD->addAccelName(GV.getLinkageName(), AddrDIE);
1726 addGlobalName(GV.getName(), VariableSpecDIE ? *VariableSpecDIE : *VariableDIE,
1730 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1731 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1732 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1733 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1735 // The LowerBound value defines the lower bounds which is typically zero for
1736 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1737 // Count == -1 then the array is unbounded and we do not emit
1738 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1739 // Count == 0, then the array has zero elements in which case we do not emit
1741 int64_t LowerBound = SR.getLo();
1742 int64_t DefaultLowerBound = getDefaultLowerBound();
1743 int64_t Count = SR.getCount();
1745 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1746 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1748 if (Count != -1 && Count != 0)
1749 // FIXME: An unbounded array should reference the expression that defines
1751 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1752 LowerBound + Count - 1);
1755 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1756 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1758 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1760 // Emit the element type.
1761 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1763 // Get an anonymous type for index type.
1764 // FIXME: This type should be passed down from the front end
1765 // as different languages may have different sizes for indexes.
1766 DIE *IdxTy = getIndexTyDie();
1768 // Construct an integer type to use for indexes.
1769 IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1770 addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1771 addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1772 addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1773 dwarf::DW_ATE_unsigned);
1774 setIndexTyDie(IdxTy);
1777 // Add subranges to array type.
1778 DIArray Elements = CTy.getElements();
1779 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1780 DIDescriptor Element = Elements.getElement(i);
1781 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1782 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1786 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1787 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1788 DIArray Elements = CTy.getElements();
1790 // Add enumerators to enumeration type.
1791 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1792 DIEnumerator Enum(Elements.getElement(i));
1793 if (Enum.isEnumerator()) {
1794 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1795 StringRef Name = Enum.getName();
1796 addString(Enumerator, dwarf::DW_AT_name, Name);
1797 int64_t Value = Enum.getEnumValue();
1798 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1802 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1804 addType(Buffer, DTy);
1805 addFlag(Buffer, dwarf::DW_AT_enum_class);
1809 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1811 void DwarfUnit::constructContainingTypeDIEs() {
1812 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1813 CE = ContainingTypeMap.end();
1815 DIE &SPDie = *CI->first;
1816 DIDescriptor D(CI->second);
1819 DIE *NDie = getDIE(D);
1822 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1826 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1827 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1829 auto D = constructVariableDIEImpl(DV, Abstract);
1834 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1836 // Define variable debug information entry.
1837 auto VariableDie = make_unique<DIE>(DV.getTag());
1840 applyVariableAttributes(DV, *VariableDie);
1844 // Add variable address.
1846 unsigned Offset = DV.getDotDebugLocOffset();
1847 if (Offset != ~0U) {
1848 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1852 // Check if variable is described by a DBG_VALUE instruction.
1853 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1854 assert(DVInsn->getNumOperands() == 3);
1855 if (DVInsn->getOperand(0).isReg()) {
1856 const MachineOperand RegOp = DVInsn->getOperand(0);
1857 // If the second operand is an immediate, this is an indirect value.
1858 if (DVInsn->getOperand(1).isImm()) {
1859 MachineLocation Location(RegOp.getReg(),
1860 DVInsn->getOperand(1).getImm());
1861 addVariableAddress(DV, *VariableDie, Location);
1862 } else if (RegOp.getReg())
1863 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1864 } else if (DVInsn->getOperand(0).isImm())
1865 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1866 else if (DVInsn->getOperand(0).isFPImm())
1867 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1868 else if (DVInsn->getOperand(0).isCImm())
1869 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1875 // .. else use frame index.
1876 int FI = DV.getFrameIndex();
1878 unsigned FrameReg = 0;
1879 const TargetFrameLowering *TFI =
1880 Asm->TM.getSubtargetImpl()->getFrameLowering();
1881 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1882 MachineLocation Location(FrameReg, Offset);
1883 addVariableAddress(DV, *VariableDie, Location);
1889 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1890 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1891 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1892 StringRef Name = DT.getName();
1894 addString(MemberDie, dwarf::DW_AT_name, Name);
1896 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1898 addSourceLine(MemberDie, DT);
1900 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1902 // For C++, virtual base classes are not at fixed offset. Use following
1903 // expression to extract appropriate offset from vtable.
1904 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1906 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1907 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1908 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1909 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1910 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1911 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1912 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1913 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1915 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1917 uint64_t Size = DT.getSizeInBits();
1918 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1919 uint64_t OffsetInBytes;
1921 if (Size != FieldSize) {
1922 // Handle bitfield, assume bytes are 8 bits.
1923 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1924 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1926 uint64_t Offset = DT.getOffsetInBits();
1927 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1928 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1929 uint64_t FieldOffset = (HiMark - FieldSize);
1930 Offset -= FieldOffset;
1932 // Maybe we need to work from the other end.
1933 if (Asm->getDataLayout().isLittleEndian())
1934 Offset = FieldSize - (Offset + Size);
1935 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1937 // Here DW_AT_data_member_location points to the anonymous
1938 // field that includes this bit field.
1939 OffsetInBytes = FieldOffset >> 3;
1941 // This is not a bitfield.
1942 OffsetInBytes = DT.getOffsetInBits() >> 3;
1944 if (DD->getDwarfVersion() <= 2) {
1945 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1946 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1947 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1948 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1950 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1954 if (DT.isProtected())
1955 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1956 dwarf::DW_ACCESS_protected);
1957 else if (DT.isPrivate())
1958 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1959 dwarf::DW_ACCESS_private);
1960 // Otherwise C++ member and base classes are considered public.
1961 else if (DT.isPublic())
1962 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1963 dwarf::DW_ACCESS_public);
1965 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1966 dwarf::DW_VIRTUALITY_virtual);
1968 // Objective-C properties.
1969 if (MDNode *PNode = DT.getObjCProperty())
1970 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1971 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1974 if (DT.isArtificial())
1975 addFlag(MemberDie, dwarf::DW_AT_artificial);
1978 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1979 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1983 // Construct the context before querying for the existence of the DIE in case
1984 // such construction creates the DIE.
1985 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1986 assert(dwarf::isType(ContextDIE->getTag()) &&
1987 "Static member should belong to a type.");
1989 if (DIE *StaticMemberDIE = getDIE(DT))
1990 return StaticMemberDIE;
1992 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1994 DIType Ty = resolve(DT.getTypeDerivedFrom());
1996 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1997 addType(StaticMemberDIE, Ty);
1998 addSourceLine(StaticMemberDIE, DT);
1999 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2000 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2002 // FIXME: We could omit private if the parent is a class_type, and
2003 // public if the parent is something else.
2004 if (DT.isProtected())
2005 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2006 dwarf::DW_ACCESS_protected);
2007 else if (DT.isPrivate())
2008 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2009 dwarf::DW_ACCESS_private);
2010 else if (DT.isPublic())
2011 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2012 dwarf::DW_ACCESS_public);
2014 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2015 addConstantValue(StaticMemberDIE, CI, Ty);
2016 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2017 addConstantFPValue(StaticMemberDIE, CFP);
2019 return &StaticMemberDIE;
2022 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2023 Asm->OutStreamer.AddComment("DWARF version number");
2024 Asm->EmitInt16(DD->getDwarfVersion());
2025 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2026 // We share one abbreviations table across all units so it's always at the
2027 // start of the section. Use a relocatable offset where needed to ensure
2028 // linking doesn't invalidate that offset.
2030 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2032 // Use a constant value when no symbol is provided.
2034 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2035 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2038 void DwarfCompileUnit::addRange(RangeSpan Range) {
2039 // Only add a range for this unit if we're emitting full debug.
2040 if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2041 bool SameAsPrevCU = this == DD->getPrevCU();
2042 DD->setPrevCU(this);
2043 // If we have no current ranges just add the range and return, otherwise,
2044 // check the current section and CU against the previous section and CU we
2045 // emitted into and the subprogram was contained within. If these are the
2046 // same then extend our current range, otherwise add this as a new range.
2047 if (CURanges.empty() || !SameAsPrevCU ||
2048 (&CURanges.back().getEnd()->getSection() !=
2049 &Range.getEnd()->getSection())) {
2050 CURanges.push_back(Range);
2054 CURanges.back().setEnd(Range.getEnd());
2058 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2059 // Define start line table label for each Compile Unit.
2060 MCSymbol *LineTableStartSym =
2061 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2063 stmtListIndex = UnitDie.getValues().size();
2065 // DW_AT_stmt_list is a offset of line number information for this
2066 // compile unit in debug_line section. For split dwarf this is
2067 // left in the skeleton CU and so not included.
2068 // The line table entries are not always emitted in assembly, so it
2069 // is not okay to use line_table_start here.
2070 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2071 addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
2073 addSectionDelta(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
2074 DwarfLineSectionSym);
2077 void DwarfCompileUnit::applyStmtList(DIE &D) {
2078 D.addValue(dwarf::DW_AT_stmt_list,
2079 UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
2080 UnitDie.getValues()[stmtListIndex]);
2083 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2084 DwarfUnit::emitHeader(ASectionSym);
2085 Asm->OutStreamer.AddComment("Type Signature");
2086 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2087 Asm->OutStreamer.AddComment("Type DIE Offset");
2088 // In a skeleton type unit there is no type DIE so emit a zero offset.
2089 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2090 sizeof(Ty->getOffset()));
2093 void DwarfTypeUnit::initSection(const MCSection *Section) {
2094 assert(!this->Section);
2095 this->Section = Section;
2096 // Since each type unit is contained in its own COMDAT section, the begin
2097 // label and the section label are the same. Using the begin label emission in
2098 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2099 // the only other alternative of lazily constructing start-of-section labels
2100 // and storing a mapping in DwarfDebug (or AsmPrinter).
2101 this->SectionSym = this->LabelBegin =
2102 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2104 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());