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 MCSymbol *StringPool = DU->getStringPool().getSectionSymbol();
230 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
232 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
233 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
236 /// addExpr - Add a Dwarf expression attribute data and value.
238 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
239 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
240 Die.addValue((dwarf::Attribute)0, Form, Value);
243 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
245 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
247 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
248 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
249 : dwarf::DW_FORM_data4;
250 Die.addValue(Attribute, Form, Value);
253 /// addLabel - Add a Dwarf label attribute data and value.
255 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
256 const MCSymbol *Label) {
257 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
258 Die.addValue(Attribute, Form, Value);
261 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
262 addLabel(Die, (dwarf::Attribute)0, Form, Label);
265 /// addSectionLabel - Add a Dwarf section label attribute data and value.
267 void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
268 const MCSymbol *Label) {
269 if (DD->getDwarfVersion() >= 4)
270 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
272 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
275 /// addSectionOffset - Add an offset into a section attribute data and value.
277 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
279 if (DD->getDwarfVersion() >= 4)
280 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
282 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
285 /// addLabelAddress - Add a dwarf label attribute data and value using
286 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
288 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
289 const MCSymbol *Label) {
291 if (!DD->useSplitDwarf())
292 return addLocalLabelAddress(Die, Attribute, Label);
295 DD->addArangeLabel(SymbolCU(this, Label));
297 unsigned idx = DD->getAddressPool().getIndex(Label);
298 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
299 Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
302 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
303 dwarf::Attribute Attribute,
304 const MCSymbol *Label) {
306 DD->addArangeLabel(SymbolCU(this, Label));
308 Die.addValue(Attribute, dwarf::DW_FORM_addr,
309 Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
310 : new (DIEValueAllocator) DIEInteger(0));
313 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
314 // If we print assembly, we can't separate .file entries according to
315 // compile units. Thus all files will belong to the default compile unit.
317 // FIXME: add a better feature test than hasRawTextSupport. Even better,
318 // extend .file to support this.
319 return Asm->OutStreamer.EmitDwarfFileDirective(
320 0, DirName, FileName,
321 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
324 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
325 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
326 : getCU().getOrCreateSourceID(FileName, DirName);
329 /// addOpAddress - Add a dwarf op address data and value using the
330 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
332 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
333 if (!DD->useSplitDwarf()) {
334 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
335 addLabel(Die, dwarf::DW_FORM_udata, Sym);
337 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
338 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
339 DD->getAddressPool().getIndex(Sym));
343 /// addSectionDelta - Add a section label delta attribute data and value.
345 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
346 const MCSymbol *Hi, const MCSymbol *Lo) {
347 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
348 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
349 : dwarf::DW_FORM_data4,
353 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
354 const MCSymbol *Hi, const MCSymbol *Lo) {
355 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
356 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
359 /// addDIEEntry - Add a DIE attribute data and value.
361 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
362 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
365 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
366 // Flag the type unit reference as a declaration so that if it contains
367 // members (implicit special members, static data member definitions, member
368 // declarations for definitions in this CU, etc) consumers don't get confused
369 // and think this is a full definition.
370 addFlag(Die, dwarf::DW_AT_declaration);
372 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
373 new (DIEValueAllocator) DIETypeSignature(Type));
376 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
378 const DIE *DieCU = Die.getUnitOrNull();
379 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
381 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
382 DieCU = &getUnitDie();
384 EntryCU = &getUnitDie();
385 Die.addValue(Attribute,
386 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
390 /// Create a DIE with the given Tag, add the DIE to its parent, and
391 /// call insertDIE if MD is not null.
392 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
393 assert(Tag != dwarf::DW_TAG_auto_variable &&
394 Tag != dwarf::DW_TAG_arg_variable);
395 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
396 DIE &Die = *Parent.getChildren().back();
402 /// addBlock - Add block data.
404 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
405 Loc->ComputeSize(Asm);
406 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
407 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
410 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
412 Block->ComputeSize(Asm);
413 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
414 Die.addValue(Attribute, Block->BestForm(), Block);
417 /// addSourceLine - Add location information to specified debug information
419 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
420 StringRef Directory) {
424 unsigned FileID = getOrCreateSourceID(File, Directory);
425 assert(FileID && "Invalid file id");
426 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
427 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
430 /// addSourceLine - Add location information to specified debug information
432 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
433 assert(V.isVariable());
435 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
436 V.getContext().getDirectory());
439 /// addSourceLine - Add location information to specified debug information
441 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
442 assert(G.isGlobalVariable());
444 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
447 /// addSourceLine - Add location information to specified debug information
449 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
450 assert(SP.isSubprogram());
452 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
455 /// addSourceLine - Add location information to specified debug information
457 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
460 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
463 /// addSourceLine - Add location information to specified debug information
465 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
466 assert(Ty.isObjCProperty());
468 DIFile File = Ty.getFile();
469 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
470 File.getDirectory());
473 /// addSourceLine - Add location information to specified debug information
475 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
478 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
481 /// addVariableAddress - Add DW_AT_location attribute for a
482 /// DbgVariable based on provided MachineLocation.
483 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
484 MachineLocation Location) {
485 if (DV.variableHasComplexAddress())
486 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
487 else if (DV.isBlockByrefVariable())
488 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
490 addAddress(Die, dwarf::DW_AT_location, Location,
491 DV.getVariable().isIndirect());
494 /// addRegisterOp - Add register operand.
495 // FIXME: Ideally, this would share the implementation with
496 // AsmPrinter::EmitDwarfRegOpPiece.
497 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
498 unsigned SizeInBits, unsigned OffsetInBits) {
499 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
500 int DWReg = RI->getDwarfRegNum(Reg, false);
501 bool isSubRegister = DWReg < 0;
505 // Go up the super-register chain until we hit a valid dwarf register number.
506 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
507 DWReg = RI->getDwarfRegNum(*SR, false);
509 Idx = RI->getSubRegIndex(*SR, Reg);
513 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
514 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
520 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
522 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
523 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
527 bool isPiece = SizeInBits > 0;
528 if (isSubRegister || isPiece) {
529 const unsigned SizeOfByte = 8;
530 unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
531 unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
532 unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
533 unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
534 assert(RegSizeInBits >= SizeInBits && "register smaller than value");
536 if (RegOffsetInBits != PieceOffsetInBits) {
537 // Manually shift the value into place, since the DW_OP_piece
538 // describes the part of the variable, not the position of the
540 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
541 addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
542 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
545 if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
546 assert(PieceSizeInBits > 0 && "piece has zero size");
547 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
548 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
549 addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
551 assert(PieceSizeInBits > 0 && "piece has zero size");
552 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
553 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
558 /// addRegisterOffset - Add register offset.
559 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
561 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
562 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
563 const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
564 if (Reg == TRI->getFrameRegister(*Asm->MF))
565 // If variable offset is based in frame register then use fbreg.
566 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
568 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
570 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
571 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
573 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
576 /// addAddress - Add an address attribute to a die based on the location
578 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
579 const MachineLocation &Location, bool Indirect) {
580 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
582 if (Location.isReg() && !Indirect)
583 addRegisterOpPiece(*Loc, Location.getReg());
585 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
586 if (Indirect && !Location.isReg()) {
587 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
591 // Now attach the location information to the DIE.
592 addBlock(Die, Attribute, Loc);
595 /// addComplexAddress - Start with the address based on the location provided,
596 /// and generate the DWARF information necessary to find the actual variable
597 /// given the extra address information encoded in the DbgVariable, starting
598 /// from the starting location. Add the DWARF information to the die.
600 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
601 dwarf::Attribute Attribute,
602 const MachineLocation &Location) {
603 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
604 unsigned N = DV.getNumAddrElements();
606 if (Location.isReg()) {
607 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
608 // If first address element is OpPlus then emit
609 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
610 addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
612 } else if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpDeref) {
613 addRegisterOpPiece(*Loc, Location.getReg(),
614 DV.getVariable().getPieceSize(),
615 DV.getVariable().getPieceOffset());
618 addRegisterOpPiece(*Loc, Location.getReg());
620 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
623 uint64_t Element = DV.getAddrElement(i);
624 if (Element == DIBuilder::OpPlus) {
625 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
626 addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
628 } else if (Element == DIBuilder::OpDeref) {
629 if (!Location.isReg())
630 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
632 } else if (Element == DIBuilder::OpPiece) {
633 const unsigned SizeOfByte = 8;
634 unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
635 unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
636 // Emit DW_OP_bit_piece Size Offset.
637 assert(PieceSizeInBits > 0 && "piece has zero size");
638 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
639 addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
640 addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
643 llvm_unreachable("unknown DIBuilder Opcode");
646 // Now attach the location information to the DIE.
647 addBlock(Die, Attribute, Loc);
650 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
651 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
652 gives the variable VarName either the struct, or a pointer to the struct, as
653 its type. This is necessary for various behind-the-scenes things the
654 compiler needs to do with by-reference variables in Blocks.
656 However, as far as the original *programmer* is concerned, the variable
657 should still have type 'SomeType', as originally declared.
659 The function getBlockByrefType dives into the __Block_byref_x_VarName
660 struct to find the original type of the variable, which is then assigned to
661 the variable's Debug Information Entry as its real type. So far, so good.
662 However now the debugger will expect the variable VarName to have the type
663 SomeType. So we need the location attribute for the variable to be an
664 expression that explains to the debugger how to navigate through the
665 pointers and struct to find the actual variable of type SomeType.
667 The following function does just that. We start by getting
668 the "normal" location for the variable. This will be the location
669 of either the struct __Block_byref_x_VarName or the pointer to the
670 struct __Block_byref_x_VarName.
672 The struct will look something like:
674 struct __Block_byref_x_VarName {
676 struct __Block_byref_x_VarName *forwarding;
677 ... <various other fields>
679 ... <maybe more fields>
682 If we are given the struct directly (as our starting point) we
683 need to tell the debugger to:
685 1). Add the offset of the forwarding field.
687 2). Follow that pointer to get the real __Block_byref_x_VarName
688 struct to use (the real one may have been copied onto the heap).
690 3). Add the offset for the field VarName, to find the actual variable.
692 If we started with a pointer to the struct, then we need to
693 dereference that pointer first, before the other steps.
694 Translating this into DWARF ops, we will need to append the following
695 to the current location description for the variable:
697 DW_OP_deref -- optional, if we start with a pointer
698 DW_OP_plus_uconst <forward_fld_offset>
700 DW_OP_plus_uconst <varName_fld_offset>
702 That is what this function does. */
704 /// addBlockByrefAddress - Start with the address based on the location
705 /// provided, and generate the DWARF information necessary to find the
706 /// actual Block variable (navigating the Block struct) based on the
707 /// starting location. Add the DWARF information to the die. For
708 /// more information, read large comment just above here.
710 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
711 dwarf::Attribute Attribute,
712 const MachineLocation &Location) {
713 DIType Ty = DV.getType();
715 uint16_t Tag = Ty.getTag();
716 bool isPointer = false;
718 StringRef varName = DV.getName();
720 if (Tag == dwarf::DW_TAG_pointer_type) {
721 DIDerivedType DTy(Ty);
722 TmpTy = resolve(DTy.getTypeDerivedFrom());
726 DICompositeType blockStruct(TmpTy);
728 // Find the __forwarding field and the variable field in the __Block_byref
730 DIArray Fields = blockStruct.getElements();
731 DIDerivedType varField;
732 DIDerivedType forwardingField;
734 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
735 DIDerivedType DT(Fields.getElement(i));
736 StringRef fieldName = DT.getName();
737 if (fieldName == "__forwarding")
738 forwardingField = DT;
739 else if (fieldName == varName)
743 // Get the offsets for the forwarding field and the variable field.
744 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
745 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
747 // Decode the original location, and use that as the start of the byref
748 // variable's location.
749 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
751 if (Location.isReg())
752 addRegisterOpPiece(*Loc, Location.getReg());
754 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
756 // If we started with a pointer to the __Block_byref... struct, then
757 // the first thing we need to do is dereference the pointer (DW_OP_deref).
759 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
761 // Next add the offset for the '__forwarding' field:
762 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
763 // adding the offset if it's 0.
764 if (forwardingFieldOffset > 0) {
765 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
766 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
769 // Now dereference the __forwarding field to get to the real __Block_byref
770 // struct: DW_OP_deref.
771 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
773 // Now that we've got the real __Block_byref... struct, add the offset
774 // for the variable's field to get to the location of the actual variable:
775 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
776 if (varFieldOffset > 0) {
777 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
778 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
781 // Now attach the location information to the DIE.
782 addBlock(Die, Attribute, Loc);
785 /// Return true if type encoding is unsigned.
786 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
787 DIDerivedType DTy(Ty);
788 if (DTy.isDerivedType()) {
789 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
790 // Encode pointer constants as unsigned bytes. This is used at least for
791 // null pointer constant emission.
792 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
793 // here, but accept them for now due to a bug in SROA producing bogus
795 if (T == dwarf::DW_TAG_pointer_type ||
796 T == dwarf::DW_TAG_ptr_to_member_type ||
797 T == dwarf::DW_TAG_reference_type ||
798 T == dwarf::DW_TAG_rvalue_reference_type)
800 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
801 T == dwarf::DW_TAG_volatile_type ||
802 T == dwarf::DW_TAG_restrict_type ||
803 T == dwarf::DW_TAG_enumeration_type);
804 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
805 return isUnsignedDIType(DD, DD->resolve(Deriv));
806 // FIXME: Enums without a fixed underlying type have unknown signedness
807 // here, leading to incorrectly emitted constants.
808 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
813 assert(BTy.isBasicType());
814 unsigned Encoding = BTy.getEncoding();
815 assert((Encoding == dwarf::DW_ATE_unsigned ||
816 Encoding == dwarf::DW_ATE_unsigned_char ||
817 Encoding == dwarf::DW_ATE_signed ||
818 Encoding == dwarf::DW_ATE_signed_char ||
819 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
820 "Unsupported encoding");
821 return (Encoding == dwarf::DW_ATE_unsigned ||
822 Encoding == dwarf::DW_ATE_unsigned_char ||
823 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
826 /// If this type is derived from a base type then return base type size.
827 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
828 unsigned Tag = Ty.getTag();
830 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
831 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
832 Tag != dwarf::DW_TAG_restrict_type)
833 return Ty.getSizeInBits();
835 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
837 // If this type is not derived from any type or the type is a declaration then
838 // take conservative approach.
839 if (!BaseType.isValid() || BaseType.isForwardDecl())
840 return Ty.getSizeInBits();
842 // If this is a derived type, go ahead and get the base type, unless it's a
843 // reference then it's just the size of the field. Pointer types have no need
844 // of this since they're a different type of qualification on the type.
845 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
846 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
847 return Ty.getSizeInBits();
849 if (BaseType.isDerivedType())
850 return getBaseTypeSize(DD, DIDerivedType(BaseType));
852 return BaseType.getSizeInBits();
855 /// addConstantFPValue - Add constant value entry in variable DIE.
856 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
857 assert(MO.isFPImm() && "Invalid machine operand!");
858 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
859 APFloat FPImm = MO.getFPImm()->getValueAPF();
861 // Get the raw data form of the floating point.
862 const APInt FltVal = FPImm.bitcastToAPInt();
863 const char *FltPtr = (const char *)FltVal.getRawData();
865 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
866 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
867 int Incr = (LittleEndian ? 1 : -1);
868 int Start = (LittleEndian ? 0 : NumBytes - 1);
869 int Stop = (LittleEndian ? NumBytes : -1);
871 // Output the constant to DWARF one byte at a time.
872 for (; Start != Stop; Start += Incr)
873 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
875 addBlock(Die, dwarf::DW_AT_const_value, Block);
878 /// addConstantFPValue - Add constant value entry in variable DIE.
879 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
880 // Pass this down to addConstantValue as an unsigned bag of bits.
881 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
884 /// addConstantValue - Add constant value entry in variable DIE.
885 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
886 addConstantValue(Die, CI->getValue(), Ty);
889 /// addConstantValue - Add constant value entry in variable DIE.
890 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
892 assert(MO.isImm() && "Invalid machine operand!");
894 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
897 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
898 // FIXME: This is a bit conservative/simple - it emits negative values always
899 // sign extended to 64 bits rather than minimizing the number of bytes.
900 addUInt(Die, dwarf::DW_AT_const_value,
901 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
904 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
905 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
908 // addConstantValue - Add constant value entry in variable DIE.
909 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
910 unsigned CIBitWidth = Val.getBitWidth();
911 if (CIBitWidth <= 64) {
912 addConstantValue(Die, Unsigned,
913 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
917 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
919 // Get the raw data form of the large APInt.
920 const uint64_t *Ptr64 = Val.getRawData();
922 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
923 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
925 // Output the constant to DWARF one byte at a time.
926 for (int i = 0; i < NumBytes; i++) {
929 c = Ptr64[i / 8] >> (8 * (i & 7));
931 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
932 addUInt(*Block, dwarf::DW_FORM_data1, c);
935 addBlock(Die, dwarf::DW_AT_const_value, Block);
938 /// addTemplateParams - Add template parameters into buffer.
939 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
940 // Add template parameters.
941 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
942 DIDescriptor Element = TParams.getElement(i);
943 if (Element.isTemplateTypeParameter())
944 constructTemplateTypeParameterDIE(Buffer,
945 DITemplateTypeParameter(Element));
946 else if (Element.isTemplateValueParameter())
947 constructTemplateValueParameterDIE(Buffer,
948 DITemplateValueParameter(Element));
952 /// getOrCreateContextDIE - Get context owner's DIE.
953 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
954 if (!Context || Context.isFile())
955 return &getUnitDie();
956 if (Context.isType())
957 return getOrCreateTypeDIE(DIType(Context));
958 if (Context.isNameSpace())
959 return getOrCreateNameSpace(DINameSpace(Context));
960 if (Context.isSubprogram())
961 return getOrCreateSubprogramDIE(DISubprogram(Context));
962 return getDIE(Context);
965 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
966 DIScope Context = resolve(Ty.getContext());
967 DIE *ContextDIE = getOrCreateContextDIE(Context);
969 if (DIE *TyDIE = getDIE(Ty))
973 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
975 constructTypeDIE(TyDIE, Ty);
977 updateAcceleratorTables(Context, Ty, TyDIE);
981 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
983 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
989 assert(Ty == resolve(Ty.getRef()) &&
990 "type was not uniqued, possible ODR violation.");
992 // DW_TAG_restrict_type is not supported in DWARF2
993 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
994 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
996 // Construct the context before querying for the existence of the DIE in case
997 // such construction creates the DIE.
998 DIScope Context = resolve(Ty.getContext());
999 DIE *ContextDIE = getOrCreateContextDIE(Context);
1002 if (DIE *TyDIE = getDIE(Ty))
1006 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1008 updateAcceleratorTables(Context, Ty, TyDIE);
1010 if (Ty.isBasicType())
1011 constructTypeDIE(TyDIE, DIBasicType(Ty));
1012 else if (Ty.isCompositeType()) {
1013 DICompositeType CTy(Ty);
1014 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1015 if (MDString *TypeId = CTy.getIdentifier()) {
1016 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1017 // Skip updating the accelerator tables since this is not the full type.
1020 constructTypeDIE(TyDIE, CTy);
1022 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1023 constructTypeDIE(TyDIE, DIDerivedType(Ty));
1029 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1031 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1032 bool IsImplementation = 0;
1033 if (Ty.isCompositeType()) {
1034 DICompositeType CT(Ty);
1035 // A runtime language of 0 actually means C/C++ and that any
1036 // non-negative value is some version of Objective-C/C++.
1037 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1039 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1040 DD->addAccelType(Ty.getName(), TyDIE, Flags);
1042 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1043 Context.isNameSpace()) &&
1044 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1045 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
1050 /// addType - Add a new type attribute to the specified entity.
1051 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1052 assert(Ty && "Trying to add a type that doesn't exist?");
1054 // Check for pre-existence.
1055 DIEEntry *Entry = getDIEEntry(Ty);
1056 // If it exists then use the existing value.
1058 addDIEEntry(Entity, Attribute, Entry);
1063 DIE *Buffer = getOrCreateTypeDIE(Ty);
1066 Entry = createDIEEntry(*Buffer);
1067 insertDIEEntry(Ty, Entry);
1068 addDIEEntry(Entity, Attribute, Entry);
1071 /// addGlobalName - Add a new global name to the compile unit.
1072 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1073 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1075 std::string FullName = getParentContextString(Context) + Name.str();
1076 GlobalNames[FullName] = &Die;
1079 /// getParentContextString - Walks the metadata parent chain in a language
1080 /// specific manner (using the compile unit language) and returns
1081 /// it as a string. This is done at the metadata level because DIEs may
1082 /// not currently have been added to the parent context and walking the
1083 /// DIEs looking for names is more expensive than walking the metadata.
1084 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1088 // FIXME: Decide whether to implement this for non-C++ languages.
1089 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1093 SmallVector<DIScope, 1> Parents;
1094 while (!Context.isCompileUnit()) {
1095 Parents.push_back(Context);
1096 if (Context.getContext())
1097 Context = resolve(Context.getContext());
1099 // Structure, etc types will have a NULL context if they're at the top
1104 // Reverse iterate over our list to go from the outermost construct to the
1106 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1110 StringRef Name = Ctx.getName();
1111 if (Name.empty() && Ctx.isNameSpace())
1112 Name = "(anonymous namespace)";
1113 if (!Name.empty()) {
1121 /// constructTypeDIE - Construct basic type die from DIBasicType.
1122 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1123 // Get core information.
1124 StringRef Name = BTy.getName();
1125 // Add name if not anonymous or intermediate type.
1127 addString(Buffer, dwarf::DW_AT_name, Name);
1129 // An unspecified type only has a name attribute.
1130 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1133 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1136 uint64_t Size = BTy.getSizeInBits() >> 3;
1137 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1140 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1141 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1142 // Get core information.
1143 StringRef Name = DTy.getName();
1144 uint64_t Size = DTy.getSizeInBits() >> 3;
1145 uint16_t Tag = Buffer.getTag();
1147 // Map to main type, void will not have a type.
1148 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1150 addType(Buffer, FromTy);
1152 // Add name if not anonymous or intermediate type.
1154 addString(Buffer, dwarf::DW_AT_name, Name);
1156 // Add size if non-zero (derived types might be zero-sized.)
1157 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1158 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1160 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1161 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1162 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1163 // Add source line info if available and TyDesc is not a forward declaration.
1164 if (!DTy.isForwardDecl())
1165 addSourceLine(Buffer, DTy);
1168 /// constructSubprogramArguments - Construct function argument DIEs.
1169 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1170 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1171 DIType Ty = resolve(Args.getElement(i));
1173 assert(i == N-1 && "Unspecified parameter must be the last argument");
1174 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1176 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1177 addType(Arg, DIType(Ty));
1178 if (DIType(Ty).isArtificial())
1179 addFlag(Arg, dwarf::DW_AT_artificial);
1184 /// constructTypeDIE - Construct type DIE from DICompositeType.
1185 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1186 // Add name if not anonymous or intermediate type.
1187 StringRef Name = CTy.getName();
1189 uint64_t Size = CTy.getSizeInBits() >> 3;
1190 uint16_t Tag = Buffer.getTag();
1193 case dwarf::DW_TAG_array_type:
1194 constructArrayTypeDIE(Buffer, CTy);
1196 case dwarf::DW_TAG_enumeration_type:
1197 constructEnumTypeDIE(Buffer, CTy);
1199 case dwarf::DW_TAG_subroutine_type: {
1200 // Add return type. A void return won't have a type.
1201 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1202 DIType RTy(resolve(Elements.getElement(0)));
1204 addType(Buffer, RTy);
1206 bool isPrototyped = true;
1207 if (Elements.getNumElements() == 2 &&
1208 !Elements.getElement(1))
1209 isPrototyped = false;
1211 constructSubprogramArguments(Buffer, Elements);
1213 // Add prototype flag if we're dealing with a C language and the
1214 // function has been prototyped.
1215 uint16_t Language = getLanguage();
1217 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1218 Language == dwarf::DW_LANG_ObjC))
1219 addFlag(Buffer, dwarf::DW_AT_prototyped);
1221 if (CTy.isLValueReference())
1222 addFlag(Buffer, dwarf::DW_AT_reference);
1224 if (CTy.isRValueReference())
1225 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1227 case dwarf::DW_TAG_structure_type:
1228 case dwarf::DW_TAG_union_type:
1229 case dwarf::DW_TAG_class_type: {
1230 // Add elements to structure type.
1231 DIArray Elements = CTy.getElements();
1232 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1233 DIDescriptor Element = Elements.getElement(i);
1234 if (Element.isSubprogram())
1235 getOrCreateSubprogramDIE(DISubprogram(Element));
1236 else if (Element.isDerivedType()) {
1237 DIDerivedType DDTy(Element);
1238 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1239 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1240 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1241 dwarf::DW_AT_friend);
1242 } else if (DDTy.isStaticMember()) {
1243 getOrCreateStaticMemberDIE(DDTy);
1245 constructMemberDIE(Buffer, DDTy);
1247 } else if (Element.isObjCProperty()) {
1248 DIObjCProperty Property(Element);
1249 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1250 StringRef PropertyName = Property.getObjCPropertyName();
1251 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1252 if (Property.getType())
1253 addType(ElemDie, Property.getType());
1254 addSourceLine(ElemDie, Property);
1255 StringRef GetterName = Property.getObjCPropertyGetterName();
1256 if (!GetterName.empty())
1257 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1258 StringRef SetterName = Property.getObjCPropertySetterName();
1259 if (!SetterName.empty())
1260 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1261 unsigned PropertyAttributes = 0;
1262 if (Property.isReadOnlyObjCProperty())
1263 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1264 if (Property.isReadWriteObjCProperty())
1265 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1266 if (Property.isAssignObjCProperty())
1267 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1268 if (Property.isRetainObjCProperty())
1269 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1270 if (Property.isCopyObjCProperty())
1271 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1272 if (Property.isNonAtomicObjCProperty())
1273 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1274 if (PropertyAttributes)
1275 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1276 PropertyAttributes);
1278 DIEEntry *Entry = getDIEEntry(Element);
1280 Entry = createDIEEntry(ElemDie);
1281 insertDIEEntry(Element, Entry);
1287 if (CTy.isAppleBlockExtension())
1288 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1290 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1292 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1293 *getOrCreateTypeDIE(ContainingType));
1295 if (CTy.isObjcClassComplete())
1296 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1298 // Add template parameters to a class, structure or union types.
1299 // FIXME: The support isn't in the metadata for this yet.
1300 if (Tag == dwarf::DW_TAG_class_type ||
1301 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1302 addTemplateParams(Buffer, CTy.getTemplateParams());
1310 // Add name if not anonymous or intermediate type.
1312 addString(Buffer, dwarf::DW_AT_name, Name);
1314 if (Tag == dwarf::DW_TAG_enumeration_type ||
1315 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1316 Tag == dwarf::DW_TAG_union_type) {
1317 // Add size if non-zero (derived types might be zero-sized.)
1318 // TODO: Do we care about size for enum forward declarations?
1320 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1321 else if (!CTy.isForwardDecl())
1322 // Add zero size if it is not a forward declaration.
1323 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1325 // If we're a forward decl, say so.
1326 if (CTy.isForwardDecl())
1327 addFlag(Buffer, dwarf::DW_AT_declaration);
1329 // Add source line info if available.
1330 if (!CTy.isForwardDecl())
1331 addSourceLine(Buffer, CTy);
1333 // No harm in adding the runtime language to the declaration.
1334 unsigned RLang = CTy.getRunTimeLang();
1336 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1341 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1342 /// DITemplateTypeParameter.
1343 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1344 DITemplateTypeParameter TP) {
1346 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1347 // Add the type if it exists, it could be void and therefore no type.
1349 addType(ParamDIE, resolve(TP.getType()));
1350 if (!TP.getName().empty())
1351 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1354 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1355 /// DITemplateValueParameter.
1357 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1358 DITemplateValueParameter VP) {
1359 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1361 // Add the type if there is one, template template and template parameter
1362 // packs will not have a type.
1363 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1364 addType(ParamDIE, resolve(VP.getType()));
1365 if (!VP.getName().empty())
1366 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1367 if (Value *Val = VP.getValue()) {
1368 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1369 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1370 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1371 // For declaration non-type template parameters (such as global values and
1373 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1374 addOpAddress(*Loc, Asm->getSymbol(GV));
1375 // Emit DW_OP_stack_value to use the address as the immediate value of the
1376 // parameter, rather than a pointer to it.
1377 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1378 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1379 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1380 assert(isa<MDString>(Val));
1381 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1382 cast<MDString>(Val)->getString());
1383 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1384 assert(isa<MDNode>(Val));
1385 DIArray A(cast<MDNode>(Val));
1386 addTemplateParams(ParamDIE, A);
1391 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1392 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1393 // Construct the context before querying for the existence of the DIE in case
1394 // such construction creates the DIE.
1395 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1397 if (DIE *NDie = getDIE(NS))
1399 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1401 StringRef Name = NS.getName();
1403 addString(NDie, dwarf::DW_AT_name, NS.getName());
1405 Name = "(anonymous namespace)";
1406 DD->addAccelNamespace(Name, NDie);
1407 addGlobalName(Name, NDie, NS.getContext());
1408 addSourceLine(NDie, NS);
1412 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1413 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1414 // Construct the context before querying for the existence of the DIE in case
1415 // such construction creates the DIE (as is the case for member function
1417 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1419 if (DIE *SPDie = getDIE(SP))
1422 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1423 // Add subprogram definitions to the CU die directly.
1424 ContextDIE = &getUnitDie();
1425 // Build the decl now to ensure it precedes the definition.
1426 getOrCreateSubprogramDIE(SPDecl);
1429 // DW_TAG_inlined_subroutine may refer to this DIE.
1430 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1432 // Stop here and fill this in later, depending on whether or not this
1433 // subprogram turns out to have inlined instances or not.
1434 if (SP.isDefinition())
1437 applySubprogramAttributes(SP, SPDie);
1441 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1442 DISubprogram SPDecl = SP.getFunctionDeclaration();
1443 DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1444 applySubprogramAttributes(SP, SPDie);
1445 addGlobalName(SP.getName(), SPDie, Context);
1448 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1449 DIE *DeclDie = nullptr;
1450 StringRef DeclLinkageName;
1451 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1452 DeclDie = getDIE(SPDecl);
1453 assert(DeclDie && "This DIE should've already been constructed when the "
1454 "definition DIE was created in "
1455 "getOrCreateSubprogramDIE");
1456 DeclLinkageName = SPDecl.getLinkageName();
1459 // Add function template parameters.
1460 addTemplateParams(SPDie, SP.getTemplateParams());
1462 // Add the linkage name if we have one and it isn't in the Decl.
1463 StringRef LinkageName = SP.getLinkageName();
1464 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1465 LinkageName == DeclLinkageName) &&
1466 "decl has a linkage name and it is different");
1467 if (!LinkageName.empty() && DeclLinkageName.empty())
1468 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1469 GlobalValue::getRealLinkageName(LinkageName));
1472 // Refer to the function declaration where all the other attributes will be
1474 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1478 // Constructors and operators for anonymous aggregates do not have names.
1479 if (!SP.getName().empty())
1480 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1482 addSourceLine(SPDie, SP);
1484 // Add the prototype if we have a prototype and we have a C like
1486 uint16_t Language = getLanguage();
1487 if (SP.isPrototyped() &&
1488 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1489 Language == dwarf::DW_LANG_ObjC))
1490 addFlag(SPDie, dwarf::DW_AT_prototyped);
1492 DISubroutineType SPTy = SP.getType();
1493 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1494 "the type of a subprogram should be a subroutine");
1496 DITypeArray Args = SPTy.getTypeArray();
1497 // Add a return type. If this is a type like a C/C++ void type we don't add a
1499 if (resolve(Args.getElement(0)))
1500 addType(SPDie, DIType(resolve(Args.getElement(0))));
1502 unsigned VK = SP.getVirtuality();
1504 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1505 DIELoc *Block = getDIELoc();
1506 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1507 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1508 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1509 ContainingTypeMap.insert(
1510 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1513 if (!SP.isDefinition()) {
1514 addFlag(SPDie, dwarf::DW_AT_declaration);
1516 // Add arguments. Do not add arguments for subprogram definition. They will
1517 // be handled while processing variables.
1518 constructSubprogramArguments(SPDie, Args);
1521 if (SP.isArtificial())
1522 addFlag(SPDie, dwarf::DW_AT_artificial);
1524 if (!SP.isLocalToUnit())
1525 addFlag(SPDie, dwarf::DW_AT_external);
1527 if (SP.isOptimized())
1528 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1530 if (unsigned isa = Asm->getISAEncoding()) {
1531 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1534 if (SP.isLValueReference())
1535 addFlag(SPDie, dwarf::DW_AT_reference);
1537 if (SP.isRValueReference())
1538 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1540 if (SP.isProtected())
1541 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1542 dwarf::DW_ACCESS_protected);
1543 else if (SP.isPrivate())
1544 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1545 dwarf::DW_ACCESS_private);
1547 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1548 dwarf::DW_ACCESS_public);
1550 if (SP.isExplicit())
1551 addFlag(SPDie, dwarf::DW_AT_explicit);
1554 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1556 StringRef Name = Var.getName();
1558 addString(VariableDie, dwarf::DW_AT_name, Name);
1559 addSourceLine(VariableDie, Var.getVariable());
1560 addType(VariableDie, Var.getType());
1561 if (Var.isArtificial())
1562 addFlag(VariableDie, dwarf::DW_AT_artificial);
1565 // Return const expression if value is a GEP to access merged global
1567 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1568 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1569 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1570 if (!CE || CE->getNumOperands() != 3 ||
1571 CE->getOpcode() != Instruction::GetElementPtr)
1574 // First operand points to a global struct.
1575 Value *Ptr = CE->getOperand(0);
1576 if (!isa<GlobalValue>(Ptr) ||
1577 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1580 // Second operand is zero.
1581 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1582 if (!CI || !CI->isZero())
1585 // Third operand is offset.
1586 if (!isa<ConstantInt>(CE->getOperand(2)))
1592 /// createGlobalVariableDIE - create global variable DIE.
1593 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1594 // Check for pre-existence.
1598 assert(GV.isGlobalVariable());
1600 DIScope GVContext = GV.getContext();
1601 DIType GTy = DD->resolve(GV.getType());
1603 // If this is a static data member definition, some attributes belong
1604 // to the declaration DIE.
1605 DIE *VariableDIE = nullptr;
1606 bool IsStaticMember = false;
1607 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1608 if (SDMDecl.Verify()) {
1609 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1610 // We need the declaration DIE that is in the static member's class.
1611 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1612 IsStaticMember = true;
1615 // If this is not a static data member definition, create the variable
1616 // DIE and add the initial set of attributes to it.
1618 // Construct the context before querying for the existence of the DIE in
1619 // case such construction creates the DIE.
1620 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1623 VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1625 // Add name and type.
1626 addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1627 addType(*VariableDIE, GTy);
1629 // Add scoping info.
1630 if (!GV.isLocalToUnit())
1631 addFlag(*VariableDIE, dwarf::DW_AT_external);
1633 // Add line number info.
1634 addSourceLine(*VariableDIE, GV);
1638 bool addToAccelTable = false;
1639 DIE *VariableSpecDIE = nullptr;
1640 bool isGlobalVariable = GV.getGlobal() != nullptr;
1641 if (isGlobalVariable) {
1642 addToAccelTable = true;
1643 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1644 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1645 if (GV.getGlobal()->isThreadLocal()) {
1646 // FIXME: Make this work with -gsplit-dwarf.
1647 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1648 assert((PointerSize == 4 || PointerSize == 8) &&
1649 "Add support for other sizes if necessary");
1650 // Based on GCC's support for TLS:
1651 if (!DD->useSplitDwarf()) {
1652 // 1) Start with a constNu of the appropriate pointer size
1653 addUInt(*Loc, dwarf::DW_FORM_data1,
1654 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1655 // 2) containing the (relocated) offset of the TLS variable
1656 // within the module's TLS block.
1657 addExpr(*Loc, dwarf::DW_FORM_udata,
1658 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1660 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1661 addUInt(*Loc, dwarf::DW_FORM_udata,
1662 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1664 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1665 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1667 DD->addArangeLabel(SymbolCU(this, Sym));
1668 addOpAddress(*Loc, Sym);
1670 // Do not create specification DIE if context is either compile unit
1672 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1673 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1674 // Create specification DIE.
1675 VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
1676 addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
1677 addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1678 // A static member's declaration is already flagged as such.
1679 if (!SDMDecl.Verify())
1680 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1682 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1684 // Add the linkage name.
1685 StringRef LinkageName = GV.getLinkageName();
1686 if (!LinkageName.empty())
1687 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1688 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1690 addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1692 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1693 : dwarf::DW_AT_MIPS_linkage_name,
1694 GlobalValue::getRealLinkageName(LinkageName));
1695 } else if (const ConstantInt *CI =
1696 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1697 // AT_const_value was added when the static member was created. To avoid
1698 // emitting AT_const_value multiple times, we only add AT_const_value when
1699 // it is not a static member.
1700 if (!IsStaticMember)
1701 addConstantValue(*VariableDIE, CI, GTy);
1702 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1703 addToAccelTable = true;
1704 // GV is a merged global.
1705 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1706 Value *Ptr = CE->getOperand(0);
1707 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1708 DD->addArangeLabel(SymbolCU(this, Sym));
1709 addOpAddress(*Loc, Sym);
1710 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1711 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1712 addUInt(*Loc, dwarf::DW_FORM_udata,
1713 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1714 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1715 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1718 if (addToAccelTable) {
1719 DIE &AddrDIE = VariableSpecDIE ? *VariableSpecDIE : *VariableDIE;
1720 DD->addAccelName(GV.getName(), AddrDIE);
1722 // If the linkage name is different than the name, go ahead and output
1723 // that as well into the name table.
1724 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1725 DD->addAccelName(GV.getLinkageName(), AddrDIE);
1728 addGlobalName(GV.getName(), VariableSpecDIE ? *VariableSpecDIE : *VariableDIE,
1732 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1733 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1734 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1735 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1737 // The LowerBound value defines the lower bounds which is typically zero for
1738 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1739 // Count == -1 then the array is unbounded and we do not emit
1740 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1741 // Count == 0, then the array has zero elements in which case we do not emit
1743 int64_t LowerBound = SR.getLo();
1744 int64_t DefaultLowerBound = getDefaultLowerBound();
1745 int64_t Count = SR.getCount();
1747 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1748 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1750 if (Count != -1 && Count != 0)
1751 // FIXME: An unbounded array should reference the expression that defines
1753 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1754 LowerBound + Count - 1);
1757 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1758 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1760 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1762 // Emit the element type.
1763 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1765 // Get an anonymous type for index type.
1766 // FIXME: This type should be passed down from the front end
1767 // as different languages may have different sizes for indexes.
1768 DIE *IdxTy = getIndexTyDie();
1770 // Construct an integer type to use for indexes.
1771 IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1772 addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1773 addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1774 addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1775 dwarf::DW_ATE_unsigned);
1776 setIndexTyDie(IdxTy);
1779 // Add subranges to array type.
1780 DIArray Elements = CTy.getElements();
1781 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1782 DIDescriptor Element = Elements.getElement(i);
1783 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1784 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1788 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1789 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1790 DIArray Elements = CTy.getElements();
1792 // Add enumerators to enumeration type.
1793 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1794 DIEnumerator Enum(Elements.getElement(i));
1795 if (Enum.isEnumerator()) {
1796 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1797 StringRef Name = Enum.getName();
1798 addString(Enumerator, dwarf::DW_AT_name, Name);
1799 int64_t Value = Enum.getEnumValue();
1800 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1804 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1806 addType(Buffer, DTy);
1807 addFlag(Buffer, dwarf::DW_AT_enum_class);
1811 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1813 void DwarfUnit::constructContainingTypeDIEs() {
1814 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1815 CE = ContainingTypeMap.end();
1817 DIE &SPDie = *CI->first;
1818 DIDescriptor D(CI->second);
1821 DIE *NDie = getDIE(D);
1824 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1828 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1829 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1831 auto D = constructVariableDIEImpl(DV, Abstract);
1836 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1838 // Define variable debug information entry.
1839 auto VariableDie = make_unique<DIE>(DV.getTag());
1842 applyVariableAttributes(DV, *VariableDie);
1846 // Add variable address.
1848 unsigned Offset = DV.getDotDebugLocOffset();
1849 if (Offset != ~0U) {
1850 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1854 // Check if variable is described by a DBG_VALUE instruction.
1855 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1856 assert(DVInsn->getNumOperands() == 3);
1857 if (DVInsn->getOperand(0).isReg()) {
1858 const MachineOperand RegOp = DVInsn->getOperand(0);
1859 // If the second operand is an immediate, this is an indirect value.
1860 if (DVInsn->getOperand(1).isImm()) {
1861 MachineLocation Location(RegOp.getReg(),
1862 DVInsn->getOperand(1).getImm());
1863 addVariableAddress(DV, *VariableDie, Location);
1864 } else if (RegOp.getReg())
1865 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1866 } else if (DVInsn->getOperand(0).isImm())
1867 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1868 else if (DVInsn->getOperand(0).isFPImm())
1869 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1870 else if (DVInsn->getOperand(0).isCImm())
1871 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1877 // .. else use frame index.
1878 int FI = DV.getFrameIndex();
1880 unsigned FrameReg = 0;
1881 const TargetFrameLowering *TFI =
1882 Asm->TM.getSubtargetImpl()->getFrameLowering();
1883 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1884 MachineLocation Location(FrameReg, Offset);
1885 addVariableAddress(DV, *VariableDie, Location);
1891 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1892 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1893 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1894 StringRef Name = DT.getName();
1896 addString(MemberDie, dwarf::DW_AT_name, Name);
1898 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1900 addSourceLine(MemberDie, DT);
1902 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1904 // For C++, virtual base classes are not at fixed offset. Use following
1905 // expression to extract appropriate offset from vtable.
1906 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1908 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1909 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1910 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1911 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1912 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1913 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1914 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1915 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1917 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1919 uint64_t Size = DT.getSizeInBits();
1920 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1921 uint64_t OffsetInBytes;
1923 if (Size != FieldSize) {
1924 // Handle bitfield, assume bytes are 8 bits.
1925 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1926 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1928 uint64_t Offset = DT.getOffsetInBits();
1929 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1930 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1931 uint64_t FieldOffset = (HiMark - FieldSize);
1932 Offset -= FieldOffset;
1934 // Maybe we need to work from the other end.
1935 if (Asm->getDataLayout().isLittleEndian())
1936 Offset = FieldSize - (Offset + Size);
1937 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1939 // Here DW_AT_data_member_location points to the anonymous
1940 // field that includes this bit field.
1941 OffsetInBytes = FieldOffset >> 3;
1943 // This is not a bitfield.
1944 OffsetInBytes = DT.getOffsetInBits() >> 3;
1946 if (DD->getDwarfVersion() <= 2) {
1947 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1948 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1949 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1950 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1952 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1956 if (DT.isProtected())
1957 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1958 dwarf::DW_ACCESS_protected);
1959 else if (DT.isPrivate())
1960 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1961 dwarf::DW_ACCESS_private);
1962 // Otherwise C++ member and base classes are considered public.
1964 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1965 dwarf::DW_ACCESS_public);
1967 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1968 dwarf::DW_VIRTUALITY_virtual);
1970 // Objective-C properties.
1971 if (MDNode *PNode = DT.getObjCProperty())
1972 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1973 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1976 if (DT.isArtificial())
1977 addFlag(MemberDie, dwarf::DW_AT_artificial);
1980 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1981 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1985 // Construct the context before querying for the existence of the DIE in case
1986 // such construction creates the DIE.
1987 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1988 assert(dwarf::isType(ContextDIE->getTag()) &&
1989 "Static member should belong to a type.");
1991 if (DIE *StaticMemberDIE = getDIE(DT))
1992 return StaticMemberDIE;
1994 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1996 DIType Ty = resolve(DT.getTypeDerivedFrom());
1998 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1999 addType(StaticMemberDIE, Ty);
2000 addSourceLine(StaticMemberDIE, DT);
2001 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2002 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2004 // FIXME: We could omit private if the parent is a class_type, and
2005 // public if the parent is something else.
2006 if (DT.isProtected())
2007 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2008 dwarf::DW_ACCESS_protected);
2009 else if (DT.isPrivate())
2010 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2011 dwarf::DW_ACCESS_private);
2013 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2014 dwarf::DW_ACCESS_public);
2016 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2017 addConstantValue(StaticMemberDIE, CI, Ty);
2018 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2019 addConstantFPValue(StaticMemberDIE, CFP);
2021 return &StaticMemberDIE;
2024 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2025 Asm->OutStreamer.AddComment("DWARF version number");
2026 Asm->EmitInt16(DD->getDwarfVersion());
2027 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2028 // We share one abbreviations table across all units so it's always at the
2029 // start of the section. Use a relocatable offset where needed to ensure
2030 // linking doesn't invalidate that offset.
2032 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2034 // Use a constant value when no symbol is provided.
2036 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2037 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2040 void DwarfUnit::addRange(RangeSpan Range) {
2041 // Only add a range for this unit if we're emitting full debug.
2042 if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
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.size() == 0 ||
2048 this != DD->getPrevCU() ||
2049 Asm->getCurrentSection() != DD->getPrevSection()) {
2050 CURanges.push_back(Range);
2054 assert(&(CURanges.back().getEnd()->getSection()) ==
2055 &(Range.getEnd()->getSection()) &&
2056 "We can only append to a range in the same section!");
2057 CURanges.back().setEnd(Range.getEnd());
2061 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2062 // Define start line table label for each Compile Unit.
2063 MCSymbol *LineTableStartSym =
2064 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2066 stmtListIndex = UnitDie.getValues().size();
2068 // DW_AT_stmt_list is a offset of line number information for this
2069 // compile unit in debug_line section. For split dwarf this is
2070 // left in the skeleton CU and so not included.
2071 // The line table entries are not always emitted in assembly, so it
2072 // is not okay to use line_table_start here.
2073 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2074 addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
2076 addSectionDelta(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
2077 DwarfLineSectionSym);
2080 void DwarfCompileUnit::applyStmtList(DIE &D) {
2081 D.addValue(dwarf::DW_AT_stmt_list,
2082 UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
2083 UnitDie.getValues()[stmtListIndex]);
2086 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2087 DwarfUnit::emitHeader(ASectionSym);
2088 Asm->OutStreamer.AddComment("Type Signature");
2089 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2090 Asm->OutStreamer.AddComment("Type DIE Offset");
2091 // In a skeleton type unit there is no type DIE so emit a zero offset.
2092 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2093 sizeof(Ty->getOffset()));
2096 void DwarfTypeUnit::initSection(const MCSection *Section) {
2097 assert(!this->Section);
2098 this->Section = Section;
2099 // Since each type unit is contained in its own COMDAT section, the begin
2100 // label and the section label are the same. Using the begin label emission in
2101 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2102 // the only other alternative of lazily constructing start-of-section labels
2103 // and storing a mapping in DwarfDebug (or AsmPrinter).
2104 this->SectionSym = this->LabelBegin =
2105 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2107 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());