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 #define DEBUG_TYPE "dwarfdebug"
16 #include "DwarfUnit.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/DIBuilder.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
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(0), Section(0), Skeleton(0) {
48 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
51 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
52 AsmPrinter *A, DwarfDebug *DW,
54 : DwarfUnit(UID, D, Node, A, DW, DWU) {
58 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DwarfCompileUnit &CU,
59 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
60 : DwarfUnit(UID, D, CU.getCUNode(), A, DW, DWU), CU(CU) {
64 /// ~Unit - Destructor for compile unit.
65 DwarfUnit::~DwarfUnit() {
66 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
67 DIEBlocks[j]->~DIEBlock();
70 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
71 /// information entry.
72 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
73 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
77 /// getDefaultLowerBound - Return the default lower bound for an array. If the
78 /// DWARF version doesn't handle the language, return -1.
79 int64_t DwarfUnit::getDefaultLowerBound() const {
80 switch (getLanguage()) {
84 case dwarf::DW_LANG_C89:
85 case dwarf::DW_LANG_C99:
86 case dwarf::DW_LANG_C:
87 case dwarf::DW_LANG_C_plus_plus:
88 case dwarf::DW_LANG_ObjC:
89 case dwarf::DW_LANG_ObjC_plus_plus:
92 case dwarf::DW_LANG_Fortran77:
93 case dwarf::DW_LANG_Fortran90:
94 case dwarf::DW_LANG_Fortran95:
97 // The languages below have valid values only if the DWARF version >= 4.
98 case dwarf::DW_LANG_Java:
99 case dwarf::DW_LANG_Python:
100 case dwarf::DW_LANG_UPC:
101 case dwarf::DW_LANG_D:
102 if (dwarf::DWARF_VERSION >= 4)
106 case dwarf::DW_LANG_Ada83:
107 case dwarf::DW_LANG_Ada95:
108 case dwarf::DW_LANG_Cobol74:
109 case dwarf::DW_LANG_Cobol85:
110 case dwarf::DW_LANG_Modula2:
111 case dwarf::DW_LANG_Pascal83:
112 case dwarf::DW_LANG_PLI:
113 if (dwarf::DWARF_VERSION >= 4)
121 /// Check whether the DIE for this MDNode can be shared across CUs.
122 static bool isShareableAcrossCUs(DIDescriptor D) {
123 // When the MDNode can be part of the type system, the DIE can be shared
125 // Combining type units and cross-CU DIE sharing is lower value (since
126 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
127 // level already) but may be implementable for some value in projects
128 // building multiple independent libraries with LTO and then linking those
130 return (D.isType() ||
131 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
132 !GenerateDwarfTypeUnits;
135 /// getDIE - Returns the debug information entry map slot for the
136 /// specified debug variable. We delegate the request to DwarfDebug
137 /// when the DIE for this MDNode can be shared across CUs. The mappings
138 /// will be kept in DwarfDebug for shareable DIEs.
139 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
140 if (isShareableAcrossCUs(D))
141 return DD->getDIE(D);
142 return MDNodeToDieMap.lookup(D);
145 /// insertDIE - Insert DIE into the map. 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 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
149 if (isShareableAcrossCUs(Desc)) {
150 DD->insertDIE(Desc, D);
153 MDNodeToDieMap.insert(std::make_pair(Desc, D));
156 /// addFlag - Add a flag that is true.
157 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
158 if (DD->getDwarfVersion() >= 4)
159 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
161 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
164 /// addUInt - Add an unsigned integer attribute data and value.
166 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
167 Optional<dwarf::Form> Form, uint64_t Integer) {
169 Form = DIEInteger::BestForm(false, Integer);
170 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
172 Die->addValue(Attribute, *Form, Value);
175 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
176 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
179 /// addSInt - Add an signed integer attribute data and value.
181 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
182 Optional<dwarf::Form> Form, int64_t Integer) {
184 Form = DIEInteger::BestForm(true, Integer);
185 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
186 Die->addValue(Attribute, *Form, Value);
189 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
191 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
194 /// addString - Add a string attribute data and value. We always emit a
195 /// reference to the string pool instead of immediate strings so that DIEs have
196 /// more predictable sizes. In the case of split dwarf we emit an index
197 /// into another table which gets us the static offset into the string
199 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
202 if (!DD->useSplitDwarf())
203 return addLocalString(Die, Attribute, String);
205 unsigned idx = DU->getStringPoolIndex(String);
206 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
207 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
208 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
211 /// addLocalString - Add a string attribute data and value. This is guaranteed
212 /// to be in the local string pool instead of indirected.
213 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
215 MCSymbol *Symb = DU->getStringPoolEntry(String);
217 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
218 Value = new (DIEValueAllocator) DIELabel(Symb);
220 MCSymbol *StringPool = DU->getStringPoolSym();
221 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
223 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
224 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
227 /// addExpr - Add a Dwarf expression attribute data and value.
229 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
230 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
231 Die->addValue((dwarf::Attribute)0, Form, Value);
234 /// addLabel - Add a Dwarf label attribute data and value.
236 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
237 const MCSymbol *Label) {
238 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
239 Die->addValue(Attribute, Form, Value);
242 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
243 const MCSymbol *Label) {
244 addLabel(Die, (dwarf::Attribute)0, Form, Label);
247 /// addSectionLabel - Add a Dwarf section label attribute data and value.
249 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
250 const MCSymbol *Label) {
251 if (DD->getDwarfVersion() >= 4)
252 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
254 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
257 /// addSectionOffset - Add an offset into a section attribute data and value.
259 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
261 if (DD->getDwarfVersion() >= 4)
262 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
264 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
267 /// addLabelAddress - Add a dwarf label attribute data and value using
268 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
270 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
273 DD->addArangeLabel(SymbolCU(this, Label));
275 if (!DD->useSplitDwarf()) {
277 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
278 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
280 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
281 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
284 unsigned idx = DU->getAddrPoolIndex(Label);
285 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
286 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
290 /// addOpAddress - Add a dwarf op address data and value using the
291 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
293 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
294 if (!DD->useSplitDwarf()) {
295 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
296 addLabel(Die, dwarf::DW_FORM_udata, Sym);
298 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
299 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
303 /// addSectionDelta - Add a section label delta attribute data and value.
305 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
306 const MCSymbol *Hi, const MCSymbol *Lo) {
307 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
308 if (DD->getDwarfVersion() >= 4)
309 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
311 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
314 /// addDIEEntry - Add a DIE attribute data and value.
316 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
317 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
320 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
321 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
322 new (DIEValueAllocator) DIETypeSignature(Type));
325 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
327 const DIE *DieCU = Die->getUnitOrNull();
328 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
330 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
331 DieCU = getUnitDie();
333 EntryCU = getUnitDie();
334 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
335 : dwarf::DW_FORM_ref_addr,
339 /// Create a DIE with the given Tag, add the DIE to its parent, and
340 /// call insertDIE if MD is not null.
341 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
342 DIE *Die = new DIE(Tag);
343 Parent.addChild(Die);
349 /// addBlock - Add block data.
351 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
353 Block->ComputeSize(Asm);
354 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
355 Die->addValue(Attribute, Block->BestForm(), Block);
358 /// addSourceLine - Add location information to specified debug information
360 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
361 StringRef Directory) {
366 DD->getOrCreateSourceID(File, Directory, getCU().getUniqueID());
367 assert(FileID && "Invalid file id");
368 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
369 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
372 /// addSourceLine - Add location information to specified debug information
374 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
375 assert(V.isVariable());
377 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
378 V.getContext().getDirectory());
381 /// addSourceLine - Add location information to specified debug information
383 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
384 assert(G.isGlobalVariable());
386 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
389 /// addSourceLine - Add location information to specified debug information
391 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
392 assert(SP.isSubprogram());
394 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
397 /// addSourceLine - Add location information to specified debug information
399 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
402 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
405 /// addSourceLine - Add location information to specified debug information
407 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
408 assert(Ty.isObjCProperty());
410 DIFile File = Ty.getFile();
411 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
412 File.getDirectory());
415 /// addSourceLine - Add location information to specified debug information
417 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
420 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
423 /// addVariableAddress - Add DW_AT_location attribute for a
424 /// DbgVariable based on provided MachineLocation.
425 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
426 MachineLocation Location) {
427 if (DV.variableHasComplexAddress())
428 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
429 else if (DV.isBlockByrefVariable())
430 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
432 addAddress(Die, dwarf::DW_AT_location, Location,
433 DV.getVariable().isIndirect());
436 /// addRegisterOp - Add register operand.
437 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
438 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
439 int DWReg = RI->getDwarfRegNum(Reg, false);
440 bool isSubRegister = DWReg < 0;
444 // Go up the super-register chain until we hit a valid dwarf register number.
445 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
446 DWReg = RI->getDwarfRegNum(*SR, false);
448 Idx = RI->getSubRegIndex(*SR, Reg);
452 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
453 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
459 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
461 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
462 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
467 unsigned Size = RI->getSubRegIdxSize(Idx);
468 unsigned Offset = RI->getSubRegIdxOffset(Idx);
470 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
471 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
472 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
474 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
475 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
476 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
481 /// addRegisterOffset - Add register offset.
482 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
484 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
485 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
486 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
487 if (Reg == TRI->getFrameRegister(*Asm->MF))
488 // If variable offset is based in frame register then use fbreg.
489 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
491 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
493 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
494 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
496 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
499 /// addAddress - Add an address attribute to a die based on the location
501 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
502 const MachineLocation &Location, bool Indirect) {
503 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
505 if (Location.isReg() && !Indirect)
506 addRegisterOp(Block, Location.getReg());
508 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
509 if (Indirect && !Location.isReg()) {
510 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
514 // Now attach the location information to the DIE.
515 addBlock(Die, Attribute, Block);
518 /// addComplexAddress - Start with the address based on the location provided,
519 /// and generate the DWARF information necessary to find the actual variable
520 /// given the extra address information encoded in the DbgVariable, starting
521 /// from the starting location. Add the DWARF information to the die.
523 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
524 dwarf::Attribute Attribute,
525 const MachineLocation &Location) {
526 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
527 unsigned N = DV.getNumAddrElements();
529 if (Location.isReg()) {
530 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
531 // If first address element is OpPlus then emit
532 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
533 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
536 addRegisterOp(Block, Location.getReg());
538 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
541 uint64_t Element = DV.getAddrElement(i);
542 if (Element == DIBuilder::OpPlus) {
543 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
544 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
545 } else if (Element == DIBuilder::OpDeref) {
546 if (!Location.isReg())
547 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
549 llvm_unreachable("unknown DIBuilder Opcode");
552 // Now attach the location information to the DIE.
553 addBlock(Die, Attribute, Block);
556 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
557 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
558 gives the variable VarName either the struct, or a pointer to the struct, as
559 its type. This is necessary for various behind-the-scenes things the
560 compiler needs to do with by-reference variables in Blocks.
562 However, as far as the original *programmer* is concerned, the variable
563 should still have type 'SomeType', as originally declared.
565 The function getBlockByrefType dives into the __Block_byref_x_VarName
566 struct to find the original type of the variable, which is then assigned to
567 the variable's Debug Information Entry as its real type. So far, so good.
568 However now the debugger will expect the variable VarName to have the type
569 SomeType. So we need the location attribute for the variable to be an
570 expression that explains to the debugger how to navigate through the
571 pointers and struct to find the actual variable of type SomeType.
573 The following function does just that. We start by getting
574 the "normal" location for the variable. This will be the location
575 of either the struct __Block_byref_x_VarName or the pointer to the
576 struct __Block_byref_x_VarName.
578 The struct will look something like:
580 struct __Block_byref_x_VarName {
582 struct __Block_byref_x_VarName *forwarding;
583 ... <various other fields>
585 ... <maybe more fields>
588 If we are given the struct directly (as our starting point) we
589 need to tell the debugger to:
591 1). Add the offset of the forwarding field.
593 2). Follow that pointer to get the real __Block_byref_x_VarName
594 struct to use (the real one may have been copied onto the heap).
596 3). Add the offset for the field VarName, to find the actual variable.
598 If we started with a pointer to the struct, then we need to
599 dereference that pointer first, before the other steps.
600 Translating this into DWARF ops, we will need to append the following
601 to the current location description for the variable:
603 DW_OP_deref -- optional, if we start with a pointer
604 DW_OP_plus_uconst <forward_fld_offset>
606 DW_OP_plus_uconst <varName_fld_offset>
608 That is what this function does. */
610 /// addBlockByrefAddress - Start with the address based on the location
611 /// provided, and generate the DWARF information necessary to find the
612 /// actual Block variable (navigating the Block struct) based on the
613 /// starting location. Add the DWARF information to the die. For
614 /// more information, read large comment just above here.
616 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
617 dwarf::Attribute Attribute,
618 const MachineLocation &Location) {
619 DIType Ty = DV.getType();
621 uint16_t Tag = Ty.getTag();
622 bool isPointer = false;
624 StringRef varName = DV.getName();
626 if (Tag == dwarf::DW_TAG_pointer_type) {
627 DIDerivedType DTy(Ty);
628 TmpTy = resolve(DTy.getTypeDerivedFrom());
632 DICompositeType blockStruct(TmpTy);
634 // Find the __forwarding field and the variable field in the __Block_byref
636 DIArray Fields = blockStruct.getTypeArray();
637 DIDerivedType varField;
638 DIDerivedType forwardingField;
640 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
641 DIDerivedType DT(Fields.getElement(i));
642 StringRef fieldName = DT.getName();
643 if (fieldName == "__forwarding")
644 forwardingField = DT;
645 else if (fieldName == varName)
649 // Get the offsets for the forwarding field and the variable field.
650 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
651 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
653 // Decode the original location, and use that as the start of the byref
654 // variable's location.
655 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
657 if (Location.isReg())
658 addRegisterOp(Block, Location.getReg());
660 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
662 // If we started with a pointer to the __Block_byref... struct, then
663 // the first thing we need to do is dereference the pointer (DW_OP_deref).
665 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
667 // Next add the offset for the '__forwarding' field:
668 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
669 // adding the offset if it's 0.
670 if (forwardingFieldOffset > 0) {
671 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
672 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
675 // Now dereference the __forwarding field to get to the real __Block_byref
676 // struct: DW_OP_deref.
677 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
679 // Now that we've got the real __Block_byref... struct, add the offset
680 // for the variable's field to get to the location of the actual variable:
681 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
682 if (varFieldOffset > 0) {
683 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
684 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
687 // Now attach the location information to the DIE.
688 addBlock(Die, Attribute, Block);
691 /// isTypeSigned - Return true if the type is signed.
692 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
693 if (Ty.isDerivedType())
694 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
696 if (Ty.isBasicType())
697 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
698 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
699 *SizeInBits = Ty.getSizeInBits();
705 /// Return true if type encoding is unsigned.
706 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
707 DIDerivedType DTy(Ty);
708 if (DTy.isDerivedType())
709 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
712 if (BTy.isBasicType()) {
713 unsigned Encoding = BTy.getEncoding();
714 if (Encoding == dwarf::DW_ATE_unsigned ||
715 Encoding == dwarf::DW_ATE_unsigned_char ||
716 Encoding == dwarf::DW_ATE_boolean)
722 /// If this type is derived from a base type then return base type size.
723 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
724 unsigned Tag = Ty.getTag();
726 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
727 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
728 Tag != dwarf::DW_TAG_restrict_type)
729 return Ty.getSizeInBits();
731 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
733 // If this type is not derived from any type then take conservative approach.
734 if (!BaseType.isValid())
735 return Ty.getSizeInBits();
737 // If this is a derived type, go ahead and get the base type, unless it's a
738 // reference then it's just the size of the field. Pointer types have no need
739 // of this since they're a different type of qualification on the type.
740 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
741 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
742 return Ty.getSizeInBits();
744 if (BaseType.isDerivedType())
745 return getBaseTypeSize(DD, DIDerivedType(BaseType));
747 return BaseType.getSizeInBits();
750 /// addConstantValue - Add constant value entry in variable DIE.
751 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
753 // FIXME: This is a bit conservative/simple - it emits negative values at
754 // their maximum bit width which is a bit unfortunate (& doesn't prefer
755 // udata/sdata over dataN as suggested by the DWARF spec)
756 assert(MO.isImm() && "Invalid machine operand!");
758 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
761 // If we're a signed constant definitely use sdata.
762 if (SignedConstant) {
763 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
767 // Else use data for now unless it's larger than we can deal with.
768 switch (SizeInBits) {
770 Form = dwarf::DW_FORM_data1;
773 Form = dwarf::DW_FORM_data2;
776 Form = dwarf::DW_FORM_data4;
779 Form = dwarf::DW_FORM_data8;
782 Form = dwarf::DW_FORM_udata;
783 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
786 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
789 /// addConstantFPValue - Add constant value entry in variable DIE.
790 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
791 assert(MO.isFPImm() && "Invalid machine operand!");
792 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
793 APFloat FPImm = MO.getFPImm()->getValueAPF();
795 // Get the raw data form of the floating point.
796 const APInt FltVal = FPImm.bitcastToAPInt();
797 const char *FltPtr = (const char *)FltVal.getRawData();
799 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
800 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
801 int Incr = (LittleEndian ? 1 : -1);
802 int Start = (LittleEndian ? 0 : NumBytes - 1);
803 int Stop = (LittleEndian ? NumBytes : -1);
805 // Output the constant to DWARF one byte at a time.
806 for (; Start != Stop; Start += Incr)
807 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
809 addBlock(Die, dwarf::DW_AT_const_value, Block);
812 /// addConstantFPValue - Add constant value entry in variable DIE.
813 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
814 // Pass this down to addConstantValue as an unsigned bag of bits.
815 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
818 /// addConstantValue - Add constant value entry in variable DIE.
819 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
821 addConstantValue(Die, CI->getValue(), Unsigned);
824 // addConstantValue - Add constant value entry in variable DIE.
825 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
826 unsigned CIBitWidth = Val.getBitWidth();
827 if (CIBitWidth <= 64) {
828 // If we're a signed constant definitely use sdata.
830 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
835 // Else use data for now unless it's larger than we can deal with.
837 switch (CIBitWidth) {
839 Form = dwarf::DW_FORM_data1;
842 Form = dwarf::DW_FORM_data2;
845 Form = dwarf::DW_FORM_data4;
848 Form = dwarf::DW_FORM_data8;
851 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
855 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
859 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
861 // Get the raw data form of the large APInt.
862 const uint64_t *Ptr64 = Val.getRawData();
864 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
865 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
867 // Output the constant to DWARF one byte at a time.
868 for (int i = 0; i < NumBytes; i++) {
871 c = Ptr64[i / 8] >> (8 * (i & 7));
873 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
874 addUInt(Block, dwarf::DW_FORM_data1, c);
877 addBlock(Die, dwarf::DW_AT_const_value, Block);
880 /// addTemplateParams - Add template parameters into buffer.
881 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
882 // Add template parameters.
883 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
884 DIDescriptor Element = TParams.getElement(i);
885 if (Element.isTemplateTypeParameter())
886 constructTemplateTypeParameterDIE(Buffer,
887 DITemplateTypeParameter(Element));
888 else if (Element.isTemplateValueParameter())
889 constructTemplateValueParameterDIE(Buffer,
890 DITemplateValueParameter(Element));
894 /// getOrCreateContextDIE - Get context owner's DIE.
895 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
896 if (!Context || Context.isFile())
898 if (Context.isType())
899 return getOrCreateTypeDIE(DIType(Context));
900 if (Context.isNameSpace())
901 return getOrCreateNameSpace(DINameSpace(Context));
902 if (Context.isSubprogram())
903 return getOrCreateSubprogramDIE(DISubprogram(Context));
904 return getDIE(Context);
907 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
908 DIScope Context = resolve(Ty.getContext());
909 DIE *ContextDIE = getOrCreateContextDIE(Context);
911 DIE *TyDIE = getDIE(Ty);
916 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
918 constructTypeDIE(*TyDIE, Ty);
920 updateAcceleratorTables(Context, Ty, TyDIE);
924 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
926 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
933 // Construct the context before querying for the existence of the DIE in case
934 // such construction creates the DIE.
935 DIScope Context = resolve(Ty.getContext());
936 DIE *ContextDIE = getOrCreateContextDIE(Context);
939 DIE *TyDIE = getDIE(Ty);
944 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
946 if (Ty.isBasicType())
947 constructTypeDIE(*TyDIE, DIBasicType(Ty));
948 else if (Ty.isCompositeType()) {
949 DICompositeType CTy(Ty);
950 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
951 if (MDString *TypeId = CTy.getIdentifier()) {
952 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
953 // Skip updating the accellerator tables since this is not the full type
956 constructTypeDIE(*TyDIE, CTy);
958 assert(Ty.isDerivedType() && "Unknown kind of DIType");
959 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
962 updateAcceleratorTables(Context, Ty, TyDIE);
967 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
969 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
970 bool IsImplementation = 0;
971 if (Ty.isCompositeType()) {
972 DICompositeType CT(Ty);
973 // A runtime language of 0 actually means C/C++ and that any
974 // non-negative value is some version of Objective-C/C++.
975 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
977 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
978 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
980 if (!Context || Context.isCompileUnit() || Context.isFile() ||
981 Context.isNameSpace())
982 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
986 /// addType - Add a new type attribute to the specified entity.
987 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
988 assert(Ty && "Trying to add a type that doesn't exist?");
990 // Check for pre-existence.
991 DIEEntry *Entry = getDIEEntry(Ty);
992 // If it exists then use the existing value.
994 addDIEEntry(Entity, Attribute, Entry);
999 DIE *Buffer = getOrCreateTypeDIE(Ty);
1002 Entry = createDIEEntry(Buffer);
1003 insertDIEEntry(Ty, Entry);
1004 addDIEEntry(Entity, Attribute, Entry);
1007 // Accelerator table mutators - add each name along with its companion
1008 // DIE to the proper table while ensuring that the name that we're going
1009 // to reference is in the string table. We do this since the names we
1010 // add may not only be identical to the names in the DIE.
1011 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1012 if (!DD->useDwarfAccelTables())
1014 DU->getStringPoolEntry(Name);
1015 std::vector<const DIE *> &DIEs = AccelNames[Name];
1016 DIEs.push_back(Die);
1019 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1020 if (!DD->useDwarfAccelTables())
1022 DU->getStringPoolEntry(Name);
1023 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1024 DIEs.push_back(Die);
1027 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1028 if (!DD->useDwarfAccelTables())
1030 DU->getStringPoolEntry(Name);
1031 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1032 DIEs.push_back(Die);
1035 void DwarfUnit::addAccelType(StringRef Name,
1036 std::pair<const DIE *, unsigned> Die) {
1037 if (!DD->useDwarfAccelTables())
1039 DU->getStringPoolEntry(Name);
1040 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1041 DIEs.push_back(Die);
1044 /// addGlobalName - Add a new global name to the compile unit.
1045 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1046 std::string FullName = getParentContextString(Context) + Name.str();
1047 GlobalNames[FullName] = Die;
1050 /// getParentContextString - Walks the metadata parent chain in a language
1051 /// specific manner (using the compile unit language) and returns
1052 /// it as a string. This is done at the metadata level because DIEs may
1053 /// not currently have been added to the parent context and walking the
1054 /// DIEs looking for names is more expensive than walking the metadata.
1055 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1059 // FIXME: Decide whether to implement this for non-C++ languages.
1060 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1064 SmallVector<DIScope, 1> Parents;
1065 while (!Context.isCompileUnit()) {
1066 Parents.push_back(Context);
1067 if (Context.getContext())
1068 Context = resolve(Context.getContext());
1070 // Structure, etc types will have a NULL context if they're at the top
1075 // Reverse iterate over our list to go from the outermost construct to the
1077 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1081 StringRef Name = Ctx.getName();
1082 if (!Name.empty()) {
1090 /// constructTypeDIE - Construct basic type die from DIBasicType.
1091 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1092 // Get core information.
1093 StringRef Name = BTy.getName();
1094 // Add name if not anonymous or intermediate type.
1096 addString(&Buffer, dwarf::DW_AT_name, Name);
1098 // An unspecified type only has a name attribute.
1099 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1102 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1105 uint64_t Size = BTy.getSizeInBits() >> 3;
1106 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1109 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1110 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1111 // Get core information.
1112 StringRef Name = DTy.getName();
1113 uint64_t Size = DTy.getSizeInBits() >> 3;
1114 uint16_t Tag = Buffer.getTag();
1116 // Map to main type, void will not have a type.
1117 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1119 addType(&Buffer, FromTy);
1121 // Add name if not anonymous or intermediate type.
1123 addString(&Buffer, dwarf::DW_AT_name, Name);
1125 // Add size if non-zero (derived types might be zero-sized.)
1126 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1127 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1129 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1130 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1131 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1132 // Add source line info if available and TyDesc is not a forward declaration.
1133 if (!DTy.isForwardDecl())
1134 addSourceLine(&Buffer, DTy);
1137 /// constructTypeDIE - Construct type DIE from DICompositeType.
1138 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1139 // Add name if not anonymous or intermediate type.
1140 StringRef Name = CTy.getName();
1142 uint64_t Size = CTy.getSizeInBits() >> 3;
1143 uint16_t Tag = Buffer.getTag();
1146 case dwarf::DW_TAG_array_type:
1147 constructArrayTypeDIE(Buffer, CTy);
1149 case dwarf::DW_TAG_enumeration_type:
1150 constructEnumTypeDIE(Buffer, CTy);
1152 case dwarf::DW_TAG_subroutine_type: {
1153 // Add return type. A void return won't have a type.
1154 DIArray Elements = CTy.getTypeArray();
1155 DIType RTy(Elements.getElement(0));
1157 addType(&Buffer, RTy);
1159 bool isPrototyped = true;
1161 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1162 DIDescriptor Ty = Elements.getElement(i);
1163 if (Ty.isUnspecifiedParameter()) {
1164 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1165 isPrototyped = false;
1167 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1168 addType(Arg, DIType(Ty));
1169 if (DIType(Ty).isArtificial())
1170 addFlag(Arg, dwarf::DW_AT_artificial);
1173 // Add prototype flag if we're dealing with a C language and the
1174 // function has been prototyped.
1175 uint16_t Language = getLanguage();
1177 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1178 Language == dwarf::DW_LANG_ObjC))
1179 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1181 if (CTy.isLValueReference())
1182 addFlag(&Buffer, dwarf::DW_AT_reference);
1184 if (CTy.isRValueReference())
1185 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1187 case dwarf::DW_TAG_structure_type:
1188 case dwarf::DW_TAG_union_type:
1189 case dwarf::DW_TAG_class_type: {
1190 // Add elements to structure type.
1191 DIArray Elements = CTy.getTypeArray();
1192 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1193 DIDescriptor Element = Elements.getElement(i);
1194 DIE *ElemDie = NULL;
1195 if (Element.isSubprogram())
1196 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1197 else if (Element.isDerivedType()) {
1198 DIDerivedType DDTy(Element);
1199 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1200 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1201 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1202 dwarf::DW_AT_friend);
1203 } else if (DDTy.isStaticMember()) {
1204 getOrCreateStaticMemberDIE(DDTy);
1206 constructMemberDIE(Buffer, DDTy);
1208 } else if (Element.isObjCProperty()) {
1209 DIObjCProperty Property(Element);
1210 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1211 StringRef PropertyName = Property.getObjCPropertyName();
1212 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1213 if (Property.getType())
1214 addType(ElemDie, Property.getType());
1215 addSourceLine(ElemDie, Property);
1216 StringRef GetterName = Property.getObjCPropertyGetterName();
1217 if (!GetterName.empty())
1218 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1219 StringRef SetterName = Property.getObjCPropertySetterName();
1220 if (!SetterName.empty())
1221 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1222 unsigned PropertyAttributes = 0;
1223 if (Property.isReadOnlyObjCProperty())
1224 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1225 if (Property.isReadWriteObjCProperty())
1226 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1227 if (Property.isAssignObjCProperty())
1228 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1229 if (Property.isRetainObjCProperty())
1230 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1231 if (Property.isCopyObjCProperty())
1232 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1233 if (Property.isNonAtomicObjCProperty())
1234 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1235 if (PropertyAttributes)
1236 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1237 PropertyAttributes);
1239 DIEEntry *Entry = getDIEEntry(Element);
1241 Entry = createDIEEntry(ElemDie);
1242 insertDIEEntry(Element, Entry);
1248 if (CTy.isAppleBlockExtension())
1249 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1251 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1253 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1254 getOrCreateTypeDIE(ContainingType));
1256 if (CTy.isObjcClassComplete())
1257 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1259 // Add template parameters to a class, structure or union types.
1260 // FIXME: The support isn't in the metadata for this yet.
1261 if (Tag == dwarf::DW_TAG_class_type ||
1262 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1263 addTemplateParams(Buffer, CTy.getTemplateParams());
1271 // Add name if not anonymous or intermediate type.
1273 addString(&Buffer, dwarf::DW_AT_name, Name);
1275 if (Tag == dwarf::DW_TAG_enumeration_type ||
1276 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1277 Tag == dwarf::DW_TAG_union_type) {
1278 // Add size if non-zero (derived types might be zero-sized.)
1279 // TODO: Do we care about size for enum forward declarations?
1281 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1282 else if (!CTy.isForwardDecl())
1283 // Add zero size if it is not a forward declaration.
1284 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1286 // If we're a forward decl, say so.
1287 if (CTy.isForwardDecl())
1288 addFlag(&Buffer, dwarf::DW_AT_declaration);
1290 // Add source line info if available.
1291 if (!CTy.isForwardDecl())
1292 addSourceLine(&Buffer, CTy);
1294 // No harm in adding the runtime language to the declaration.
1295 unsigned RLang = CTy.getRunTimeLang();
1297 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1302 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1303 /// DITemplateTypeParameter.
1304 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1305 DITemplateTypeParameter TP) {
1307 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1308 // Add the type if it exists, it could be void and therefore no type.
1310 addType(ParamDIE, resolve(TP.getType()));
1311 if (!TP.getName().empty())
1312 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1315 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1316 /// DITemplateValueParameter.
1318 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1319 DITemplateValueParameter VP) {
1320 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1322 // Add the type if there is one, template template and template parameter
1323 // packs will not have a type.
1324 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1325 addType(ParamDIE, resolve(VP.getType()));
1326 if (!VP.getName().empty())
1327 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1328 if (Value *Val = VP.getValue()) {
1329 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1330 addConstantValue(ParamDIE, CI,
1331 isUnsignedDIType(DD, resolve(VP.getType())));
1332 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1333 // For declaration non-type template parameters (such as global values and
1335 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1336 addOpAddress(Block, Asm->getSymbol(GV));
1337 // Emit DW_OP_stack_value to use the address as the immediate value of the
1338 // parameter, rather than a pointer to it.
1339 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1340 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1341 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1342 assert(isa<MDString>(Val));
1343 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1344 cast<MDString>(Val)->getString());
1345 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1346 assert(isa<MDNode>(Val));
1347 DIArray A(cast<MDNode>(Val));
1348 addTemplateParams(*ParamDIE, A);
1353 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1354 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1355 // Construct the context before querying for the existence of the DIE in case
1356 // such construction creates the DIE.
1357 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1359 DIE *NDie = getDIE(NS);
1362 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1364 if (!NS.getName().empty()) {
1365 addString(NDie, dwarf::DW_AT_name, NS.getName());
1366 addAccelNamespace(NS.getName(), NDie);
1367 addGlobalName(NS.getName(), NDie, NS.getContext());
1369 addAccelNamespace("(anonymous namespace)", NDie);
1370 addSourceLine(NDie, NS);
1374 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1375 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1376 // Construct the context before querying for the existence of the DIE in case
1377 // such construction creates the DIE (as is the case for member function
1379 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1381 DIE *SPDie = getDIE(SP);
1385 DISubprogram SPDecl = SP.getFunctionDeclaration();
1386 if (SPDecl.isSubprogram())
1387 // Add subprogram definitions to the CU die directly.
1388 ContextDIE = UnitDie.get();
1390 // DW_TAG_inlined_subroutine may refer to this DIE.
1391 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1393 DIE *DeclDie = NULL;
1394 if (SPDecl.isSubprogram())
1395 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1397 // Add function template parameters.
1398 addTemplateParams(*SPDie, SP.getTemplateParams());
1400 // If this DIE is going to refer declaration info using AT_specification
1401 // then there is no need to add other attributes.
1403 // Refer function declaration directly.
1404 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1409 // Add the linkage name if we have one.
1410 StringRef LinkageName = SP.getLinkageName();
1411 if (!LinkageName.empty())
1412 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1413 GlobalValue::getRealLinkageName(LinkageName));
1415 // Constructors and operators for anonymous aggregates do not have names.
1416 if (!SP.getName().empty())
1417 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1419 addSourceLine(SPDie, SP);
1421 // Add the prototype if we have a prototype and we have a C like
1423 uint16_t Language = getLanguage();
1424 if (SP.isPrototyped() &&
1425 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1426 Language == dwarf::DW_LANG_ObjC))
1427 addFlag(SPDie, dwarf::DW_AT_prototyped);
1429 DICompositeType SPTy = SP.getType();
1430 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1431 "the type of a subprogram should be a subroutine");
1433 DIArray Args = SPTy.getTypeArray();
1434 // Add a return type. If this is a type like a C/C++ void type we don't add a
1436 if (Args.getElement(0))
1437 addType(SPDie, DIType(Args.getElement(0)));
1439 unsigned VK = SP.getVirtuality();
1441 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1442 DIEBlock *Block = getDIEBlock();
1443 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1444 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1445 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1446 ContainingTypeMap.insert(
1447 std::make_pair(SPDie, resolve(SP.getContainingType())));
1450 if (!SP.isDefinition()) {
1451 addFlag(SPDie, dwarf::DW_AT_declaration);
1453 // Add arguments. Do not add arguments for subprogram definition. They will
1454 // be handled while processing variables.
1455 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1456 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1457 DIType ATy(Args.getElement(i));
1459 if (ATy.isArtificial())
1460 addFlag(Arg, dwarf::DW_AT_artificial);
1464 if (SP.isArtificial())
1465 addFlag(SPDie, dwarf::DW_AT_artificial);
1467 if (!SP.isLocalToUnit())
1468 addFlag(SPDie, dwarf::DW_AT_external);
1470 if (SP.isOptimized())
1471 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1473 if (unsigned isa = Asm->getISAEncoding()) {
1474 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1477 if (SP.isLValueReference())
1478 addFlag(SPDie, dwarf::DW_AT_reference);
1480 if (SP.isRValueReference())
1481 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1483 if (SP.isProtected())
1484 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1485 dwarf::DW_ACCESS_protected);
1486 else if (SP.isPrivate())
1487 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1488 dwarf::DW_ACCESS_private);
1490 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1491 dwarf::DW_ACCESS_public);
1493 if (SP.isExplicit())
1494 addFlag(SPDie, dwarf::DW_AT_explicit);
1499 // Return const expression if value is a GEP to access merged global
1501 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1502 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1503 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1504 if (!CE || CE->getNumOperands() != 3 ||
1505 CE->getOpcode() != Instruction::GetElementPtr)
1508 // First operand points to a global struct.
1509 Value *Ptr = CE->getOperand(0);
1510 if (!isa<GlobalValue>(Ptr) ||
1511 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1514 // Second operand is zero.
1515 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1516 if (!CI || !CI->isZero())
1519 // Third operand is offset.
1520 if (!isa<ConstantInt>(CE->getOperand(2)))
1526 /// createGlobalVariableDIE - create global variable DIE.
1527 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1528 // Check for pre-existence.
1532 assert(GV.isGlobalVariable());
1534 DIScope GVContext = GV.getContext();
1535 DIType GTy = GV.getType();
1537 // If this is a static data member definition, some attributes belong
1538 // to the declaration DIE.
1539 DIE *VariableDIE = NULL;
1540 bool IsStaticMember = false;
1541 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1542 if (SDMDecl.Verify()) {
1543 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1544 // We need the declaration DIE that is in the static member's class.
1545 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1546 IsStaticMember = true;
1549 // If this is not a static data member definition, create the variable
1550 // DIE and add the initial set of attributes to it.
1552 // Construct the context before querying for the existence of the DIE in
1553 // case such construction creates the DIE.
1554 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1557 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1559 // Add name and type.
1560 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1561 addType(VariableDIE, GTy);
1563 // Add scoping info.
1564 if (!GV.isLocalToUnit())
1565 addFlag(VariableDIE, dwarf::DW_AT_external);
1567 // Add line number info.
1568 addSourceLine(VariableDIE, GV);
1572 bool addToAccelTable = false;
1573 DIE *VariableSpecDIE = NULL;
1574 bool isGlobalVariable = GV.getGlobal() != NULL;
1575 if (isGlobalVariable) {
1576 addToAccelTable = true;
1577 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1578 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1579 if (GV.getGlobal()->isThreadLocal()) {
1580 // FIXME: Make this work with -gsplit-dwarf.
1581 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1582 assert((PointerSize == 4 || PointerSize == 8) &&
1583 "Add support for other sizes if necessary");
1584 const MCExpr *Expr =
1585 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1586 // Based on GCC's support for TLS:
1587 if (!DD->useSplitDwarf()) {
1588 // 1) Start with a constNu of the appropriate pointer size
1589 addUInt(Block, dwarf::DW_FORM_data1,
1590 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1591 // 2) containing the (relocated) offset of the TLS variable
1592 // within the module's TLS block.
1593 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1595 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1596 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1598 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1599 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1601 DD->addArangeLabel(SymbolCU(this, Sym));
1602 addOpAddress(Block, Sym);
1604 // Do not create specification DIE if context is either compile unit
1606 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1607 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1608 // Create specification DIE.
1609 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1610 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1611 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1612 // A static member's declaration is already flagged as such.
1613 if (!SDMDecl.Verify())
1614 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1616 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1618 // Add the linkage name.
1619 StringRef LinkageName = GV.getLinkageName();
1620 if (!LinkageName.empty())
1621 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1622 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1624 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1626 dwarf::DW_AT_MIPS_linkage_name,
1627 GlobalValue::getRealLinkageName(LinkageName));
1628 } else if (const ConstantInt *CI =
1629 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1630 // AT_const_value was added when the static member was created. To avoid
1631 // emitting AT_const_value multiple times, we only add AT_const_value when
1632 // it is not a static member.
1633 if (!IsStaticMember)
1634 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1635 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1636 addToAccelTable = true;
1637 // GV is a merged global.
1638 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1639 Value *Ptr = CE->getOperand(0);
1640 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1641 DD->addArangeLabel(SymbolCU(this, Sym));
1642 addOpAddress(Block, Sym);
1643 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1644 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1645 addUInt(Block, dwarf::DW_FORM_udata,
1646 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1647 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1648 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1651 if (addToAccelTable) {
1652 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1653 addAccelName(GV.getName(), AddrDIE);
1655 // If the linkage name is different than the name, go ahead and output
1656 // that as well into the name table.
1657 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1658 addAccelName(GV.getLinkageName(), AddrDIE);
1661 if (!GV.isLocalToUnit())
1662 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1666 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1667 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1668 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1669 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1671 // The LowerBound value defines the lower bounds which is typically zero for
1672 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1673 // Count == -1 then the array is unbounded and we do not emit
1674 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1675 // Count == 0, then the array has zero elements in which case we do not emit
1677 int64_t LowerBound = SR.getLo();
1678 int64_t DefaultLowerBound = getDefaultLowerBound();
1679 int64_t Count = SR.getCount();
1681 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1682 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1684 if (Count != -1 && Count != 0)
1685 // FIXME: An unbounded array should reference the expression that defines
1687 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1688 LowerBound + Count - 1);
1691 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1692 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1694 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1696 // Emit the element type.
1697 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1699 // Get an anonymous type for index type.
1700 // FIXME: This type should be passed down from the front end
1701 // as different languages may have different sizes for indexes.
1702 DIE *IdxTy = getIndexTyDie();
1704 // Construct an anonymous type for index type.
1705 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1706 addString(IdxTy, dwarf::DW_AT_name, "int");
1707 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1708 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1709 dwarf::DW_ATE_signed);
1710 setIndexTyDie(IdxTy);
1713 // Add subranges to array type.
1714 DIArray Elements = CTy.getTypeArray();
1715 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1716 DIDescriptor Element = Elements.getElement(i);
1717 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1718 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1722 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1723 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1724 DIArray Elements = CTy.getTypeArray();
1726 // Add enumerators to enumeration type.
1727 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1728 DIEnumerator Enum(Elements.getElement(i));
1729 if (Enum.isEnumerator()) {
1730 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1731 StringRef Name = Enum.getName();
1732 addString(Enumerator, dwarf::DW_AT_name, Name);
1733 int64_t Value = Enum.getEnumValue();
1734 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1738 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1740 addType(&Buffer, DTy);
1741 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1745 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1747 void DwarfUnit::constructContainingTypeDIEs() {
1748 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1749 CE = ContainingTypeMap.end();
1751 DIE *SPDie = CI->first;
1752 DIDescriptor D(CI->second);
1755 DIE *NDie = getDIE(D);
1758 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1762 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1763 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1764 StringRef Name = DV.getName();
1766 // Define variable debug information entry.
1767 DIE *VariableDie = new DIE(DV.getTag());
1768 DbgVariable *AbsVar = DV.getAbstractVariable();
1769 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1771 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1774 addString(VariableDie, dwarf::DW_AT_name, Name);
1775 addSourceLine(VariableDie, DV.getVariable());
1776 addType(VariableDie, DV.getType());
1779 if (DV.isArtificial())
1780 addFlag(VariableDie, dwarf::DW_AT_artificial);
1782 if (isScopeAbstract) {
1783 DV.setDIE(VariableDie);
1787 // Add variable address.
1789 unsigned Offset = DV.getDotDebugLocOffset();
1790 if (Offset != ~0U) {
1791 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1792 Asm->GetTempSymbol("debug_loc", Offset));
1793 DV.setDIE(VariableDie);
1797 // Check if variable is described by a DBG_VALUE instruction.
1798 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1799 assert(DVInsn->getNumOperands() == 3);
1800 if (DVInsn->getOperand(0).isReg()) {
1801 const MachineOperand RegOp = DVInsn->getOperand(0);
1802 // If the second operand is an immediate, this is an indirect value.
1803 if (DVInsn->getOperand(1).isImm()) {
1804 MachineLocation Location(RegOp.getReg(),
1805 DVInsn->getOperand(1).getImm());
1806 addVariableAddress(DV, VariableDie, Location);
1807 } else if (RegOp.getReg())
1808 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1809 } else if (DVInsn->getOperand(0).isImm())
1810 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1811 else if (DVInsn->getOperand(0).isFPImm())
1812 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1813 else if (DVInsn->getOperand(0).isCImm())
1814 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1815 isUnsignedDIType(DD, DV.getType()));
1817 DV.setDIE(VariableDie);
1820 // .. else use frame index.
1821 int FI = DV.getFrameIndex();
1823 unsigned FrameReg = 0;
1824 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1825 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1826 MachineLocation Location(FrameReg, Offset);
1827 addVariableAddress(DV, VariableDie, Location);
1831 DV.setDIE(VariableDie);
1835 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1836 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1837 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1838 StringRef Name = DT.getName();
1840 addString(MemberDie, dwarf::DW_AT_name, Name);
1842 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1844 addSourceLine(MemberDie, DT);
1846 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1848 // For C++, virtual base classes are not at fixed offset. Use following
1849 // expression to extract appropriate offset from vtable.
1850 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1852 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1853 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1854 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1855 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1856 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1857 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1858 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1859 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1861 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1863 uint64_t Size = DT.getSizeInBits();
1864 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1865 uint64_t OffsetInBytes;
1867 if (Size != FieldSize) {
1869 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1870 getBaseTypeSize(DD, DT) >> 3);
1871 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1873 uint64_t Offset = DT.getOffsetInBits();
1874 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1875 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1876 uint64_t FieldOffset = (HiMark - FieldSize);
1877 Offset -= FieldOffset;
1879 // Maybe we need to work from the other end.
1880 if (Asm->getDataLayout().isLittleEndian())
1881 Offset = FieldSize - (Offset + Size);
1882 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1884 // Here DW_AT_data_member_location points to the anonymous
1885 // field that includes this bit field.
1886 OffsetInBytes = FieldOffset >> 3;
1888 // This is not a bitfield.
1889 OffsetInBytes = DT.getOffsetInBits() >> 3;
1891 if (DD->getDwarfVersion() <= 2) {
1892 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1893 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1894 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1895 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1897 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1901 if (DT.isProtected())
1902 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1903 dwarf::DW_ACCESS_protected);
1904 else if (DT.isPrivate())
1905 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1906 dwarf::DW_ACCESS_private);
1907 // Otherwise C++ member and base classes are considered public.
1909 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1910 dwarf::DW_ACCESS_public);
1912 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1913 dwarf::DW_VIRTUALITY_virtual);
1915 // Objective-C properties.
1916 if (MDNode *PNode = DT.getObjCProperty())
1917 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1918 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1921 if (DT.isArtificial())
1922 addFlag(MemberDie, dwarf::DW_AT_artificial);
1925 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1926 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1930 // Construct the context before querying for the existence of the DIE in case
1931 // such construction creates the DIE.
1932 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1933 assert(dwarf::isType(ContextDIE->getTag()) &&
1934 "Static member should belong to a type.");
1936 DIE *StaticMemberDIE = getDIE(DT);
1937 if (StaticMemberDIE)
1938 return StaticMemberDIE;
1940 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1942 DIType Ty = resolve(DT.getTypeDerivedFrom());
1944 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1945 addType(StaticMemberDIE, Ty);
1946 addSourceLine(StaticMemberDIE, DT);
1947 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1948 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1950 // FIXME: We could omit private if the parent is a class_type, and
1951 // public if the parent is something else.
1952 if (DT.isProtected())
1953 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1954 dwarf::DW_ACCESS_protected);
1955 else if (DT.isPrivate())
1956 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1957 dwarf::DW_ACCESS_private);
1959 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1960 dwarf::DW_ACCESS_public);
1962 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1963 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1964 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1965 addConstantFPValue(StaticMemberDIE, CFP);
1967 return StaticMemberDIE;
1970 void DwarfUnit::emitHeader(const MCSection *ASection,
1971 const MCSymbol *ASectionSym) const {
1972 Asm->OutStreamer.AddComment("DWARF version number");
1973 Asm->EmitInt16(DD->getDwarfVersion());
1974 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1975 // We share one abbreviations table across all units so it's always at the
1976 // start of the section. Use a relocatable offset where needed to ensure
1977 // linking doesn't invalidate that offset.
1978 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1979 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1980 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1983 DwarfCompileUnit::~DwarfCompileUnit() {}
1985 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
1986 // Define start line table label for each Compile Unit.
1987 MCSymbol *LineTableStartSym =
1988 Asm->GetTempSymbol("line_table_start", getUniqueID());
1989 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
1992 // Use a single line table if we are generating assembly.
1993 bool UseTheFirstCU =
1994 Asm->OutStreamer.hasRawTextSupport() || (getUniqueID() == 0);
1996 // DW_AT_stmt_list is a offset of line number information for this
1997 // compile unit in debug_line section. For split dwarf this is
1998 // left in the skeleton CU and so not included.
1999 // The line table entries are not always emitted in assembly, so it
2000 // is not okay to use line_table_start here.
2001 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2002 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list,
2003 UseTheFirstCU ? DwarfLineSectionSym : LineTableStartSym);
2004 else if (UseTheFirstCU)
2005 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
2007 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2008 DwarfLineSectionSym);
2011 DwarfTypeUnit::~DwarfTypeUnit() {}
2013 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2014 const MCSymbol *ASectionSym) const {
2015 DwarfUnit::emitHeader(ASection, ASectionSym);
2016 Asm->OutStreamer.AddComment("Type Signature");
2017 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2018 Asm->OutStreamer.AddComment("Type DIE Offset");
2019 // In a skeleton type unit there is no type DIE so emit a zero offset.
2020 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2021 sizeof(Ty->getOffset()));
2024 void DwarfTypeUnit::initSection(const MCSection *Section) {
2025 assert(!this->Section);
2026 this->Section = Section;
2027 // Since each type unit is contained in its own COMDAT section, the begin
2028 // label and the section label are the same. Using the begin label emission in
2029 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2030 // the only other alternative of lazily constructing start-of-section labels
2031 // and storing a mapping in DwarfDebug (or AsmPrinter).
2032 this->SectionSym = this->LabelBegin =
2033 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2035 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2036 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());