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"
36 #define DEBUG_TYPE "dwarfdebug"
39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
40 cl::desc("Generate DWARF4 type units."),
43 /// Unit - Unit constructor.
44 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
45 DwarfDebug *DW, DwarfFile *DWU)
46 : UniqueID(UID), CUNode(Node), UnitDie(D), DebugInfoOffset(0), Asm(A),
47 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr),
49 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
52 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
53 AsmPrinter *A, DwarfDebug *DW,
55 : DwarfUnit(UID, D, Node, A, DW, DWU) {
59 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DwarfCompileUnit &CU,
60 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU,
61 MCDwarfDwoLineTable *SplitLineTable)
62 : DwarfUnit(UID, D, CU.getCUNode(), A, DW, DWU), CU(CU),
63 SplitLineTable(SplitLineTable) {
65 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
68 /// ~Unit - Destructor for compile unit.
69 DwarfUnit::~DwarfUnit() {
70 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
71 DIEBlocks[j]->~DIEBlock();
72 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
73 DIELocs[j]->~DIELoc();
76 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
77 /// information entry.
78 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
79 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
83 /// getDefaultLowerBound - Return the default lower bound for an array. If the
84 /// DWARF version doesn't handle the language, return -1.
85 int64_t DwarfUnit::getDefaultLowerBound() const {
86 switch (getLanguage()) {
90 case dwarf::DW_LANG_C89:
91 case dwarf::DW_LANG_C99:
92 case dwarf::DW_LANG_C:
93 case dwarf::DW_LANG_C_plus_plus:
94 case dwarf::DW_LANG_ObjC:
95 case dwarf::DW_LANG_ObjC_plus_plus:
98 case dwarf::DW_LANG_Fortran77:
99 case dwarf::DW_LANG_Fortran90:
100 case dwarf::DW_LANG_Fortran95:
103 // The languages below have valid values only if the DWARF version >= 4.
104 case dwarf::DW_LANG_Java:
105 case dwarf::DW_LANG_Python:
106 case dwarf::DW_LANG_UPC:
107 case dwarf::DW_LANG_D:
108 if (dwarf::DWARF_VERSION >= 4)
112 case dwarf::DW_LANG_Ada83:
113 case dwarf::DW_LANG_Ada95:
114 case dwarf::DW_LANG_Cobol74:
115 case dwarf::DW_LANG_Cobol85:
116 case dwarf::DW_LANG_Modula2:
117 case dwarf::DW_LANG_Pascal83:
118 case dwarf::DW_LANG_PLI:
119 if (dwarf::DWARF_VERSION >= 4)
127 /// Check whether the DIE for this MDNode can be shared across CUs.
128 static bool isShareableAcrossCUs(DIDescriptor D) {
129 // When the MDNode can be part of the type system, the DIE can be shared
131 // Combining type units and cross-CU DIE sharing is lower value (since
132 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
133 // level already) but may be implementable for some value in projects
134 // building multiple independent libraries with LTO and then linking those
136 return (D.isType() ||
137 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
138 !GenerateDwarfTypeUnits;
141 /// getDIE - Returns the debug information entry map slot for the
142 /// specified debug variable. We delegate the request to DwarfDebug
143 /// when the DIE for this MDNode can be shared across CUs. The mappings
144 /// will be kept in DwarfDebug for shareable DIEs.
145 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
146 if (isShareableAcrossCUs(D))
147 return DD->getDIE(D);
148 return MDNodeToDieMap.lookup(D);
151 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
152 /// when the DIE for this MDNode can be shared across CUs. The mappings
153 /// will be kept in DwarfDebug for shareable DIEs.
154 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
155 if (isShareableAcrossCUs(Desc)) {
156 DD->insertDIE(Desc, D);
159 MDNodeToDieMap.insert(std::make_pair(Desc, D));
162 /// addFlag - Add a flag that is true.
163 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
164 if (DD->getDwarfVersion() >= 4)
165 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
167 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
170 /// addUInt - Add an unsigned integer attribute data and value.
172 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
173 Optional<dwarf::Form> Form, uint64_t Integer) {
175 Form = DIEInteger::BestForm(false, Integer);
176 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
178 Die->addValue(Attribute, *Form, Value);
181 void DwarfUnit::addUInt(DIE *Block, dwarf::Form Form, uint64_t Integer) {
182 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
185 /// addSInt - Add an signed integer attribute data and value.
187 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
188 Optional<dwarf::Form> Form, int64_t Integer) {
190 Form = DIEInteger::BestForm(true, Integer);
191 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
192 Die->addValue(Attribute, *Form, Value);
195 void DwarfUnit::addSInt(DIELoc *Die, Optional<dwarf::Form> Form,
197 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
200 /// addString - Add a string attribute data and value. We always emit a
201 /// reference to the string pool instead of immediate strings so that DIEs have
202 /// more predictable sizes. In the case of split dwarf we emit an index
203 /// into another table which gets us the static offset into the string
205 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
208 if (!DD->useSplitDwarf())
209 return addLocalString(Die, Attribute, String);
211 unsigned idx = DU->getStringPoolIndex(String);
212 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
213 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
214 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
217 /// addLocalString - Add a string attribute data and value. This is guaranteed
218 /// to be in the local string pool instead of indirected.
219 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
221 MCSymbol *Symb = DU->getStringPoolEntry(String);
223 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
224 Value = new (DIEValueAllocator) DIELabel(Symb);
226 MCSymbol *StringPool = DU->getStringPoolSym();
227 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
229 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
230 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
233 /// addExpr - Add a Dwarf expression attribute data and value.
235 void DwarfUnit::addExpr(DIELoc *Die, dwarf::Form Form, const MCExpr *Expr) {
236 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
237 Die->addValue((dwarf::Attribute)0, Form, Value);
240 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
242 void DwarfUnit::addLocationList(DIE *Die, dwarf::Attribute Attribute,
244 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
245 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
246 : dwarf::DW_FORM_data4;
247 Die->addValue(Attribute, Form, Value);
250 /// addLabel - Add a Dwarf label attribute data and value.
252 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
253 const MCSymbol *Label) {
254 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
255 Die->addValue(Attribute, Form, Value);
258 void DwarfUnit::addLabel(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) {
259 addLabel(Die, (dwarf::Attribute)0, Form, Label);
262 /// addSectionLabel - Add a Dwarf section label attribute data and value.
264 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
265 const MCSymbol *Label) {
266 if (DD->getDwarfVersion() >= 4)
267 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
269 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
272 /// addSectionOffset - Add an offset into a section attribute data and value.
274 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
276 if (DD->getDwarfVersion() >= 4)
277 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
279 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
282 /// addLabelAddress - Add a dwarf label attribute data and value using
283 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
285 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
286 const MCSymbol *Label) {
288 if (!DD->useSplitDwarf())
289 return addLocalLabelAddress(Die, Attribute, Label);
292 DD->addArangeLabel(SymbolCU(this, Label));
294 unsigned idx = DD->getAddressPool().getIndex(Label);
295 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
296 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
299 void DwarfCompileUnit::addLocalLabelAddress(DIE *Die,
300 dwarf::Attribute Attribute,
301 const MCSymbol *Label) {
303 DD->addArangeLabel(SymbolCU(this, Label));
306 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
307 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
309 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
310 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
314 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
315 // If we print assembly, we can't separate .file entries according to
316 // compile units. Thus all files will belong to the default compile unit.
318 // FIXME: add a better feature test than hasRawTextSupport. Even better,
319 // extend .file to support this.
320 return Asm->OutStreamer.EmitDwarfFileDirective(
321 0, DirName, FileName,
322 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
325 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
326 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
327 : getCU().getOrCreateSourceID(FileName, DirName);
330 /// addOpAddress - Add a dwarf op address data and value using the
331 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
333 void DwarfUnit::addOpAddress(DIELoc *Die, const MCSymbol *Sym) {
334 if (!DD->useSplitDwarf()) {
335 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
336 addLabel(Die, dwarf::DW_FORM_udata, Sym);
338 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
339 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
340 DD->getAddressPool().getIndex(Sym));
344 /// addSectionDelta - Add a section label delta attribute data and value.
346 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
347 const MCSymbol *Hi, const MCSymbol *Lo) {
348 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
349 if (DD->getDwarfVersion() >= 4)
350 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
352 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
355 void DwarfUnit::addLabelDelta(DIE *Die, dwarf::Attribute Attribute,
356 const MCSymbol *Hi, const MCSymbol *Lo) {
357 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
358 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
361 /// addDIEEntry - Add a DIE attribute data and value.
363 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
364 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
367 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
368 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
369 new (DIEValueAllocator) DIETypeSignature(Type));
372 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
374 const DIE *DieCU = Die->getUnitOrNull();
375 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
377 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
378 DieCU = getUnitDie();
380 EntryCU = getUnitDie();
381 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
382 : dwarf::DW_FORM_ref_addr,
386 /// Create a DIE with the given Tag, add the DIE to its parent, and
387 /// call insertDIE if MD is not null.
388 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
389 assert(Tag != dwarf::DW_TAG_auto_variable &&
390 Tag != dwarf::DW_TAG_arg_variable);
391 DIE *Die = new DIE((dwarf::Tag)Tag);
392 Parent.addChild(Die);
398 /// addBlock - Add block data.
400 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIELoc *Loc) {
401 Loc->ComputeSize(Asm);
402 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
403 Die->addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
406 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
408 Block->ComputeSize(Asm);
409 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
410 Die->addValue(Attribute, Block->BestForm(), Block);
413 /// addSourceLine - Add location information to specified debug information
415 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
416 StringRef Directory) {
420 unsigned FileID = getOrCreateSourceID(File, Directory);
421 assert(FileID && "Invalid file id");
422 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
423 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
426 /// addSourceLine - Add location information to specified debug information
428 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
429 assert(V.isVariable());
431 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
432 V.getContext().getDirectory());
435 /// addSourceLine - Add location information to specified debug information
437 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
438 assert(G.isGlobalVariable());
440 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
443 /// addSourceLine - Add location information to specified debug information
445 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
446 assert(SP.isSubprogram());
448 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
451 /// addSourceLine - Add location information to specified debug information
453 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
456 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
459 /// addSourceLine - Add location information to specified debug information
461 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
462 assert(Ty.isObjCProperty());
464 DIFile File = Ty.getFile();
465 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
466 File.getDirectory());
469 /// addSourceLine - Add location information to specified debug information
471 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
474 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
477 /// addVariableAddress - Add DW_AT_location attribute for a
478 /// DbgVariable based on provided MachineLocation.
479 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
480 MachineLocation Location) {
481 if (DV.variableHasComplexAddress())
482 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
483 else if (DV.isBlockByrefVariable())
484 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
486 addAddress(Die, dwarf::DW_AT_location, Location,
487 DV.getVariable().isIndirect());
490 /// addRegisterOp - Add register operand.
491 void DwarfUnit::addRegisterOp(DIELoc *TheDie, unsigned Reg) {
492 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
493 int DWReg = RI->getDwarfRegNum(Reg, false);
494 bool isSubRegister = DWReg < 0;
498 // Go up the super-register chain until we hit a valid dwarf register number.
499 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
500 DWReg = RI->getDwarfRegNum(*SR, false);
502 Idx = RI->getSubRegIndex(*SR, Reg);
506 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
507 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
513 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
515 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
516 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
521 unsigned Size = RI->getSubRegIdxSize(Idx);
522 unsigned Offset = RI->getSubRegIdxOffset(Idx);
524 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
525 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
526 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
528 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
529 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
530 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
535 /// addRegisterOffset - Add register offset.
536 void DwarfUnit::addRegisterOffset(DIELoc *TheDie, unsigned Reg,
538 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
539 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
540 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
541 if (Reg == TRI->getFrameRegister(*Asm->MF))
542 // If variable offset is based in frame register then use fbreg.
543 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
545 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
547 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
548 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
550 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
553 /// addAddress - Add an address attribute to a die based on the location
555 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
556 const MachineLocation &Location, bool Indirect) {
557 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
559 if (Location.isReg() && !Indirect)
560 addRegisterOp(Loc, Location.getReg());
562 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
563 if (Indirect && !Location.isReg()) {
564 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
568 // Now attach the location information to the DIE.
569 addBlock(Die, Attribute, Loc);
572 /// addComplexAddress - Start with the address based on the location provided,
573 /// and generate the DWARF information necessary to find the actual variable
574 /// given the extra address information encoded in the DbgVariable, starting
575 /// from the starting location. Add the DWARF information to the die.
577 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
578 dwarf::Attribute Attribute,
579 const MachineLocation &Location) {
580 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
581 unsigned N = DV.getNumAddrElements();
583 if (Location.isReg()) {
584 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
585 // If first address element is OpPlus then emit
586 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
587 addRegisterOffset(Loc, Location.getReg(), DV.getAddrElement(1));
590 addRegisterOp(Loc, Location.getReg());
592 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
595 uint64_t Element = DV.getAddrElement(i);
596 if (Element == DIBuilder::OpPlus) {
597 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
598 addUInt(Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
599 } else if (Element == DIBuilder::OpDeref) {
600 if (!Location.isReg())
601 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
603 llvm_unreachable("unknown DIBuilder Opcode");
606 // Now attach the location information to the DIE.
607 addBlock(Die, Attribute, Loc);
610 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
611 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
612 gives the variable VarName either the struct, or a pointer to the struct, as
613 its type. This is necessary for various behind-the-scenes things the
614 compiler needs to do with by-reference variables in Blocks.
616 However, as far as the original *programmer* is concerned, the variable
617 should still have type 'SomeType', as originally declared.
619 The function getBlockByrefType dives into the __Block_byref_x_VarName
620 struct to find the original type of the variable, which is then assigned to
621 the variable's Debug Information Entry as its real type. So far, so good.
622 However now the debugger will expect the variable VarName to have the type
623 SomeType. So we need the location attribute for the variable to be an
624 expression that explains to the debugger how to navigate through the
625 pointers and struct to find the actual variable of type SomeType.
627 The following function does just that. We start by getting
628 the "normal" location for the variable. This will be the location
629 of either the struct __Block_byref_x_VarName or the pointer to the
630 struct __Block_byref_x_VarName.
632 The struct will look something like:
634 struct __Block_byref_x_VarName {
636 struct __Block_byref_x_VarName *forwarding;
637 ... <various other fields>
639 ... <maybe more fields>
642 If we are given the struct directly (as our starting point) we
643 need to tell the debugger to:
645 1). Add the offset of the forwarding field.
647 2). Follow that pointer to get the real __Block_byref_x_VarName
648 struct to use (the real one may have been copied onto the heap).
650 3). Add the offset for the field VarName, to find the actual variable.
652 If we started with a pointer to the struct, then we need to
653 dereference that pointer first, before the other steps.
654 Translating this into DWARF ops, we will need to append the following
655 to the current location description for the variable:
657 DW_OP_deref -- optional, if we start with a pointer
658 DW_OP_plus_uconst <forward_fld_offset>
660 DW_OP_plus_uconst <varName_fld_offset>
662 That is what this function does. */
664 /// addBlockByrefAddress - Start with the address based on the location
665 /// provided, and generate the DWARF information necessary to find the
666 /// actual Block variable (navigating the Block struct) based on the
667 /// starting location. Add the DWARF information to the die. For
668 /// more information, read large comment just above here.
670 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
671 dwarf::Attribute Attribute,
672 const MachineLocation &Location) {
673 DIType Ty = DV.getType();
675 uint16_t Tag = Ty.getTag();
676 bool isPointer = false;
678 StringRef varName = DV.getName();
680 if (Tag == dwarf::DW_TAG_pointer_type) {
681 DIDerivedType DTy(Ty);
682 TmpTy = resolve(DTy.getTypeDerivedFrom());
686 DICompositeType blockStruct(TmpTy);
688 // Find the __forwarding field and the variable field in the __Block_byref
690 DIArray Fields = blockStruct.getTypeArray();
691 DIDerivedType varField;
692 DIDerivedType forwardingField;
694 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
695 DIDerivedType DT(Fields.getElement(i));
696 StringRef fieldName = DT.getName();
697 if (fieldName == "__forwarding")
698 forwardingField = DT;
699 else if (fieldName == varName)
703 // Get the offsets for the forwarding field and the variable field.
704 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
705 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
707 // Decode the original location, and use that as the start of the byref
708 // variable's location.
709 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
711 if (Location.isReg())
712 addRegisterOp(Loc, Location.getReg());
714 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
716 // If we started with a pointer to the __Block_byref... struct, then
717 // the first thing we need to do is dereference the pointer (DW_OP_deref).
719 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
721 // Next add the offset for the '__forwarding' field:
722 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
723 // adding the offset if it's 0.
724 if (forwardingFieldOffset > 0) {
725 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
726 addUInt(Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
729 // Now dereference the __forwarding field to get to the real __Block_byref
730 // struct: DW_OP_deref.
731 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
733 // Now that we've got the real __Block_byref... struct, add the offset
734 // for the variable's field to get to the location of the actual variable:
735 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
736 if (varFieldOffset > 0) {
737 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
738 addUInt(Loc, dwarf::DW_FORM_udata, varFieldOffset);
741 // Now attach the location information to the DIE.
742 addBlock(Die, Attribute, Loc);
745 /// isTypeSigned - Return true if the type is signed.
746 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
747 if (Ty.isDerivedType())
748 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
750 if (Ty.isBasicType())
751 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
752 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
753 *SizeInBits = Ty.getSizeInBits();
759 /// Return true if type encoding is unsigned.
760 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
761 DIDerivedType DTy(Ty);
762 if (DTy.isDerivedType())
763 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
766 if (BTy.isBasicType()) {
767 unsigned Encoding = BTy.getEncoding();
768 if (Encoding == dwarf::DW_ATE_unsigned ||
769 Encoding == dwarf::DW_ATE_unsigned_char ||
770 Encoding == dwarf::DW_ATE_boolean)
776 /// If this type is derived from a base type then return base type size.
777 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
778 unsigned Tag = Ty.getTag();
780 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
781 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
782 Tag != dwarf::DW_TAG_restrict_type)
783 return Ty.getSizeInBits();
785 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
787 // If this type is not derived from any type or the type is a declaration then
788 // take conservative approach.
789 if (!BaseType.isValid() || BaseType.isForwardDecl())
790 return Ty.getSizeInBits();
792 // If this is a derived type, go ahead and get the base type, unless it's a
793 // reference then it's just the size of the field. Pointer types have no need
794 // of this since they're a different type of qualification on the type.
795 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
796 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
797 return Ty.getSizeInBits();
799 if (BaseType.isDerivedType())
800 return getBaseTypeSize(DD, DIDerivedType(BaseType));
802 return BaseType.getSizeInBits();
805 /// addConstantValue - Add constant value entry in variable DIE.
806 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
808 // FIXME: This is a bit conservative/simple - it emits negative values at
809 // their maximum bit width which is a bit unfortunate (& doesn't prefer
810 // udata/sdata over dataN as suggested by the DWARF spec)
811 assert(MO.isImm() && "Invalid machine operand!");
813 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
816 // If we're a signed constant definitely use sdata.
817 if (SignedConstant) {
818 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
822 // Else use data for now unless it's larger than we can deal with.
823 switch (SizeInBits) {
825 Form = dwarf::DW_FORM_data1;
828 Form = dwarf::DW_FORM_data2;
831 Form = dwarf::DW_FORM_data4;
834 Form = dwarf::DW_FORM_data8;
837 Form = dwarf::DW_FORM_udata;
838 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
841 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
844 /// addConstantFPValue - Add constant value entry in variable DIE.
845 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
846 assert(MO.isFPImm() && "Invalid machine operand!");
847 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
848 APFloat FPImm = MO.getFPImm()->getValueAPF();
850 // Get the raw data form of the floating point.
851 const APInt FltVal = FPImm.bitcastToAPInt();
852 const char *FltPtr = (const char *)FltVal.getRawData();
854 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
855 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
856 int Incr = (LittleEndian ? 1 : -1);
857 int Start = (LittleEndian ? 0 : NumBytes - 1);
858 int Stop = (LittleEndian ? NumBytes : -1);
860 // Output the constant to DWARF one byte at a time.
861 for (; Start != Stop; Start += Incr)
862 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
864 addBlock(Die, dwarf::DW_AT_const_value, Block);
867 /// addConstantFPValue - Add constant value entry in variable DIE.
868 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
869 // Pass this down to addConstantValue as an unsigned bag of bits.
870 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
873 /// addConstantValue - Add constant value entry in variable DIE.
874 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
876 addConstantValue(Die, CI->getValue(), Unsigned);
879 // addConstantValue - Add constant value entry in variable DIE.
880 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
881 unsigned CIBitWidth = Val.getBitWidth();
882 if (CIBitWidth <= 64) {
883 // If we're a signed constant definitely use sdata.
885 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
890 // Else use data for now unless it's larger than we can deal with.
892 switch (CIBitWidth) {
894 Form = dwarf::DW_FORM_data1;
897 Form = dwarf::DW_FORM_data2;
900 Form = dwarf::DW_FORM_data4;
903 Form = dwarf::DW_FORM_data8;
906 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
910 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
914 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
916 // Get the raw data form of the large APInt.
917 const uint64_t *Ptr64 = Val.getRawData();
919 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
920 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
922 // Output the constant to DWARF one byte at a time.
923 for (int i = 0; i < NumBytes; i++) {
926 c = Ptr64[i / 8] >> (8 * (i & 7));
928 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
929 addUInt(Block, dwarf::DW_FORM_data1, c);
932 addBlock(Die, dwarf::DW_AT_const_value, Block);
935 /// addTemplateParams - Add template parameters into buffer.
936 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
937 // Add template parameters.
938 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
939 DIDescriptor Element = TParams.getElement(i);
940 if (Element.isTemplateTypeParameter())
941 constructTemplateTypeParameterDIE(Buffer,
942 DITemplateTypeParameter(Element));
943 else if (Element.isTemplateValueParameter())
944 constructTemplateValueParameterDIE(Buffer,
945 DITemplateValueParameter(Element));
949 /// getOrCreateContextDIE - Get context owner's DIE.
950 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
951 if (!Context || Context.isFile())
953 if (Context.isType())
954 return getOrCreateTypeDIE(DIType(Context));
955 if (Context.isNameSpace())
956 return getOrCreateNameSpace(DINameSpace(Context));
957 if (Context.isSubprogram())
958 return getOrCreateSubprogramDIE(DISubprogram(Context));
959 return getDIE(Context);
962 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
963 DIScope Context = resolve(Ty.getContext());
964 DIE *ContextDIE = getOrCreateContextDIE(Context);
966 DIE *TyDIE = getDIE(Ty);
971 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
973 constructTypeDIE(*TyDIE, Ty);
975 updateAcceleratorTables(Context, Ty, TyDIE);
979 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
981 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
987 assert(Ty == resolve(Ty.getRef()) &&
988 "type was not uniqued, possible ODR violation.");
990 // DW_TAG_restrict_type is not supported in DWARF2
991 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
992 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
994 // Construct the context before querying for the existence of the DIE in case
995 // such construction creates the DIE.
996 DIScope Context = resolve(Ty.getContext());
997 DIE *ContextDIE = getOrCreateContextDIE(Context);
1000 DIE *TyDIE = getDIE(Ty);
1005 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1007 updateAcceleratorTables(Context, Ty, TyDIE);
1009 if (Ty.isBasicType())
1010 constructTypeDIE(*TyDIE, DIBasicType(Ty));
1011 else if (Ty.isCompositeType()) {
1012 DICompositeType CTy(Ty);
1013 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1014 if (MDString *TypeId = CTy.getIdentifier()) {
1015 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1016 // Skip updating the accelerator tables since this is not the full type.
1019 constructTypeDIE(*TyDIE, CTy);
1021 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1022 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1028 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1030 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1031 bool IsImplementation = 0;
1032 if (Ty.isCompositeType()) {
1033 DICompositeType CT(Ty);
1034 // A runtime language of 0 actually means C/C++ and that any
1035 // non-negative value is some version of Objective-C/C++.
1036 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1038 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1039 DD->addAccelType(Ty.getName(), TyDIE, Flags);
1041 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1042 Context.isNameSpace()) &&
1043 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1044 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1048 /// addType - Add a new type attribute to the specified entity.
1049 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1050 assert(Ty && "Trying to add a type that doesn't exist?");
1052 // Check for pre-existence.
1053 DIEEntry *Entry = getDIEEntry(Ty);
1054 // If it exists then use the existing value.
1056 addDIEEntry(Entity, Attribute, Entry);
1061 DIE *Buffer = getOrCreateTypeDIE(Ty);
1064 Entry = createDIEEntry(Buffer);
1065 insertDIEEntry(Ty, Entry);
1066 addDIEEntry(Entity, Attribute, Entry);
1069 /// addGlobalName - Add a new global name to the compile unit.
1070 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1071 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1073 std::string FullName = getParentContextString(Context) + Name.str();
1074 GlobalNames[FullName] = Die;
1077 /// getParentContextString - Walks the metadata parent chain in a language
1078 /// specific manner (using the compile unit language) and returns
1079 /// it as a string. This is done at the metadata level because DIEs may
1080 /// not currently have been added to the parent context and walking the
1081 /// DIEs looking for names is more expensive than walking the metadata.
1082 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1086 // FIXME: Decide whether to implement this for non-C++ languages.
1087 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1091 SmallVector<DIScope, 1> Parents;
1092 while (!Context.isCompileUnit()) {
1093 Parents.push_back(Context);
1094 if (Context.getContext())
1095 Context = resolve(Context.getContext());
1097 // Structure, etc types will have a NULL context if they're at the top
1102 // Reverse iterate over our list to go from the outermost construct to the
1104 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1108 StringRef Name = Ctx.getName();
1109 if (!Name.empty()) {
1117 /// constructTypeDIE - Construct basic type die from DIBasicType.
1118 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1119 // Get core information.
1120 StringRef Name = BTy.getName();
1121 // Add name if not anonymous or intermediate type.
1123 addString(&Buffer, dwarf::DW_AT_name, Name);
1125 // An unspecified type only has a name attribute.
1126 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1129 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1132 uint64_t Size = BTy.getSizeInBits() >> 3;
1133 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1136 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1137 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1138 // Get core information.
1139 StringRef Name = DTy.getName();
1140 uint64_t Size = DTy.getSizeInBits() >> 3;
1141 uint16_t Tag = Buffer.getTag();
1143 // Map to main type, void will not have a type.
1144 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1146 addType(&Buffer, FromTy);
1148 // Add name if not anonymous or intermediate type.
1150 addString(&Buffer, dwarf::DW_AT_name, Name);
1152 // Add size if non-zero (derived types might be zero-sized.)
1153 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1154 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1156 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1157 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1158 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1159 // Add source line info if available and TyDesc is not a forward declaration.
1160 if (!DTy.isForwardDecl())
1161 addSourceLine(&Buffer, DTy);
1164 /// constructSubprogramArguments - Construct function argument DIEs.
1165 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DIArray Args) {
1166 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1167 DIDescriptor Ty = Args.getElement(i);
1168 if (Ty.isUnspecifiedParameter()) {
1169 assert(i == N-1 && "Unspecified parameter must be the last argument");
1170 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1172 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1173 addType(Arg, DIType(Ty));
1174 if (DIType(Ty).isArtificial())
1175 addFlag(Arg, dwarf::DW_AT_artificial);
1180 /// constructTypeDIE - Construct type DIE from DICompositeType.
1181 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1182 // Add name if not anonymous or intermediate type.
1183 StringRef Name = CTy.getName();
1185 uint64_t Size = CTy.getSizeInBits() >> 3;
1186 uint16_t Tag = Buffer.getTag();
1189 case dwarf::DW_TAG_array_type:
1190 constructArrayTypeDIE(Buffer, CTy);
1192 case dwarf::DW_TAG_enumeration_type:
1193 constructEnumTypeDIE(Buffer, CTy);
1195 case dwarf::DW_TAG_subroutine_type: {
1196 // Add return type. A void return won't have a type.
1197 DIArray Elements = CTy.getTypeArray();
1198 DIType RTy(Elements.getElement(0));
1200 addType(&Buffer, RTy);
1202 bool isPrototyped = true;
1203 if (Elements.getNumElements() == 2 &&
1204 Elements.getElement(1).isUnspecifiedParameter())
1205 isPrototyped = false;
1207 constructSubprogramArguments(Buffer, Elements);
1209 // Add prototype flag if we're dealing with a C language and the
1210 // function has been prototyped.
1211 uint16_t Language = getLanguage();
1213 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1214 Language == dwarf::DW_LANG_ObjC))
1215 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1217 if (CTy.isLValueReference())
1218 addFlag(&Buffer, dwarf::DW_AT_reference);
1220 if (CTy.isRValueReference())
1221 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1223 case dwarf::DW_TAG_structure_type:
1224 case dwarf::DW_TAG_union_type:
1225 case dwarf::DW_TAG_class_type: {
1226 // Add elements to structure type.
1227 DIArray Elements = CTy.getTypeArray();
1228 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1229 DIDescriptor Element = Elements.getElement(i);
1230 DIE *ElemDie = nullptr;
1231 if (Element.isSubprogram())
1232 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1233 else if (Element.isDerivedType()) {
1234 DIDerivedType DDTy(Element);
1235 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1236 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1237 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1238 dwarf::DW_AT_friend);
1239 } else if (DDTy.isStaticMember()) {
1240 getOrCreateStaticMemberDIE(DDTy);
1242 constructMemberDIE(Buffer, DDTy);
1244 } else if (Element.isObjCProperty()) {
1245 DIObjCProperty Property(Element);
1246 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1247 StringRef PropertyName = Property.getObjCPropertyName();
1248 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1249 if (Property.getType())
1250 addType(ElemDie, Property.getType());
1251 addSourceLine(ElemDie, Property);
1252 StringRef GetterName = Property.getObjCPropertyGetterName();
1253 if (!GetterName.empty())
1254 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1255 StringRef SetterName = Property.getObjCPropertySetterName();
1256 if (!SetterName.empty())
1257 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1258 unsigned PropertyAttributes = 0;
1259 if (Property.isReadOnlyObjCProperty())
1260 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1261 if (Property.isReadWriteObjCProperty())
1262 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1263 if (Property.isAssignObjCProperty())
1264 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1265 if (Property.isRetainObjCProperty())
1266 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1267 if (Property.isCopyObjCProperty())
1268 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1269 if (Property.isNonAtomicObjCProperty())
1270 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1271 if (PropertyAttributes)
1272 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1273 PropertyAttributes);
1275 DIEEntry *Entry = getDIEEntry(Element);
1277 Entry = createDIEEntry(ElemDie);
1278 insertDIEEntry(Element, Entry);
1284 if (CTy.isAppleBlockExtension())
1285 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1287 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1289 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1290 getOrCreateTypeDIE(ContainingType));
1292 if (CTy.isObjcClassComplete())
1293 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1295 // Add template parameters to a class, structure or union types.
1296 // FIXME: The support isn't in the metadata for this yet.
1297 if (Tag == dwarf::DW_TAG_class_type ||
1298 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1299 addTemplateParams(Buffer, CTy.getTemplateParams());
1307 // Add name if not anonymous or intermediate type.
1309 addString(&Buffer, dwarf::DW_AT_name, Name);
1311 if (Tag == dwarf::DW_TAG_enumeration_type ||
1312 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1313 Tag == dwarf::DW_TAG_union_type) {
1314 // Add size if non-zero (derived types might be zero-sized.)
1315 // TODO: Do we care about size for enum forward declarations?
1317 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1318 else if (!CTy.isForwardDecl())
1319 // Add zero size if it is not a forward declaration.
1320 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1322 // If we're a forward decl, say so.
1323 if (CTy.isForwardDecl())
1324 addFlag(&Buffer, dwarf::DW_AT_declaration);
1326 // Add source line info if available.
1327 if (!CTy.isForwardDecl())
1328 addSourceLine(&Buffer, CTy);
1330 // No harm in adding the runtime language to the declaration.
1331 unsigned RLang = CTy.getRunTimeLang();
1333 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1338 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1339 /// DITemplateTypeParameter.
1340 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1341 DITemplateTypeParameter TP) {
1343 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1344 // Add the type if it exists, it could be void and therefore no type.
1346 addType(ParamDIE, resolve(TP.getType()));
1347 if (!TP.getName().empty())
1348 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1351 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1352 /// DITemplateValueParameter.
1354 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1355 DITemplateValueParameter VP) {
1356 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1358 // Add the type if there is one, template template and template parameter
1359 // packs will not have a type.
1360 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1361 addType(ParamDIE, resolve(VP.getType()));
1362 if (!VP.getName().empty())
1363 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1364 if (Value *Val = VP.getValue()) {
1365 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1366 addConstantValue(ParamDIE, CI,
1367 isUnsignedDIType(DD, resolve(VP.getType())));
1368 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1369 // For declaration non-type template parameters (such as global values and
1371 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1372 addOpAddress(Loc, Asm->getSymbol(GV));
1373 // Emit DW_OP_stack_value to use the address as the immediate value of the
1374 // parameter, rather than a pointer to it.
1375 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1376 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1377 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1378 assert(isa<MDString>(Val));
1379 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1380 cast<MDString>(Val)->getString());
1381 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1382 assert(isa<MDNode>(Val));
1383 DIArray A(cast<MDNode>(Val));
1384 addTemplateParams(*ParamDIE, A);
1389 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1390 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1391 // Construct the context before querying for the existence of the DIE in case
1392 // such construction creates the DIE.
1393 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1395 DIE *NDie = getDIE(NS);
1398 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1400 if (!NS.getName().empty()) {
1401 addString(NDie, dwarf::DW_AT_name, NS.getName());
1402 DD->addAccelNamespace(NS.getName(), NDie);
1403 addGlobalName(NS.getName(), NDie, NS.getContext());
1405 DD->addAccelNamespace("(anonymous namespace)", NDie);
1406 addSourceLine(NDie, NS);
1410 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1411 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1412 // Construct the context before querying for the existence of the DIE in case
1413 // such construction creates the DIE (as is the case for member function
1415 DIScope Context = resolve(SP.getContext());
1416 DIE *ContextDIE = getOrCreateContextDIE(Context);
1418 // Unique declarations based on the ODR, where applicable.
1419 SP = DISubprogram(DD->resolve(SP.getRef()));
1420 assert(SP.Verify());
1422 DIE *SPDie = getDIE(SP);
1426 DISubprogram SPDecl = SP.getFunctionDeclaration();
1427 if (SPDecl.isSubprogram())
1428 // Add subprogram definitions to the CU die directly.
1429 ContextDIE = UnitDie.get();
1431 // DW_TAG_inlined_subroutine may refer to this DIE.
1432 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1434 DIE *DeclDie = nullptr;
1435 if (SPDecl.isSubprogram())
1436 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1438 // Add function template parameters.
1439 addTemplateParams(*SPDie, SP.getTemplateParams());
1442 // Refer function declaration directly.
1443 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1445 // Add the linkage name if we have one and it isn't in the Decl.
1446 StringRef LinkageName = SP.getLinkageName();
1447 if (!LinkageName.empty()) {
1448 if (SPDecl.isSubprogram() && !SPDecl.getLinkageName().empty())
1449 assert(SPDecl.getLinkageName() == SP.getLinkageName() &&
1450 "decl has a linkage name and it is different");
1452 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1453 GlobalValue::getRealLinkageName(LinkageName));
1456 // If this DIE is going to refer declaration info using AT_specification
1457 // then there is no need to add other attributes.
1461 // Constructors and operators for anonymous aggregates do not have names.
1462 if (!SP.getName().empty())
1463 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1465 addSourceLine(SPDie, SP);
1467 // Add the prototype if we have a prototype and we have a C like
1469 uint16_t Language = getLanguage();
1470 if (SP.isPrototyped() &&
1471 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1472 Language == dwarf::DW_LANG_ObjC))
1473 addFlag(SPDie, dwarf::DW_AT_prototyped);
1475 DICompositeType SPTy = SP.getType();
1476 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1477 "the type of a subprogram should be a subroutine");
1479 DIArray Args = SPTy.getTypeArray();
1480 // Add a return type. If this is a type like a C/C++ void type we don't add a
1482 if (Args.getElement(0))
1483 addType(SPDie, DIType(Args.getElement(0)));
1485 unsigned VK = SP.getVirtuality();
1487 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1488 DIELoc *Block = getDIELoc();
1489 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1490 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1491 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1492 ContainingTypeMap.insert(
1493 std::make_pair(SPDie, resolve(SP.getContainingType())));
1496 if (!SP.isDefinition()) {
1497 addFlag(SPDie, dwarf::DW_AT_declaration);
1499 // Add arguments. Do not add arguments for subprogram definition. They will
1500 // be handled while processing variables.
1501 constructSubprogramArguments(*SPDie, Args);
1504 if (SP.isArtificial())
1505 addFlag(SPDie, dwarf::DW_AT_artificial);
1507 if (!SP.isLocalToUnit())
1508 addFlag(SPDie, dwarf::DW_AT_external);
1510 if (SP.isOptimized())
1511 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1513 if (unsigned isa = Asm->getISAEncoding()) {
1514 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1517 if (SP.isLValueReference())
1518 addFlag(SPDie, dwarf::DW_AT_reference);
1520 if (SP.isRValueReference())
1521 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1523 if (SP.isProtected())
1524 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1525 dwarf::DW_ACCESS_protected);
1526 else if (SP.isPrivate())
1527 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1528 dwarf::DW_ACCESS_private);
1530 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1531 dwarf::DW_ACCESS_public);
1533 if (SP.isExplicit())
1534 addFlag(SPDie, dwarf::DW_AT_explicit);
1539 // Return const expression if value is a GEP to access merged global
1541 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1542 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1543 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1544 if (!CE || CE->getNumOperands() != 3 ||
1545 CE->getOpcode() != Instruction::GetElementPtr)
1548 // First operand points to a global struct.
1549 Value *Ptr = CE->getOperand(0);
1550 if (!isa<GlobalValue>(Ptr) ||
1551 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1554 // Second operand is zero.
1555 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1556 if (!CI || !CI->isZero())
1559 // Third operand is offset.
1560 if (!isa<ConstantInt>(CE->getOperand(2)))
1566 /// createGlobalVariableDIE - create global variable DIE.
1567 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1568 // Check for pre-existence.
1572 assert(GV.isGlobalVariable());
1574 DIScope GVContext = GV.getContext();
1575 DIType GTy = DD->resolve(GV.getType());
1577 // If this is a static data member definition, some attributes belong
1578 // to the declaration DIE.
1579 DIE *VariableDIE = nullptr;
1580 bool IsStaticMember = false;
1581 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1582 if (SDMDecl.Verify()) {
1583 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1584 // We need the declaration DIE that is in the static member's class.
1585 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1586 IsStaticMember = true;
1589 // If this is not a static data member definition, create the variable
1590 // DIE and add the initial set of attributes to it.
1592 // Construct the context before querying for the existence of the DIE in
1593 // case such construction creates the DIE.
1594 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1597 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1599 // Add name and type.
1600 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1601 addType(VariableDIE, GTy);
1603 // Add scoping info.
1604 if (!GV.isLocalToUnit())
1605 addFlag(VariableDIE, dwarf::DW_AT_external);
1607 // Add line number info.
1608 addSourceLine(VariableDIE, GV);
1612 bool addToAccelTable = false;
1613 DIE *VariableSpecDIE = nullptr;
1614 bool isGlobalVariable = GV.getGlobal() != nullptr;
1615 if (isGlobalVariable) {
1616 addToAccelTable = true;
1617 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1618 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1619 if (GV.getGlobal()->isThreadLocal()) {
1620 // FIXME: Make this work with -gsplit-dwarf.
1621 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1622 assert((PointerSize == 4 || PointerSize == 8) &&
1623 "Add support for other sizes if necessary");
1624 // Based on GCC's support for TLS:
1625 if (!DD->useSplitDwarf()) {
1626 // 1) Start with a constNu of the appropriate pointer size
1627 addUInt(Loc, dwarf::DW_FORM_data1,
1628 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1629 // 2) containing the (relocated) offset of the TLS variable
1630 // within the module's TLS block.
1631 addExpr(Loc, dwarf::DW_FORM_udata,
1632 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1634 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1635 addUInt(Loc, dwarf::DW_FORM_udata,
1636 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1638 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1639 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1641 DD->addArangeLabel(SymbolCU(this, Sym));
1642 addOpAddress(Loc, Sym);
1644 // Do not create specification DIE if context is either compile unit
1646 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1647 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1648 // Create specification DIE.
1649 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1650 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1651 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc);
1652 // A static member's declaration is already flagged as such.
1653 if (!SDMDecl.Verify())
1654 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1656 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1658 // Add the linkage name.
1659 StringRef LinkageName = GV.getLinkageName();
1660 if (!LinkageName.empty())
1661 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1662 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1664 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1666 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1667 : dwarf::DW_AT_MIPS_linkage_name,
1668 GlobalValue::getRealLinkageName(LinkageName));
1669 } else if (const ConstantInt *CI =
1670 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1671 // AT_const_value was added when the static member was created. To avoid
1672 // emitting AT_const_value multiple times, we only add AT_const_value when
1673 // it is not a static member.
1674 if (!IsStaticMember)
1675 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1676 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1677 addToAccelTable = true;
1678 // GV is a merged global.
1679 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1680 Value *Ptr = CE->getOperand(0);
1681 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1682 DD->addArangeLabel(SymbolCU(this, Sym));
1683 addOpAddress(Loc, Sym);
1684 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1685 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1686 addUInt(Loc, dwarf::DW_FORM_udata,
1687 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1688 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1689 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1692 if (addToAccelTable) {
1693 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1694 DD->addAccelName(GV.getName(), AddrDIE);
1696 // If the linkage name is different than the name, go ahead and output
1697 // that as well into the name table.
1698 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1699 DD->addAccelName(GV.getLinkageName(), AddrDIE);
1702 if (!GV.isLocalToUnit())
1703 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1707 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1708 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1709 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1710 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1712 // The LowerBound value defines the lower bounds which is typically zero for
1713 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1714 // Count == -1 then the array is unbounded and we do not emit
1715 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1716 // Count == 0, then the array has zero elements in which case we do not emit
1718 int64_t LowerBound = SR.getLo();
1719 int64_t DefaultLowerBound = getDefaultLowerBound();
1720 int64_t Count = SR.getCount();
1722 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1723 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1725 if (Count != -1 && Count != 0)
1726 // FIXME: An unbounded array should reference the expression that defines
1728 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1729 LowerBound + Count - 1);
1732 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1733 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1735 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1737 // Emit the element type.
1738 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1740 // Get an anonymous type for index type.
1741 // FIXME: This type should be passed down from the front end
1742 // as different languages may have different sizes for indexes.
1743 DIE *IdxTy = getIndexTyDie();
1745 // Construct an integer type to use for indexes.
1746 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1747 addString(IdxTy, dwarf::DW_AT_name, "sizetype");
1748 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1749 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1750 dwarf::DW_ATE_unsigned);
1751 setIndexTyDie(IdxTy);
1754 // Add subranges to array type.
1755 DIArray Elements = CTy.getTypeArray();
1756 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1757 DIDescriptor Element = Elements.getElement(i);
1758 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1759 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1763 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1764 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1765 DIArray Elements = CTy.getTypeArray();
1767 // Add enumerators to enumeration type.
1768 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1769 DIEnumerator Enum(Elements.getElement(i));
1770 if (Enum.isEnumerator()) {
1771 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1772 StringRef Name = Enum.getName();
1773 addString(Enumerator, dwarf::DW_AT_name, Name);
1774 int64_t Value = Enum.getEnumValue();
1775 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1779 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1781 addType(&Buffer, DTy);
1782 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1786 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1788 void DwarfUnit::constructContainingTypeDIEs() {
1789 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1790 CE = ContainingTypeMap.end();
1792 DIE *SPDie = CI->first;
1793 DIDescriptor D(CI->second);
1796 DIE *NDie = getDIE(D);
1799 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1803 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1804 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1805 auto D = constructVariableDIEImpl(DV, isScopeAbstract);
1810 DIE *DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1811 bool isScopeAbstract) {
1812 StringRef Name = DV.getName();
1814 // Define variable debug information entry.
1815 DIE *VariableDie = new DIE(DV.getTag());
1816 DbgVariable *AbsVar = DV.getAbstractVariable();
1817 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : nullptr;
1819 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1822 addString(VariableDie, dwarf::DW_AT_name, Name);
1823 addSourceLine(VariableDie, DV.getVariable());
1824 addType(VariableDie, DV.getType());
1827 if (DV.isArtificial())
1828 addFlag(VariableDie, dwarf::DW_AT_artificial);
1830 if (isScopeAbstract)
1833 // Add variable address.
1835 unsigned Offset = DV.getDotDebugLocOffset();
1836 if (Offset != ~0U) {
1837 addLocationList(VariableDie, dwarf::DW_AT_location, Offset);
1841 // Check if variable is described by a DBG_VALUE instruction.
1842 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1843 assert(DVInsn->getNumOperands() == 3);
1844 if (DVInsn->getOperand(0).isReg()) {
1845 const MachineOperand RegOp = DVInsn->getOperand(0);
1846 // If the second operand is an immediate, this is an indirect value.
1847 if (DVInsn->getOperand(1).isImm()) {
1848 MachineLocation Location(RegOp.getReg(),
1849 DVInsn->getOperand(1).getImm());
1850 addVariableAddress(DV, VariableDie, Location);
1851 } else if (RegOp.getReg())
1852 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1853 } else if (DVInsn->getOperand(0).isImm())
1854 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1855 else if (DVInsn->getOperand(0).isFPImm())
1856 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1857 else if (DVInsn->getOperand(0).isCImm())
1858 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1859 isUnsignedDIType(DD, DV.getType()));
1864 // .. else use frame index.
1865 int FI = DV.getFrameIndex();
1867 unsigned FrameReg = 0;
1868 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1869 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1870 MachineLocation Location(FrameReg, Offset);
1871 addVariableAddress(DV, VariableDie, Location);
1877 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1878 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1879 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1880 StringRef Name = DT.getName();
1882 addString(MemberDie, dwarf::DW_AT_name, Name);
1884 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1886 addSourceLine(MemberDie, DT);
1888 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1890 // For C++, virtual base classes are not at fixed offset. Use following
1891 // expression to extract appropriate offset from vtable.
1892 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1894 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1895 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1896 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1897 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1898 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1899 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1900 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1901 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1903 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1905 uint64_t Size = DT.getSizeInBits();
1906 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1907 uint64_t OffsetInBytes;
1909 if (Size != FieldSize) {
1910 // Handle bitfield, assume bytes are 8 bits.
1911 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1912 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1914 uint64_t Offset = DT.getOffsetInBits();
1915 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1916 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1917 uint64_t FieldOffset = (HiMark - FieldSize);
1918 Offset -= FieldOffset;
1920 // Maybe we need to work from the other end.
1921 if (Asm->getDataLayout().isLittleEndian())
1922 Offset = FieldSize - (Offset + Size);
1923 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1925 // Here DW_AT_data_member_location points to the anonymous
1926 // field that includes this bit field.
1927 OffsetInBytes = FieldOffset >> 3;
1929 // This is not a bitfield.
1930 OffsetInBytes = DT.getOffsetInBits() >> 3;
1932 if (DD->getDwarfVersion() <= 2) {
1933 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1934 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1935 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1936 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1938 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1942 if (DT.isProtected())
1943 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1944 dwarf::DW_ACCESS_protected);
1945 else if (DT.isPrivate())
1946 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1947 dwarf::DW_ACCESS_private);
1948 // Otherwise C++ member and base classes are considered public.
1950 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1951 dwarf::DW_ACCESS_public);
1953 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1954 dwarf::DW_VIRTUALITY_virtual);
1956 // Objective-C properties.
1957 if (MDNode *PNode = DT.getObjCProperty())
1958 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1959 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1962 if (DT.isArtificial())
1963 addFlag(MemberDie, dwarf::DW_AT_artificial);
1966 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1967 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1971 // Construct the context before querying for the existence of the DIE in case
1972 // such construction creates the DIE.
1973 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1974 assert(dwarf::isType(ContextDIE->getTag()) &&
1975 "Static member should belong to a type.");
1977 DIE *StaticMemberDIE = getDIE(DT);
1978 if (StaticMemberDIE)
1979 return StaticMemberDIE;
1981 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1983 DIType Ty = resolve(DT.getTypeDerivedFrom());
1985 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1986 addType(StaticMemberDIE, Ty);
1987 addSourceLine(StaticMemberDIE, DT);
1988 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1989 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1991 // FIXME: We could omit private if the parent is a class_type, and
1992 // public if the parent is something else.
1993 if (DT.isProtected())
1994 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1995 dwarf::DW_ACCESS_protected);
1996 else if (DT.isPrivate())
1997 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1998 dwarf::DW_ACCESS_private);
2000 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2001 dwarf::DW_ACCESS_public);
2003 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2004 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2005 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2006 addConstantFPValue(StaticMemberDIE, CFP);
2008 return StaticMemberDIE;
2011 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2012 Asm->OutStreamer.AddComment("DWARF version number");
2013 Asm->EmitInt16(DD->getDwarfVersion());
2014 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2015 // We share one abbreviations table across all units so it's always at the
2016 // start of the section. Use a relocatable offset where needed to ensure
2017 // linking doesn't invalidate that offset.
2019 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2021 // Use a constant value when no symbol is provided.
2023 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2024 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2027 void DwarfUnit::addRange(RangeSpan Range) {
2028 // Only add a range for this unit if we're emitting full debug.
2029 if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2030 // If we have no current ranges just add the range and return, otherwise,
2031 // check the current section and CU against the previous section and CU we
2032 // emitted into and the subprogram was contained within. If these are the
2033 // same then extend our current range, otherwise add this as a new range.
2034 if (CURanges.size() == 0 ||
2035 this != DD->getPrevCU() ||
2036 Asm->getCurrentSection() != DD->getPrevSection()) {
2037 CURanges.push_back(Range);
2041 assert(&(CURanges.back().getEnd()->getSection()) ==
2042 &(Range.getEnd()->getSection()) &&
2043 "We can only append to a range in the same section!");
2044 CURanges.back().setEnd(Range.getEnd());
2048 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2049 // Define start line table label for each Compile Unit.
2050 MCSymbol *LineTableStartSym =
2051 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2053 stmtListIndex = UnitDie->getValues().size();
2055 // DW_AT_stmt_list is a offset of line number information for this
2056 // compile unit in debug_line section. For split dwarf this is
2057 // left in the skeleton CU and so not included.
2058 // The line table entries are not always emitted in assembly, so it
2059 // is not okay to use line_table_start here.
2060 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2061 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym);
2063 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2064 DwarfLineSectionSym);
2067 void DwarfCompileUnit::applyStmtList(DIE &D) {
2068 D.addValue(dwarf::DW_AT_stmt_list,
2069 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2070 UnitDie->getValues()[stmtListIndex]);
2073 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2074 DwarfUnit::emitHeader(ASectionSym);
2075 Asm->OutStreamer.AddComment("Type Signature");
2076 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2077 Asm->OutStreamer.AddComment("Type DIE Offset");
2078 // In a skeleton type unit there is no type DIE so emit a zero offset.
2079 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2080 sizeof(Ty->getOffset()));
2083 void DwarfTypeUnit::initSection(const MCSection *Section) {
2084 assert(!this->Section);
2085 this->Section = Section;
2086 // Since each type unit is contained in its own COMDAT section, the begin
2087 // label and the section label are the same. Using the begin label emission in
2088 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2089 // the only other alternative of lazily constructing start-of-section labels
2090 // and storing a mapping in DwarfDebug (or AsmPrinter).
2091 this->SectionSym = this->LabelBegin =
2092 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2094 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2095 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());