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 // Don't use the address pool in non-fission or in the skeleton unit itself.
290 // FIXME: Once GDB supports this, it's probably worthwhile using the address
291 // pool from the skeleton - maybe even in non-fission (possibly fewer
292 // relocations by sharing them in the pool, but we have other ideas about how
293 // to reduce the number of relocations as well/instead).
294 if (!DD->useSplitDwarf() || !Skeleton)
295 return addLocalLabelAddress(Die, Attribute, Label);
298 DD->addArangeLabel(SymbolCU(this, Label));
300 unsigned idx = DD->getAddressPool().getIndex(Label);
301 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
302 Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
305 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
306 dwarf::Attribute Attribute,
307 const MCSymbol *Label) {
309 DD->addArangeLabel(SymbolCU(this, Label));
311 Die.addValue(Attribute, dwarf::DW_FORM_addr,
312 Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
313 : new (DIEValueAllocator) DIEInteger(0));
316 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
317 // If we print assembly, we can't separate .file entries according to
318 // compile units. Thus all files will belong to the default compile unit.
320 // FIXME: add a better feature test than hasRawTextSupport. Even better,
321 // extend .file to support this.
322 return Asm->OutStreamer.EmitDwarfFileDirective(
323 0, DirName, FileName,
324 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
327 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
328 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
329 : getCU().getOrCreateSourceID(FileName, DirName);
332 /// addOpAddress - Add a dwarf op address data and value using the
333 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
335 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
336 if (!DD->useSplitDwarf()) {
337 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
338 addLabel(Die, dwarf::DW_FORM_udata, Sym);
340 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
341 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
342 DD->getAddressPool().getIndex(Sym));
346 /// addSectionDelta - Add a section label delta attribute data and value.
348 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
349 const MCSymbol *Hi, const MCSymbol *Lo) {
350 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
351 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
352 : dwarf::DW_FORM_data4,
356 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
357 const MCSymbol *Hi, const MCSymbol *Lo) {
358 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
359 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
362 /// addDIEEntry - Add a DIE attribute data and value.
364 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
365 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
368 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
369 // Flag the type unit reference as a declaration so that if it contains
370 // members (implicit special members, static data member definitions, member
371 // declarations for definitions in this CU, etc) consumers don't get confused
372 // and think this is a full definition.
373 addFlag(Die, dwarf::DW_AT_declaration);
375 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
376 new (DIEValueAllocator) DIETypeSignature(Type));
379 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
381 const DIE *DieCU = Die.getUnitOrNull();
382 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
384 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
385 DieCU = &getUnitDie();
387 EntryCU = &getUnitDie();
388 Die.addValue(Attribute,
389 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
393 /// Create a DIE with the given Tag, add the DIE to its parent, and
394 /// call insertDIE if MD is not null.
395 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
396 assert(Tag != dwarf::DW_TAG_auto_variable &&
397 Tag != dwarf::DW_TAG_arg_variable);
398 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
399 DIE &Die = *Parent.getChildren().back();
405 /// addBlock - Add block data.
407 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
408 Loc->ComputeSize(Asm);
409 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
410 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
413 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
415 Block->ComputeSize(Asm);
416 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
417 Die.addValue(Attribute, Block->BestForm(), Block);
420 /// addSourceLine - Add location information to specified debug information
422 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
423 StringRef Directory) {
427 unsigned FileID = getOrCreateSourceID(File, Directory);
428 assert(FileID && "Invalid file id");
429 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
430 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
433 /// addSourceLine - Add location information to specified debug information
435 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
436 assert(V.isVariable());
438 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
439 V.getContext().getDirectory());
442 /// addSourceLine - Add location information to specified debug information
444 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
445 assert(G.isGlobalVariable());
447 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
450 /// addSourceLine - Add location information to specified debug information
452 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
453 assert(SP.isSubprogram());
455 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
458 /// addSourceLine - Add location information to specified debug information
460 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
463 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
466 /// addSourceLine - Add location information to specified debug information
468 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
469 assert(Ty.isObjCProperty());
471 DIFile File = Ty.getFile();
472 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
473 File.getDirectory());
476 /// addSourceLine - Add location information to specified debug information
478 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
481 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
484 /// addVariableAddress - Add DW_AT_location attribute for a
485 /// DbgVariable based on provided MachineLocation.
486 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
487 MachineLocation Location) {
488 if (DV.variableHasComplexAddress())
489 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
490 else if (DV.isBlockByrefVariable())
491 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
493 addAddress(Die, dwarf::DW_AT_location, Location,
494 DV.getVariable().isIndirect());
497 /// addRegisterOp - Add register operand.
498 // FIXME: Ideally, this would share the implementation with
499 // AsmPrinter::EmitDwarfRegOpPiece.
500 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
501 unsigned SizeInBits, unsigned OffsetInBits) {
502 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
503 int DWReg = RI->getDwarfRegNum(Reg, false);
504 bool isSubRegister = DWReg < 0;
508 // Go up the super-register chain until we hit a valid dwarf register number.
509 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
510 DWReg = RI->getDwarfRegNum(*SR, false);
512 Idx = RI->getSubRegIndex(*SR, Reg);
516 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
517 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
523 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
525 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
526 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
530 bool isPiece = SizeInBits > 0;
531 if (isSubRegister || isPiece) {
532 const unsigned SizeOfByte = 8;
533 unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
534 unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
535 unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
536 unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
537 assert(RegSizeInBits >= SizeInBits && "register smaller than value");
539 if (RegOffsetInBits != PieceOffsetInBits) {
540 // Manually shift the value into place, since the DW_OP_piece
541 // describes the part of the variable, not the position of the
543 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
544 addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
545 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
548 if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
549 assert(PieceSizeInBits > 0 && "piece has zero size");
550 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
551 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
552 addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
554 assert(PieceSizeInBits > 0 && "piece has zero size");
555 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
556 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
561 /// addRegisterOffset - Add register offset.
562 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
564 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
565 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
566 const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
567 if (Reg == TRI->getFrameRegister(*Asm->MF))
568 // If variable offset is based in frame register then use fbreg.
569 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
571 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
573 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
574 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
576 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
579 /// addAddress - Add an address attribute to a die based on the location
581 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
582 const MachineLocation &Location, bool Indirect) {
583 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
585 if (Location.isReg() && !Indirect)
586 addRegisterOpPiece(*Loc, Location.getReg());
588 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
589 if (Indirect && !Location.isReg()) {
590 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
594 // Now attach the location information to the DIE.
595 addBlock(Die, Attribute, Loc);
598 /// addComplexAddress - Start with the address based on the location provided,
599 /// and generate the DWARF information necessary to find the actual variable
600 /// given the extra address information encoded in the DbgVariable, starting
601 /// from the starting location. Add the DWARF information to the die.
603 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
604 dwarf::Attribute Attribute,
605 const MachineLocation &Location) {
606 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
607 unsigned N = DV.getNumAddrElements();
609 if (Location.isReg()) {
610 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
611 // If first address element is OpPlus then emit
612 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
613 addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
615 } else if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpDeref) {
616 addRegisterOpPiece(*Loc, Location.getReg(),
617 DV.getVariable().getPieceSize(),
618 DV.getVariable().getPieceOffset());
621 addRegisterOpPiece(*Loc, Location.getReg());
623 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
626 uint64_t Element = DV.getAddrElement(i);
627 if (Element == DIBuilder::OpPlus) {
628 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
629 addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
631 } else if (Element == DIBuilder::OpDeref) {
632 if (!Location.isReg())
633 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
635 } else if (Element == DIBuilder::OpPiece) {
636 const unsigned SizeOfByte = 8;
637 unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
638 unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
639 // Emit DW_OP_bit_piece Size Offset.
640 assert(PieceSizeInBits > 0 && "piece has zero size");
641 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
642 addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
643 addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
646 llvm_unreachable("unknown DIBuilder Opcode");
649 // Now attach the location information to the DIE.
650 addBlock(Die, Attribute, Loc);
653 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
654 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
655 gives the variable VarName either the struct, or a pointer to the struct, as
656 its type. This is necessary for various behind-the-scenes things the
657 compiler needs to do with by-reference variables in Blocks.
659 However, as far as the original *programmer* is concerned, the variable
660 should still have type 'SomeType', as originally declared.
662 The function getBlockByrefType dives into the __Block_byref_x_VarName
663 struct to find the original type of the variable, which is then assigned to
664 the variable's Debug Information Entry as its real type. So far, so good.
665 However now the debugger will expect the variable VarName to have the type
666 SomeType. So we need the location attribute for the variable to be an
667 expression that explains to the debugger how to navigate through the
668 pointers and struct to find the actual variable of type SomeType.
670 The following function does just that. We start by getting
671 the "normal" location for the variable. This will be the location
672 of either the struct __Block_byref_x_VarName or the pointer to the
673 struct __Block_byref_x_VarName.
675 The struct will look something like:
677 struct __Block_byref_x_VarName {
679 struct __Block_byref_x_VarName *forwarding;
680 ... <various other fields>
682 ... <maybe more fields>
685 If we are given the struct directly (as our starting point) we
686 need to tell the debugger to:
688 1). Add the offset of the forwarding field.
690 2). Follow that pointer to get the real __Block_byref_x_VarName
691 struct to use (the real one may have been copied onto the heap).
693 3). Add the offset for the field VarName, to find the actual variable.
695 If we started with a pointer to the struct, then we need to
696 dereference that pointer first, before the other steps.
697 Translating this into DWARF ops, we will need to append the following
698 to the current location description for the variable:
700 DW_OP_deref -- optional, if we start with a pointer
701 DW_OP_plus_uconst <forward_fld_offset>
703 DW_OP_plus_uconst <varName_fld_offset>
705 That is what this function does. */
707 /// addBlockByrefAddress - Start with the address based on the location
708 /// provided, and generate the DWARF information necessary to find the
709 /// actual Block variable (navigating the Block struct) based on the
710 /// starting location. Add the DWARF information to the die. For
711 /// more information, read large comment just above here.
713 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
714 dwarf::Attribute Attribute,
715 const MachineLocation &Location) {
716 DIType Ty = DV.getType();
718 uint16_t Tag = Ty.getTag();
719 bool isPointer = false;
721 StringRef varName = DV.getName();
723 if (Tag == dwarf::DW_TAG_pointer_type) {
724 DIDerivedType DTy(Ty);
725 TmpTy = resolve(DTy.getTypeDerivedFrom());
729 DICompositeType blockStruct(TmpTy);
731 // Find the __forwarding field and the variable field in the __Block_byref
733 DIArray Fields = blockStruct.getElements();
734 DIDerivedType varField;
735 DIDerivedType forwardingField;
737 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
738 DIDerivedType DT(Fields.getElement(i));
739 StringRef fieldName = DT.getName();
740 if (fieldName == "__forwarding")
741 forwardingField = DT;
742 else if (fieldName == varName)
746 // Get the offsets for the forwarding field and the variable field.
747 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
748 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
750 // Decode the original location, and use that as the start of the byref
751 // variable's location.
752 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
754 if (Location.isReg())
755 addRegisterOpPiece(*Loc, Location.getReg());
757 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
759 // If we started with a pointer to the __Block_byref... struct, then
760 // the first thing we need to do is dereference the pointer (DW_OP_deref).
762 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
764 // Next add the offset for the '__forwarding' field:
765 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
766 // adding the offset if it's 0.
767 if (forwardingFieldOffset > 0) {
768 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
769 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
772 // Now dereference the __forwarding field to get to the real __Block_byref
773 // struct: DW_OP_deref.
774 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
776 // Now that we've got the real __Block_byref... struct, add the offset
777 // for the variable's field to get to the location of the actual variable:
778 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
779 if (varFieldOffset > 0) {
780 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
781 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
784 // Now attach the location information to the DIE.
785 addBlock(Die, Attribute, Loc);
788 /// Return true if type encoding is unsigned.
789 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
790 DIDerivedType DTy(Ty);
791 if (DTy.isDerivedType()) {
792 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
793 // Encode pointer constants as unsigned bytes. This is used at least for
794 // null pointer constant emission.
795 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
796 // here, but accept them for now due to a bug in SROA producing bogus
798 if (T == dwarf::DW_TAG_pointer_type ||
799 T == dwarf::DW_TAG_ptr_to_member_type ||
800 T == dwarf::DW_TAG_reference_type ||
801 T == dwarf::DW_TAG_rvalue_reference_type)
803 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
804 T == dwarf::DW_TAG_volatile_type ||
805 T == dwarf::DW_TAG_restrict_type ||
806 T == dwarf::DW_TAG_enumeration_type);
807 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
808 return isUnsignedDIType(DD, DD->resolve(Deriv));
809 // FIXME: Enums without a fixed underlying type have unknown signedness
810 // here, leading to incorrectly emitted constants.
811 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
816 assert(BTy.isBasicType());
817 unsigned Encoding = BTy.getEncoding();
818 assert((Encoding == dwarf::DW_ATE_unsigned ||
819 Encoding == dwarf::DW_ATE_unsigned_char ||
820 Encoding == dwarf::DW_ATE_signed ||
821 Encoding == dwarf::DW_ATE_signed_char ||
822 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
823 "Unsupported encoding");
824 return (Encoding == dwarf::DW_ATE_unsigned ||
825 Encoding == dwarf::DW_ATE_unsigned_char ||
826 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
829 /// If this type is derived from a base type then return base type size.
830 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
831 unsigned Tag = Ty.getTag();
833 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
834 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
835 Tag != dwarf::DW_TAG_restrict_type)
836 return Ty.getSizeInBits();
838 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
840 // If this type is not derived from any type or the type is a declaration then
841 // take conservative approach.
842 if (!BaseType.isValid() || BaseType.isForwardDecl())
843 return Ty.getSizeInBits();
845 // If this is a derived type, go ahead and get the base type, unless it's a
846 // reference then it's just the size of the field. Pointer types have no need
847 // of this since they're a different type of qualification on the type.
848 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
849 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
850 return Ty.getSizeInBits();
852 if (BaseType.isDerivedType())
853 return getBaseTypeSize(DD, DIDerivedType(BaseType));
855 return BaseType.getSizeInBits();
858 /// addConstantFPValue - Add constant value entry in variable DIE.
859 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
860 assert(MO.isFPImm() && "Invalid machine operand!");
861 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
862 APFloat FPImm = MO.getFPImm()->getValueAPF();
864 // Get the raw data form of the floating point.
865 const APInt FltVal = FPImm.bitcastToAPInt();
866 const char *FltPtr = (const char *)FltVal.getRawData();
868 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
869 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
870 int Incr = (LittleEndian ? 1 : -1);
871 int Start = (LittleEndian ? 0 : NumBytes - 1);
872 int Stop = (LittleEndian ? NumBytes : -1);
874 // Output the constant to DWARF one byte at a time.
875 for (; Start != Stop; Start += Incr)
876 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
878 addBlock(Die, dwarf::DW_AT_const_value, Block);
881 /// addConstantFPValue - Add constant value entry in variable DIE.
882 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
883 // Pass this down to addConstantValue as an unsigned bag of bits.
884 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
887 /// addConstantValue - Add constant value entry in variable DIE.
888 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
889 addConstantValue(Die, CI->getValue(), Ty);
892 /// addConstantValue - Add constant value entry in variable DIE.
893 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
895 assert(MO.isImm() && "Invalid machine operand!");
897 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
900 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
901 // FIXME: This is a bit conservative/simple - it emits negative values always
902 // sign extended to 64 bits rather than minimizing the number of bytes.
903 addUInt(Die, dwarf::DW_AT_const_value,
904 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
907 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
908 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
911 // addConstantValue - Add constant value entry in variable DIE.
912 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
913 unsigned CIBitWidth = Val.getBitWidth();
914 if (CIBitWidth <= 64) {
915 addConstantValue(Die, Unsigned,
916 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
920 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
922 // Get the raw data form of the large APInt.
923 const uint64_t *Ptr64 = Val.getRawData();
925 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
926 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
928 // Output the constant to DWARF one byte at a time.
929 for (int i = 0; i < NumBytes; i++) {
932 c = Ptr64[i / 8] >> (8 * (i & 7));
934 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
935 addUInt(*Block, dwarf::DW_FORM_data1, c);
938 addBlock(Die, dwarf::DW_AT_const_value, Block);
941 /// addTemplateParams - Add template parameters into buffer.
942 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
943 // Add template parameters.
944 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
945 DIDescriptor Element = TParams.getElement(i);
946 if (Element.isTemplateTypeParameter())
947 constructTemplateTypeParameterDIE(Buffer,
948 DITemplateTypeParameter(Element));
949 else if (Element.isTemplateValueParameter())
950 constructTemplateValueParameterDIE(Buffer,
951 DITemplateValueParameter(Element));
955 /// getOrCreateContextDIE - Get context owner's DIE.
956 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
957 if (!Context || Context.isFile())
958 return &getUnitDie();
959 if (Context.isType())
960 return getOrCreateTypeDIE(DIType(Context));
961 if (Context.isNameSpace())
962 return getOrCreateNameSpace(DINameSpace(Context));
963 if (Context.isSubprogram())
964 return getOrCreateSubprogramDIE(DISubprogram(Context));
965 return getDIE(Context);
968 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
969 DIScope Context = resolve(Ty.getContext());
970 DIE *ContextDIE = getOrCreateContextDIE(Context);
972 if (DIE *TyDIE = getDIE(Ty))
976 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
978 constructTypeDIE(TyDIE, Ty);
980 updateAcceleratorTables(Context, Ty, TyDIE);
984 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
986 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
992 assert(Ty == resolve(Ty.getRef()) &&
993 "type was not uniqued, possible ODR violation.");
995 // DW_TAG_restrict_type is not supported in DWARF2
996 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
997 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
999 // Construct the context before querying for the existence of the DIE in case
1000 // such construction creates the DIE.
1001 DIScope Context = resolve(Ty.getContext());
1002 DIE *ContextDIE = getOrCreateContextDIE(Context);
1005 if (DIE *TyDIE = getDIE(Ty))
1009 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1011 updateAcceleratorTables(Context, Ty, TyDIE);
1013 if (Ty.isBasicType())
1014 constructTypeDIE(TyDIE, DIBasicType(Ty));
1015 else if (Ty.isCompositeType()) {
1016 DICompositeType CTy(Ty);
1017 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1018 if (MDString *TypeId = CTy.getIdentifier()) {
1019 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1020 // Skip updating the accelerator tables since this is not the full type.
1023 constructTypeDIE(TyDIE, CTy);
1025 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1026 constructTypeDIE(TyDIE, DIDerivedType(Ty));
1032 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1034 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1035 bool IsImplementation = 0;
1036 if (Ty.isCompositeType()) {
1037 DICompositeType CT(Ty);
1038 // A runtime language of 0 actually means C/C++ and that any
1039 // non-negative value is some version of Objective-C/C++.
1040 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1042 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1043 DD->addAccelType(Ty.getName(), TyDIE, Flags);
1045 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1046 Context.isNameSpace()) &&
1047 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1048 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
1053 /// addType - Add a new type attribute to the specified entity.
1054 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1055 assert(Ty && "Trying to add a type that doesn't exist?");
1057 // Check for pre-existence.
1058 DIEEntry *Entry = getDIEEntry(Ty);
1059 // If it exists then use the existing value.
1061 addDIEEntry(Entity, Attribute, Entry);
1066 DIE *Buffer = getOrCreateTypeDIE(Ty);
1069 Entry = createDIEEntry(*Buffer);
1070 insertDIEEntry(Ty, Entry);
1071 addDIEEntry(Entity, Attribute, Entry);
1074 /// addGlobalName - Add a new global name to the compile unit.
1075 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1076 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1078 std::string FullName = getParentContextString(Context) + Name.str();
1079 GlobalNames[FullName] = &Die;
1082 /// getParentContextString - Walks the metadata parent chain in a language
1083 /// specific manner (using the compile unit language) and returns
1084 /// it as a string. This is done at the metadata level because DIEs may
1085 /// not currently have been added to the parent context and walking the
1086 /// DIEs looking for names is more expensive than walking the metadata.
1087 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1091 // FIXME: Decide whether to implement this for non-C++ languages.
1092 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1096 SmallVector<DIScope, 1> Parents;
1097 while (!Context.isCompileUnit()) {
1098 Parents.push_back(Context);
1099 if (Context.getContext())
1100 Context = resolve(Context.getContext());
1102 // Structure, etc types will have a NULL context if they're at the top
1107 // Reverse iterate over our list to go from the outermost construct to the
1109 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1113 StringRef Name = Ctx.getName();
1114 if (Name.empty() && Ctx.isNameSpace())
1115 Name = "(anonymous namespace)";
1116 if (!Name.empty()) {
1124 /// constructTypeDIE - Construct basic type die from DIBasicType.
1125 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1126 // Get core information.
1127 StringRef Name = BTy.getName();
1128 // Add name if not anonymous or intermediate type.
1130 addString(Buffer, dwarf::DW_AT_name, Name);
1132 // An unspecified type only has a name attribute.
1133 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1136 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1139 uint64_t Size = BTy.getSizeInBits() >> 3;
1140 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1143 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1144 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1145 // Get core information.
1146 StringRef Name = DTy.getName();
1147 uint64_t Size = DTy.getSizeInBits() >> 3;
1148 uint16_t Tag = Buffer.getTag();
1150 // Map to main type, void will not have a type.
1151 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1153 addType(Buffer, FromTy);
1155 // Add name if not anonymous or intermediate type.
1157 addString(Buffer, dwarf::DW_AT_name, Name);
1159 // Add size if non-zero (derived types might be zero-sized.)
1160 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1161 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1163 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1164 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1165 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1166 // Add source line info if available and TyDesc is not a forward declaration.
1167 if (!DTy.isForwardDecl())
1168 addSourceLine(Buffer, DTy);
1171 /// constructSubprogramArguments - Construct function argument DIEs.
1172 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1173 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1174 DIType Ty = resolve(Args.getElement(i));
1176 assert(i == N-1 && "Unspecified parameter must be the last argument");
1177 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1179 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1180 addType(Arg, DIType(Ty));
1181 if (DIType(Ty).isArtificial())
1182 addFlag(Arg, dwarf::DW_AT_artificial);
1187 /// constructTypeDIE - Construct type DIE from DICompositeType.
1188 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1189 // Add name if not anonymous or intermediate type.
1190 StringRef Name = CTy.getName();
1192 uint64_t Size = CTy.getSizeInBits() >> 3;
1193 uint16_t Tag = Buffer.getTag();
1196 case dwarf::DW_TAG_array_type:
1197 constructArrayTypeDIE(Buffer, CTy);
1199 case dwarf::DW_TAG_enumeration_type:
1200 constructEnumTypeDIE(Buffer, CTy);
1202 case dwarf::DW_TAG_subroutine_type: {
1203 // Add return type. A void return won't have a type.
1204 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1205 DIType RTy(resolve(Elements.getElement(0)));
1207 addType(Buffer, RTy);
1209 bool isPrototyped = true;
1210 if (Elements.getNumElements() == 2 &&
1211 !Elements.getElement(1))
1212 isPrototyped = false;
1214 constructSubprogramArguments(Buffer, Elements);
1216 // Add prototype flag if we're dealing with a C language and the
1217 // function has been prototyped.
1218 uint16_t Language = getLanguage();
1220 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1221 Language == dwarf::DW_LANG_ObjC))
1222 addFlag(Buffer, dwarf::DW_AT_prototyped);
1224 if (CTy.isLValueReference())
1225 addFlag(Buffer, dwarf::DW_AT_reference);
1227 if (CTy.isRValueReference())
1228 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1230 case dwarf::DW_TAG_structure_type:
1231 case dwarf::DW_TAG_union_type:
1232 case dwarf::DW_TAG_class_type: {
1233 // Add elements to structure type.
1234 DIArray Elements = CTy.getElements();
1235 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1236 DIDescriptor Element = Elements.getElement(i);
1237 if (Element.isSubprogram())
1238 getOrCreateSubprogramDIE(DISubprogram(Element));
1239 else if (Element.isDerivedType()) {
1240 DIDerivedType DDTy(Element);
1241 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1242 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1243 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1244 dwarf::DW_AT_friend);
1245 } else if (DDTy.isStaticMember()) {
1246 getOrCreateStaticMemberDIE(DDTy);
1248 constructMemberDIE(Buffer, DDTy);
1250 } else if (Element.isObjCProperty()) {
1251 DIObjCProperty Property(Element);
1252 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1253 StringRef PropertyName = Property.getObjCPropertyName();
1254 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1255 if (Property.getType())
1256 addType(ElemDie, Property.getType());
1257 addSourceLine(ElemDie, Property);
1258 StringRef GetterName = Property.getObjCPropertyGetterName();
1259 if (!GetterName.empty())
1260 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1261 StringRef SetterName = Property.getObjCPropertySetterName();
1262 if (!SetterName.empty())
1263 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1264 unsigned PropertyAttributes = 0;
1265 if (Property.isReadOnlyObjCProperty())
1266 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1267 if (Property.isReadWriteObjCProperty())
1268 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1269 if (Property.isAssignObjCProperty())
1270 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1271 if (Property.isRetainObjCProperty())
1272 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1273 if (Property.isCopyObjCProperty())
1274 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1275 if (Property.isNonAtomicObjCProperty())
1276 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1277 if (PropertyAttributes)
1278 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1279 PropertyAttributes);
1281 DIEEntry *Entry = getDIEEntry(Element);
1283 Entry = createDIEEntry(ElemDie);
1284 insertDIEEntry(Element, Entry);
1290 if (CTy.isAppleBlockExtension())
1291 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1293 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1295 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1296 *getOrCreateTypeDIE(ContainingType));
1298 if (CTy.isObjcClassComplete())
1299 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1301 // Add template parameters to a class, structure or union types.
1302 // FIXME: The support isn't in the metadata for this yet.
1303 if (Tag == dwarf::DW_TAG_class_type ||
1304 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1305 addTemplateParams(Buffer, CTy.getTemplateParams());
1313 // Add name if not anonymous or intermediate type.
1315 addString(Buffer, dwarf::DW_AT_name, Name);
1317 if (Tag == dwarf::DW_TAG_enumeration_type ||
1318 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1319 Tag == dwarf::DW_TAG_union_type) {
1320 // Add size if non-zero (derived types might be zero-sized.)
1321 // TODO: Do we care about size for enum forward declarations?
1323 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1324 else if (!CTy.isForwardDecl())
1325 // Add zero size if it is not a forward declaration.
1326 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1328 // If we're a forward decl, say so.
1329 if (CTy.isForwardDecl())
1330 addFlag(Buffer, dwarf::DW_AT_declaration);
1332 // Add source line info if available.
1333 if (!CTy.isForwardDecl())
1334 addSourceLine(Buffer, CTy);
1336 // No harm in adding the runtime language to the declaration.
1337 unsigned RLang = CTy.getRunTimeLang();
1339 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1344 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1345 /// DITemplateTypeParameter.
1346 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1347 DITemplateTypeParameter TP) {
1349 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1350 // Add the type if it exists, it could be void and therefore no type.
1352 addType(ParamDIE, resolve(TP.getType()));
1353 if (!TP.getName().empty())
1354 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1357 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1358 /// DITemplateValueParameter.
1360 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1361 DITemplateValueParameter VP) {
1362 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1364 // Add the type if there is one, template template and template parameter
1365 // packs will not have a type.
1366 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1367 addType(ParamDIE, resolve(VP.getType()));
1368 if (!VP.getName().empty())
1369 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1370 if (Value *Val = VP.getValue()) {
1371 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1372 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1373 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1374 // For declaration non-type template parameters (such as global values and
1376 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1377 addOpAddress(*Loc, Asm->getSymbol(GV));
1378 // Emit DW_OP_stack_value to use the address as the immediate value of the
1379 // parameter, rather than a pointer to it.
1380 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1381 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1382 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1383 assert(isa<MDString>(Val));
1384 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1385 cast<MDString>(Val)->getString());
1386 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1387 assert(isa<MDNode>(Val));
1388 DIArray A(cast<MDNode>(Val));
1389 addTemplateParams(ParamDIE, A);
1394 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1395 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1396 // Construct the context before querying for the existence of the DIE in case
1397 // such construction creates the DIE.
1398 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1400 if (DIE *NDie = getDIE(NS))
1402 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1404 StringRef Name = NS.getName();
1406 addString(NDie, dwarf::DW_AT_name, NS.getName());
1408 Name = "(anonymous namespace)";
1409 DD->addAccelNamespace(Name, NDie);
1410 addGlobalName(Name, NDie, NS.getContext());
1411 addSourceLine(NDie, NS);
1415 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1416 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1417 // Construct the context before querying for the existence of the DIE in case
1418 // such construction creates the DIE (as is the case for member function
1420 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1422 if (DIE *SPDie = getDIE(SP))
1425 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1426 // Add subprogram definitions to the CU die directly.
1427 ContextDIE = &getUnitDie();
1428 // Build the decl now to ensure it precedes the definition.
1429 getOrCreateSubprogramDIE(SPDecl);
1432 // DW_TAG_inlined_subroutine may refer to this DIE.
1433 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1435 // Stop here and fill this in later, depending on whether or not this
1436 // subprogram turns out to have inlined instances or not.
1437 if (SP.isDefinition())
1440 applySubprogramAttributes(SP, SPDie);
1444 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1445 DISubprogram SPDecl = SP.getFunctionDeclaration();
1446 DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1447 applySubprogramAttributes(SP, SPDie);
1448 addGlobalName(SP.getName(), SPDie, Context);
1451 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1452 DIE *DeclDie = nullptr;
1453 StringRef DeclLinkageName;
1454 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1455 DeclDie = getDIE(SPDecl);
1456 assert(DeclDie && "This DIE should've already been constructed when the "
1457 "definition DIE was created in "
1458 "getOrCreateSubprogramDIE");
1459 DeclLinkageName = SPDecl.getLinkageName();
1462 // Add function template parameters.
1463 addTemplateParams(SPDie, SP.getTemplateParams());
1465 // Add the linkage name if we have one and it isn't in the Decl.
1466 StringRef LinkageName = SP.getLinkageName();
1467 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1468 LinkageName == DeclLinkageName) &&
1469 "decl has a linkage name and it is different");
1470 if (!LinkageName.empty() && DeclLinkageName.empty())
1471 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1472 GlobalValue::getRealLinkageName(LinkageName));
1475 // Refer to the function declaration where all the other attributes will be
1477 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1481 // Constructors and operators for anonymous aggregates do not have names.
1482 if (!SP.getName().empty())
1483 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1485 addSourceLine(SPDie, SP);
1487 // Add the prototype if we have a prototype and we have a C like
1489 uint16_t Language = getLanguage();
1490 if (SP.isPrototyped() &&
1491 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1492 Language == dwarf::DW_LANG_ObjC))
1493 addFlag(SPDie, dwarf::DW_AT_prototyped);
1495 DISubroutineType SPTy = SP.getType();
1496 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1497 "the type of a subprogram should be a subroutine");
1499 DITypeArray Args = SPTy.getTypeArray();
1500 // Add a return type. If this is a type like a C/C++ void type we don't add a
1502 if (resolve(Args.getElement(0)))
1503 addType(SPDie, DIType(resolve(Args.getElement(0))));
1505 unsigned VK = SP.getVirtuality();
1507 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1508 DIELoc *Block = getDIELoc();
1509 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1510 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1511 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1512 ContainingTypeMap.insert(
1513 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1516 if (!SP.isDefinition()) {
1517 addFlag(SPDie, dwarf::DW_AT_declaration);
1519 // Add arguments. Do not add arguments for subprogram definition. They will
1520 // be handled while processing variables.
1521 constructSubprogramArguments(SPDie, Args);
1524 if (SP.isArtificial())
1525 addFlag(SPDie, dwarf::DW_AT_artificial);
1527 if (!SP.isLocalToUnit())
1528 addFlag(SPDie, dwarf::DW_AT_external);
1530 if (SP.isOptimized())
1531 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1533 if (unsigned isa = Asm->getISAEncoding()) {
1534 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1537 if (SP.isLValueReference())
1538 addFlag(SPDie, dwarf::DW_AT_reference);
1540 if (SP.isRValueReference())
1541 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1543 if (SP.isProtected())
1544 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1545 dwarf::DW_ACCESS_protected);
1546 else if (SP.isPrivate())
1547 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1548 dwarf::DW_ACCESS_private);
1549 else if (SP.isPublic())
1550 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1551 dwarf::DW_ACCESS_public);
1553 if (SP.isExplicit())
1554 addFlag(SPDie, dwarf::DW_AT_explicit);
1557 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1559 StringRef Name = Var.getName();
1561 addString(VariableDie, dwarf::DW_AT_name, Name);
1562 addSourceLine(VariableDie, Var.getVariable());
1563 addType(VariableDie, Var.getType());
1564 if (Var.isArtificial())
1565 addFlag(VariableDie, dwarf::DW_AT_artificial);
1568 // Return const expression if value is a GEP to access merged global
1570 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1571 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1572 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1573 if (!CE || CE->getNumOperands() != 3 ||
1574 CE->getOpcode() != Instruction::GetElementPtr)
1577 // First operand points to a global struct.
1578 Value *Ptr = CE->getOperand(0);
1579 if (!isa<GlobalValue>(Ptr) ||
1580 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1583 // Second operand is zero.
1584 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1585 if (!CI || !CI->isZero())
1588 // Third operand is offset.
1589 if (!isa<ConstantInt>(CE->getOperand(2)))
1595 /// createGlobalVariableDIE - create global variable DIE.
1596 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1597 // Check for pre-existence.
1601 assert(GV.isGlobalVariable());
1603 DIScope GVContext = GV.getContext();
1604 DIType GTy = DD->resolve(GV.getType());
1606 // If this is a static data member definition, some attributes belong
1607 // to the declaration DIE.
1608 DIE *VariableDIE = nullptr;
1609 bool IsStaticMember = false;
1610 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1611 if (SDMDecl.Verify()) {
1612 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1613 // We need the declaration DIE that is in the static member's class.
1614 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1615 IsStaticMember = true;
1618 // If this is not a static data member definition, create the variable
1619 // DIE and add the initial set of attributes to it.
1621 // Construct the context before querying for the existence of the DIE in
1622 // case such construction creates the DIE.
1623 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1626 VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1628 // Add name and type.
1629 addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1630 addType(*VariableDIE, GTy);
1632 // Add scoping info.
1633 if (!GV.isLocalToUnit())
1634 addFlag(*VariableDIE, dwarf::DW_AT_external);
1636 // Add line number info.
1637 addSourceLine(*VariableDIE, GV);
1641 bool addToAccelTable = false;
1642 DIE *VariableSpecDIE = nullptr;
1643 bool isGlobalVariable = GV.getGlobal() != nullptr;
1644 if (isGlobalVariable) {
1645 addToAccelTable = true;
1646 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1647 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1648 if (GV.getGlobal()->isThreadLocal()) {
1649 // FIXME: Make this work with -gsplit-dwarf.
1650 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1651 assert((PointerSize == 4 || PointerSize == 8) &&
1652 "Add support for other sizes if necessary");
1653 // Based on GCC's support for TLS:
1654 if (!DD->useSplitDwarf()) {
1655 // 1) Start with a constNu of the appropriate pointer size
1656 addUInt(*Loc, dwarf::DW_FORM_data1,
1657 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1658 // 2) containing the (relocated) offset of the TLS variable
1659 // within the module's TLS block.
1660 addExpr(*Loc, dwarf::DW_FORM_udata,
1661 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1663 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1664 addUInt(*Loc, dwarf::DW_FORM_udata,
1665 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1667 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1668 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1670 DD->addArangeLabel(SymbolCU(this, Sym));
1671 addOpAddress(*Loc, Sym);
1673 // A static member's declaration is already flagged as such.
1674 if (!SDMDecl.Verify() && !GV.isDefinition())
1675 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1676 // Do not create specification DIE if context is either compile unit
1678 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1679 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1680 // Create specification DIE.
1681 VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
1682 addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
1683 addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1684 // A static member's declaration is already flagged as such.
1685 if (!SDMDecl.Verify())
1686 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1688 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1690 // Add the linkage name.
1691 StringRef LinkageName = GV.getLinkageName();
1692 if (!LinkageName.empty())
1693 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1694 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1696 addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1698 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1699 : dwarf::DW_AT_MIPS_linkage_name,
1700 GlobalValue::getRealLinkageName(LinkageName));
1701 } else if (const ConstantInt *CI =
1702 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1703 // AT_const_value was added when the static member was created. To avoid
1704 // emitting AT_const_value multiple times, we only add AT_const_value when
1705 // it is not a static member.
1706 if (!IsStaticMember)
1707 addConstantValue(*VariableDIE, CI, GTy);
1708 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1709 addToAccelTable = true;
1710 // GV is a merged global.
1711 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1712 Value *Ptr = CE->getOperand(0);
1713 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1714 DD->addArangeLabel(SymbolCU(this, Sym));
1715 addOpAddress(*Loc, Sym);
1716 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1717 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1718 addUInt(*Loc, dwarf::DW_FORM_udata,
1719 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1720 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1721 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1724 if (addToAccelTable) {
1725 DIE &AddrDIE = VariableSpecDIE ? *VariableSpecDIE : *VariableDIE;
1726 DD->addAccelName(GV.getName(), AddrDIE);
1728 // If the linkage name is different than the name, go ahead and output
1729 // that as well into the name table.
1730 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1731 DD->addAccelName(GV.getLinkageName(), AddrDIE);
1734 addGlobalName(GV.getName(), VariableSpecDIE ? *VariableSpecDIE : *VariableDIE,
1738 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1739 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1740 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1741 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1743 // The LowerBound value defines the lower bounds which is typically zero for
1744 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1745 // Count == -1 then the array is unbounded and we do not emit
1746 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1747 // Count == 0, then the array has zero elements in which case we do not emit
1749 int64_t LowerBound = SR.getLo();
1750 int64_t DefaultLowerBound = getDefaultLowerBound();
1751 int64_t Count = SR.getCount();
1753 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1754 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1756 if (Count != -1 && Count != 0)
1757 // FIXME: An unbounded array should reference the expression that defines
1759 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1760 LowerBound + Count - 1);
1763 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1764 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1766 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1768 // Emit the element type.
1769 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1771 // Get an anonymous type for index type.
1772 // FIXME: This type should be passed down from the front end
1773 // as different languages may have different sizes for indexes.
1774 DIE *IdxTy = getIndexTyDie();
1776 // Construct an integer type to use for indexes.
1777 IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1778 addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1779 addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1780 addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1781 dwarf::DW_ATE_unsigned);
1782 setIndexTyDie(IdxTy);
1785 // Add subranges to array type.
1786 DIArray Elements = CTy.getElements();
1787 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1788 DIDescriptor Element = Elements.getElement(i);
1789 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1790 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1794 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1795 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1796 DIArray Elements = CTy.getElements();
1798 // Add enumerators to enumeration type.
1799 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1800 DIEnumerator Enum(Elements.getElement(i));
1801 if (Enum.isEnumerator()) {
1802 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1803 StringRef Name = Enum.getName();
1804 addString(Enumerator, dwarf::DW_AT_name, Name);
1805 int64_t Value = Enum.getEnumValue();
1806 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1810 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1812 addType(Buffer, DTy);
1813 addFlag(Buffer, dwarf::DW_AT_enum_class);
1817 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1819 void DwarfUnit::constructContainingTypeDIEs() {
1820 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1821 CE = ContainingTypeMap.end();
1823 DIE &SPDie = *CI->first;
1824 DIDescriptor D(CI->second);
1827 DIE *NDie = getDIE(D);
1830 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1834 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1835 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1837 auto D = constructVariableDIEImpl(DV, Abstract);
1842 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1844 // Define variable debug information entry.
1845 auto VariableDie = make_unique<DIE>(DV.getTag());
1848 applyVariableAttributes(DV, *VariableDie);
1852 // Add variable address.
1854 unsigned Offset = DV.getDotDebugLocOffset();
1855 if (Offset != ~0U) {
1856 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1860 // Check if variable is described by a DBG_VALUE instruction.
1861 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1862 assert(DVInsn->getNumOperands() == 3);
1863 if (DVInsn->getOperand(0).isReg()) {
1864 const MachineOperand RegOp = DVInsn->getOperand(0);
1865 // If the second operand is an immediate, this is an indirect value.
1866 if (DVInsn->getOperand(1).isImm()) {
1867 MachineLocation Location(RegOp.getReg(),
1868 DVInsn->getOperand(1).getImm());
1869 addVariableAddress(DV, *VariableDie, Location);
1870 } else if (RegOp.getReg())
1871 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1872 } else if (DVInsn->getOperand(0).isImm())
1873 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1874 else if (DVInsn->getOperand(0).isFPImm())
1875 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1876 else if (DVInsn->getOperand(0).isCImm())
1877 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1883 // .. else use frame index.
1884 int FI = DV.getFrameIndex();
1886 unsigned FrameReg = 0;
1887 const TargetFrameLowering *TFI =
1888 Asm->TM.getSubtargetImpl()->getFrameLowering();
1889 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1890 MachineLocation Location(FrameReg, Offset);
1891 addVariableAddress(DV, *VariableDie, Location);
1897 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1898 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1899 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1900 StringRef Name = DT.getName();
1902 addString(MemberDie, dwarf::DW_AT_name, Name);
1904 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1906 addSourceLine(MemberDie, DT);
1908 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1910 // For C++, virtual base classes are not at fixed offset. Use following
1911 // expression to extract appropriate offset from vtable.
1912 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1914 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1915 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1916 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1917 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1918 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1919 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1920 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1921 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1923 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1925 uint64_t Size = DT.getSizeInBits();
1926 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1927 uint64_t OffsetInBytes;
1929 if (Size != FieldSize) {
1930 // Handle bitfield, assume bytes are 8 bits.
1931 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1932 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1934 uint64_t Offset = DT.getOffsetInBits();
1935 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1936 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1937 uint64_t FieldOffset = (HiMark - FieldSize);
1938 Offset -= FieldOffset;
1940 // Maybe we need to work from the other end.
1941 if (Asm->getDataLayout().isLittleEndian())
1942 Offset = FieldSize - (Offset + Size);
1943 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1945 // Here DW_AT_data_member_location points to the anonymous
1946 // field that includes this bit field.
1947 OffsetInBytes = FieldOffset >> 3;
1949 // This is not a bitfield.
1950 OffsetInBytes = DT.getOffsetInBits() >> 3;
1952 if (DD->getDwarfVersion() <= 2) {
1953 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1954 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1955 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1956 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1958 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1962 if (DT.isProtected())
1963 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1964 dwarf::DW_ACCESS_protected);
1965 else if (DT.isPrivate())
1966 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1967 dwarf::DW_ACCESS_private);
1968 // Otherwise C++ member and base classes are considered public.
1969 else if (DT.isPublic())
1970 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1971 dwarf::DW_ACCESS_public);
1973 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1974 dwarf::DW_VIRTUALITY_virtual);
1976 // Objective-C properties.
1977 if (MDNode *PNode = DT.getObjCProperty())
1978 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1979 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1982 if (DT.isArtificial())
1983 addFlag(MemberDie, dwarf::DW_AT_artificial);
1986 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1987 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1991 // Construct the context before querying for the existence of the DIE in case
1992 // such construction creates the DIE.
1993 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1994 assert(dwarf::isType(ContextDIE->getTag()) &&
1995 "Static member should belong to a type.");
1997 if (DIE *StaticMemberDIE = getDIE(DT))
1998 return StaticMemberDIE;
2000 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
2002 DIType Ty = resolve(DT.getTypeDerivedFrom());
2004 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2005 addType(StaticMemberDIE, Ty);
2006 addSourceLine(StaticMemberDIE, DT);
2007 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2008 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2010 // FIXME: We could omit private if the parent is a class_type, and
2011 // public if the parent is something else.
2012 if (DT.isProtected())
2013 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2014 dwarf::DW_ACCESS_protected);
2015 else if (DT.isPrivate())
2016 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2017 dwarf::DW_ACCESS_private);
2018 else if (DT.isPublic())
2019 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2020 dwarf::DW_ACCESS_public);
2022 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2023 addConstantValue(StaticMemberDIE, CI, Ty);
2024 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2025 addConstantFPValue(StaticMemberDIE, CFP);
2027 return &StaticMemberDIE;
2030 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2031 Asm->OutStreamer.AddComment("DWARF version number");
2032 Asm->EmitInt16(DD->getDwarfVersion());
2033 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2034 // We share one abbreviations table across all units so it's always at the
2035 // start of the section. Use a relocatable offset where needed to ensure
2036 // linking doesn't invalidate that offset.
2038 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2040 // Use a constant value when no symbol is provided.
2042 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2043 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2046 void DwarfCompileUnit::addRange(RangeSpan Range) {
2047 // Only add a range for this unit if we're emitting full debug.
2048 if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2049 bool SameAsPrevCU = this == DD->getPrevCU();
2050 DD->setPrevCU(this);
2051 // If we have no current ranges just add the range and return, otherwise,
2052 // check the current section and CU against the previous section and CU we
2053 // emitted into and the subprogram was contained within. If these are the
2054 // same then extend our current range, otherwise add this as a new range.
2055 if (CURanges.empty() || !SameAsPrevCU ||
2056 (&CURanges.back().getEnd()->getSection() !=
2057 &Range.getEnd()->getSection())) {
2058 CURanges.push_back(Range);
2062 CURanges.back().setEnd(Range.getEnd());
2066 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2067 // Define start line table label for each Compile Unit.
2068 MCSymbol *LineTableStartSym =
2069 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2071 stmtListIndex = UnitDie.getValues().size();
2073 // DW_AT_stmt_list is a offset of line number information for this
2074 // compile unit in debug_line section. For split dwarf this is
2075 // left in the skeleton CU and so not included.
2076 // The line table entries are not always emitted in assembly, so it
2077 // is not okay to use line_table_start here.
2078 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2079 addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
2081 addSectionDelta(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
2082 DwarfLineSectionSym);
2085 void DwarfCompileUnit::applyStmtList(DIE &D) {
2086 D.addValue(dwarf::DW_AT_stmt_list,
2087 UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
2088 UnitDie.getValues()[stmtListIndex]);
2091 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2092 DwarfUnit::emitHeader(ASectionSym);
2093 Asm->OutStreamer.AddComment("Type Signature");
2094 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2095 Asm->OutStreamer.AddComment("Type DIE Offset");
2096 // In a skeleton type unit there is no type DIE so emit a zero offset.
2097 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2098 sizeof(Ty->getOffset()));
2101 void DwarfTypeUnit::initSection(const MCSection *Section) {
2102 assert(!this->Section);
2103 this->Section = Section;
2104 // Since each type unit is contained in its own COMDAT section, the begin
2105 // label and the section label are the same. Using the begin label emission in
2106 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2107 // the only other alternative of lazily constructing start-of-section labels
2108 // and storing a mapping in DwarfDebug (or AsmPrinter).
2109 this->SectionSym = this->LabelBegin =
2110 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2112 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());