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) {}
62 /// ~Unit - Destructor for compile unit.
63 DwarfUnit::~DwarfUnit() {
64 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
65 DIEBlocks[j]->~DIEBlock();
66 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
67 DIELocs[j]->~DIELoc();
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(DIE *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(DIELoc *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(DIELoc *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(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) {
243 addLabel(Die, (dwarf::Attribute)0, Form, Label);
246 /// addSectionLabel - Add a Dwarf section label attribute data and value.
248 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
249 const MCSymbol *Label) {
250 if (DD->getDwarfVersion() >= 4)
251 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
253 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
256 /// addSectionOffset - Add an offset into a section attribute data and value.
258 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
260 if (DD->getDwarfVersion() >= 4)
261 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
263 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
266 /// addLabelAddress - Add a dwarf label attribute data and value using
267 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
269 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
272 DD->addArangeLabel(SymbolCU(this, Label));
274 if (!DD->useSplitDwarf()) {
276 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
277 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
279 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
280 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
283 unsigned idx = DU->getAddrPoolIndex(Label);
284 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
285 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
289 /// addOpAddress - Add a dwarf op address data and value using the
290 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
292 void DwarfUnit::addOpAddress(DIELoc *Die, const MCSymbol *Sym) {
293 if (!DD->useSplitDwarf()) {
294 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
295 addLabel(Die, dwarf::DW_FORM_udata, Sym);
297 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
298 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
302 /// addSectionDelta - Add a section label delta attribute data and value.
304 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
305 const MCSymbol *Hi, const MCSymbol *Lo) {
306 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
307 if (DD->getDwarfVersion() >= 4)
308 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
310 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
313 /// addDIEEntry - Add a DIE attribute data and value.
315 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
316 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
319 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
320 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
321 new (DIEValueAllocator) DIETypeSignature(Type));
324 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
326 const DIE *DieCU = Die->getUnitOrNull();
327 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
329 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
330 DieCU = getUnitDie();
332 EntryCU = getUnitDie();
333 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
334 : dwarf::DW_FORM_ref_addr,
338 /// Create a DIE with the given Tag, add the DIE to its parent, and
339 /// call insertDIE if MD is not null.
340 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
341 DIE *Die = new DIE(Tag);
342 Parent.addChild(Die);
348 /// addBlock - Add block data.
350 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIELoc *Loc) {
351 Loc->ComputeSize(Asm);
352 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
353 Die->addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
356 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
358 Block->ComputeSize(Asm);
359 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
360 Die->addValue(Attribute, Block->BestForm(), Block);
363 /// addSourceLine - Add location information to specified debug information
365 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
366 StringRef Directory) {
371 DD->getOrCreateSourceID(File, Directory, getCU().getUniqueID());
372 assert(FileID && "Invalid file id");
373 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
374 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
377 /// addSourceLine - Add location information to specified debug information
379 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
380 assert(V.isVariable());
382 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
383 V.getContext().getDirectory());
386 /// addSourceLine - Add location information to specified debug information
388 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
389 assert(G.isGlobalVariable());
391 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
394 /// addSourceLine - Add location information to specified debug information
396 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
397 assert(SP.isSubprogram());
399 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
402 /// addSourceLine - Add location information to specified debug information
404 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
407 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
410 /// addSourceLine - Add location information to specified debug information
412 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
413 assert(Ty.isObjCProperty());
415 DIFile File = Ty.getFile();
416 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
417 File.getDirectory());
420 /// addSourceLine - Add location information to specified debug information
422 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
425 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
428 /// addVariableAddress - Add DW_AT_location attribute for a
429 /// DbgVariable based on provided MachineLocation.
430 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
431 MachineLocation Location) {
432 if (DV.variableHasComplexAddress())
433 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
434 else if (DV.isBlockByrefVariable())
435 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
437 addAddress(Die, dwarf::DW_AT_location, Location,
438 DV.getVariable().isIndirect());
441 /// addRegisterOp - Add register operand.
442 void DwarfUnit::addRegisterOp(DIELoc *TheDie, unsigned Reg) {
443 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
444 int DWReg = RI->getDwarfRegNum(Reg, false);
445 bool isSubRegister = DWReg < 0;
449 // Go up the super-register chain until we hit a valid dwarf register number.
450 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
451 DWReg = RI->getDwarfRegNum(*SR, false);
453 Idx = RI->getSubRegIndex(*SR, Reg);
457 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
458 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
464 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
466 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
467 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
472 unsigned Size = RI->getSubRegIdxSize(Idx);
473 unsigned Offset = RI->getSubRegIdxOffset(Idx);
475 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
476 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
477 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
479 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
480 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
481 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
486 /// addRegisterOffset - Add register offset.
487 void DwarfUnit::addRegisterOffset(DIELoc *TheDie, unsigned Reg,
489 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
490 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
491 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
492 if (Reg == TRI->getFrameRegister(*Asm->MF))
493 // If variable offset is based in frame register then use fbreg.
494 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
496 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
498 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
499 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
501 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
504 /// addAddress - Add an address attribute to a die based on the location
506 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
507 const MachineLocation &Location, bool Indirect) {
508 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
510 if (Location.isReg() && !Indirect)
511 addRegisterOp(Loc, Location.getReg());
513 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
514 if (Indirect && !Location.isReg()) {
515 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
519 // Now attach the location information to the DIE.
520 addBlock(Die, Attribute, Loc);
523 /// addComplexAddress - Start with the address based on the location provided,
524 /// and generate the DWARF information necessary to find the actual variable
525 /// given the extra address information encoded in the DbgVariable, starting
526 /// from the starting location. Add the DWARF information to the die.
528 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
529 dwarf::Attribute Attribute,
530 const MachineLocation &Location) {
531 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
532 unsigned N = DV.getNumAddrElements();
534 if (Location.isReg()) {
535 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
536 // If first address element is OpPlus then emit
537 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
538 addRegisterOffset(Loc, Location.getReg(), DV.getAddrElement(1));
541 addRegisterOp(Loc, Location.getReg());
543 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
546 uint64_t Element = DV.getAddrElement(i);
547 if (Element == DIBuilder::OpPlus) {
548 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
549 addUInt(Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
550 } else if (Element == DIBuilder::OpDeref) {
551 if (!Location.isReg())
552 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
554 llvm_unreachable("unknown DIBuilder Opcode");
557 // Now attach the location information to the DIE.
558 addBlock(Die, Attribute, Loc);
561 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
562 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
563 gives the variable VarName either the struct, or a pointer to the struct, as
564 its type. This is necessary for various behind-the-scenes things the
565 compiler needs to do with by-reference variables in Blocks.
567 However, as far as the original *programmer* is concerned, the variable
568 should still have type 'SomeType', as originally declared.
570 The function getBlockByrefType dives into the __Block_byref_x_VarName
571 struct to find the original type of the variable, which is then assigned to
572 the variable's Debug Information Entry as its real type. So far, so good.
573 However now the debugger will expect the variable VarName to have the type
574 SomeType. So we need the location attribute for the variable to be an
575 expression that explains to the debugger how to navigate through the
576 pointers and struct to find the actual variable of type SomeType.
578 The following function does just that. We start by getting
579 the "normal" location for the variable. This will be the location
580 of either the struct __Block_byref_x_VarName or the pointer to the
581 struct __Block_byref_x_VarName.
583 The struct will look something like:
585 struct __Block_byref_x_VarName {
587 struct __Block_byref_x_VarName *forwarding;
588 ... <various other fields>
590 ... <maybe more fields>
593 If we are given the struct directly (as our starting point) we
594 need to tell the debugger to:
596 1). Add the offset of the forwarding field.
598 2). Follow that pointer to get the real __Block_byref_x_VarName
599 struct to use (the real one may have been copied onto the heap).
601 3). Add the offset for the field VarName, to find the actual variable.
603 If we started with a pointer to the struct, then we need to
604 dereference that pointer first, before the other steps.
605 Translating this into DWARF ops, we will need to append the following
606 to the current location description for the variable:
608 DW_OP_deref -- optional, if we start with a pointer
609 DW_OP_plus_uconst <forward_fld_offset>
611 DW_OP_plus_uconst <varName_fld_offset>
613 That is what this function does. */
615 /// addBlockByrefAddress - Start with the address based on the location
616 /// provided, and generate the DWARF information necessary to find the
617 /// actual Block variable (navigating the Block struct) based on the
618 /// starting location. Add the DWARF information to the die. For
619 /// more information, read large comment just above here.
621 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
622 dwarf::Attribute Attribute,
623 const MachineLocation &Location) {
624 DIType Ty = DV.getType();
626 uint16_t Tag = Ty.getTag();
627 bool isPointer = false;
629 StringRef varName = DV.getName();
631 if (Tag == dwarf::DW_TAG_pointer_type) {
632 DIDerivedType DTy(Ty);
633 TmpTy = resolve(DTy.getTypeDerivedFrom());
637 DICompositeType blockStruct(TmpTy);
639 // Find the __forwarding field and the variable field in the __Block_byref
641 DIArray Fields = blockStruct.getTypeArray();
642 DIDerivedType varField;
643 DIDerivedType forwardingField;
645 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
646 DIDerivedType DT(Fields.getElement(i));
647 StringRef fieldName = DT.getName();
648 if (fieldName == "__forwarding")
649 forwardingField = DT;
650 else if (fieldName == varName)
654 // Get the offsets for the forwarding field and the variable field.
655 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
656 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
658 // Decode the original location, and use that as the start of the byref
659 // variable's location.
660 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
662 if (Location.isReg())
663 addRegisterOp(Loc, Location.getReg());
665 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
667 // If we started with a pointer to the __Block_byref... struct, then
668 // the first thing we need to do is dereference the pointer (DW_OP_deref).
670 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
672 // Next add the offset for the '__forwarding' field:
673 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
674 // adding the offset if it's 0.
675 if (forwardingFieldOffset > 0) {
676 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
677 addUInt(Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
680 // Now dereference the __forwarding field to get to the real __Block_byref
681 // struct: DW_OP_deref.
682 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
684 // Now that we've got the real __Block_byref... struct, add the offset
685 // for the variable's field to get to the location of the actual variable:
686 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
687 if (varFieldOffset > 0) {
688 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
689 addUInt(Loc, dwarf::DW_FORM_udata, varFieldOffset);
692 // Now attach the location information to the DIE.
693 addBlock(Die, Attribute, Loc);
696 /// isTypeSigned - Return true if the type is signed.
697 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
698 if (Ty.isDerivedType())
699 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
701 if (Ty.isBasicType())
702 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
703 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
704 *SizeInBits = Ty.getSizeInBits();
710 /// Return true if type encoding is unsigned.
711 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
712 DIDerivedType DTy(Ty);
713 if (DTy.isDerivedType())
714 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
717 if (BTy.isBasicType()) {
718 unsigned Encoding = BTy.getEncoding();
719 if (Encoding == dwarf::DW_ATE_unsigned ||
720 Encoding == dwarf::DW_ATE_unsigned_char ||
721 Encoding == dwarf::DW_ATE_boolean)
727 /// If this type is derived from a base type then return base type size.
728 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
729 unsigned Tag = Ty.getTag();
731 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
732 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
733 Tag != dwarf::DW_TAG_restrict_type)
734 return Ty.getSizeInBits();
736 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
738 // If this type is not derived from any type then take conservative approach.
739 if (!BaseType.isValid())
740 return Ty.getSizeInBits();
742 // If this is a derived type, go ahead and get the base type, unless it's a
743 // reference then it's just the size of the field. Pointer types have no need
744 // of this since they're a different type of qualification on the type.
745 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
746 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
747 return Ty.getSizeInBits();
749 if (BaseType.isDerivedType())
750 return getBaseTypeSize(DD, DIDerivedType(BaseType));
752 return BaseType.getSizeInBits();
755 /// addConstantValue - Add constant value entry in variable DIE.
756 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
758 // FIXME: This is a bit conservative/simple - it emits negative values at
759 // their maximum bit width which is a bit unfortunate (& doesn't prefer
760 // udata/sdata over dataN as suggested by the DWARF spec)
761 assert(MO.isImm() && "Invalid machine operand!");
763 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
766 // If we're a signed constant definitely use sdata.
767 if (SignedConstant) {
768 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
772 // Else use data for now unless it's larger than we can deal with.
773 switch (SizeInBits) {
775 Form = dwarf::DW_FORM_data1;
778 Form = dwarf::DW_FORM_data2;
781 Form = dwarf::DW_FORM_data4;
784 Form = dwarf::DW_FORM_data8;
787 Form = dwarf::DW_FORM_udata;
788 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
791 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
794 /// addConstantFPValue - Add constant value entry in variable DIE.
795 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
796 assert(MO.isFPImm() && "Invalid machine operand!");
797 // FIXME-echristo: Use a block here.
798 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
799 APFloat FPImm = MO.getFPImm()->getValueAPF();
801 // Get the raw data form of the floating point.
802 const APInt FltVal = FPImm.bitcastToAPInt();
803 const char *FltPtr = (const char *)FltVal.getRawData();
805 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
806 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
807 int Incr = (LittleEndian ? 1 : -1);
808 int Start = (LittleEndian ? 0 : NumBytes - 1);
809 int Stop = (LittleEndian ? NumBytes : -1);
811 // Output the constant to DWARF one byte at a time.
812 for (; Start != Stop; Start += Incr)
813 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
815 addBlock(Die, dwarf::DW_AT_const_value, Block);
818 /// addConstantFPValue - Add constant value entry in variable DIE.
819 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
820 // Pass this down to addConstantValue as an unsigned bag of bits.
821 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
824 /// addConstantValue - Add constant value entry in variable DIE.
825 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
827 addConstantValue(Die, CI->getValue(), Unsigned);
830 // addConstantValue - Add constant value entry in variable DIE.
831 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
832 unsigned CIBitWidth = Val.getBitWidth();
833 if (CIBitWidth <= 64) {
834 // If we're a signed constant definitely use sdata.
836 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
841 // Else use data for now unless it's larger than we can deal with.
843 switch (CIBitWidth) {
845 Form = dwarf::DW_FORM_data1;
848 Form = dwarf::DW_FORM_data2;
851 Form = dwarf::DW_FORM_data4;
854 Form = dwarf::DW_FORM_data8;
857 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
861 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
865 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
867 // Get the raw data form of the large APInt.
868 const uint64_t *Ptr64 = Val.getRawData();
870 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
871 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
873 // Output the constant to DWARF one byte at a time.
874 for (int i = 0; i < NumBytes; i++) {
877 c = Ptr64[i / 8] >> (8 * (i & 7));
879 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
880 addUInt(Block, dwarf::DW_FORM_data1, c);
883 addBlock(Die, dwarf::DW_AT_const_value, Block);
886 /// addTemplateParams - Add template parameters into buffer.
887 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
888 // Add template parameters.
889 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
890 DIDescriptor Element = TParams.getElement(i);
891 if (Element.isTemplateTypeParameter())
892 constructTemplateTypeParameterDIE(Buffer,
893 DITemplateTypeParameter(Element));
894 else if (Element.isTemplateValueParameter())
895 constructTemplateValueParameterDIE(Buffer,
896 DITemplateValueParameter(Element));
900 /// getOrCreateContextDIE - Get context owner's DIE.
901 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
902 if (!Context || Context.isFile())
904 if (Context.isType())
905 return getOrCreateTypeDIE(DIType(Context));
906 if (Context.isNameSpace())
907 return getOrCreateNameSpace(DINameSpace(Context));
908 if (Context.isSubprogram())
909 return getOrCreateSubprogramDIE(DISubprogram(Context));
910 return getDIE(Context);
913 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
914 DIScope Context = resolve(Ty.getContext());
915 DIE *ContextDIE = getOrCreateContextDIE(Context);
917 DIE *TyDIE = getDIE(Ty);
922 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
924 constructTypeDIE(*TyDIE, Ty);
926 updateAcceleratorTables(Context, Ty, TyDIE);
930 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
932 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
939 // Construct the context before querying for the existence of the DIE in case
940 // such construction creates the DIE.
941 DIScope Context = resolve(Ty.getContext());
942 DIE *ContextDIE = getOrCreateContextDIE(Context);
945 DIE *TyDIE = getDIE(Ty);
950 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
952 if (Ty.isBasicType())
953 constructTypeDIE(*TyDIE, DIBasicType(Ty));
954 else if (Ty.isCompositeType()) {
955 DICompositeType CTy(Ty);
956 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
957 if (MDString *TypeId = CTy.getIdentifier()) {
958 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
959 // Skip updating the accellerator tables since this is not the full type
962 constructTypeDIE(*TyDIE, CTy);
964 assert(Ty.isDerivedType() && "Unknown kind of DIType");
965 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
968 updateAcceleratorTables(Context, Ty, TyDIE);
973 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
975 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
976 bool IsImplementation = 0;
977 if (Ty.isCompositeType()) {
978 DICompositeType CT(Ty);
979 // A runtime language of 0 actually means C/C++ and that any
980 // non-negative value is some version of Objective-C/C++.
981 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
983 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
984 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
986 if (!Context || Context.isCompileUnit() || Context.isFile() ||
987 Context.isNameSpace())
988 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
992 /// addType - Add a new type attribute to the specified entity.
993 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
994 assert(Ty && "Trying to add a type that doesn't exist?");
996 // Check for pre-existence.
997 DIEEntry *Entry = getDIEEntry(Ty);
998 // If it exists then use the existing value.
1000 addDIEEntry(Entity, Attribute, Entry);
1005 DIE *Buffer = getOrCreateTypeDIE(Ty);
1008 Entry = createDIEEntry(Buffer);
1009 insertDIEEntry(Ty, Entry);
1010 addDIEEntry(Entity, Attribute, Entry);
1013 // Accelerator table mutators - add each name along with its companion
1014 // DIE to the proper table while ensuring that the name that we're going
1015 // to reference is in the string table. We do this since the names we
1016 // add may not only be identical to the names in the DIE.
1017 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1018 if (!DD->useDwarfAccelTables())
1020 DU->getStringPoolEntry(Name);
1021 std::vector<const DIE *> &DIEs = AccelNames[Name];
1022 DIEs.push_back(Die);
1025 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1026 if (!DD->useDwarfAccelTables())
1028 DU->getStringPoolEntry(Name);
1029 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1030 DIEs.push_back(Die);
1033 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1034 if (!DD->useDwarfAccelTables())
1036 DU->getStringPoolEntry(Name);
1037 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1038 DIEs.push_back(Die);
1041 void DwarfUnit::addAccelType(StringRef Name,
1042 std::pair<const DIE *, unsigned> Die) {
1043 if (!DD->useDwarfAccelTables())
1045 DU->getStringPoolEntry(Name);
1046 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1047 DIEs.push_back(Die);
1050 /// addGlobalName - Add a new global name to the compile unit.
1051 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1052 std::string FullName = getParentContextString(Context) + Name.str();
1053 GlobalNames[FullName] = Die;
1056 /// getParentContextString - Walks the metadata parent chain in a language
1057 /// specific manner (using the compile unit language) and returns
1058 /// it as a string. This is done at the metadata level because DIEs may
1059 /// not currently have been added to the parent context and walking the
1060 /// DIEs looking for names is more expensive than walking the metadata.
1061 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1065 // FIXME: Decide whether to implement this for non-C++ languages.
1066 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1070 SmallVector<DIScope, 1> Parents;
1071 while (!Context.isCompileUnit()) {
1072 Parents.push_back(Context);
1073 if (Context.getContext())
1074 Context = resolve(Context.getContext());
1076 // Structure, etc types will have a NULL context if they're at the top
1081 // Reverse iterate over our list to go from the outermost construct to the
1083 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1087 StringRef Name = Ctx.getName();
1088 if (!Name.empty()) {
1096 /// constructTypeDIE - Construct basic type die from DIBasicType.
1097 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1098 // Get core information.
1099 StringRef Name = BTy.getName();
1100 // Add name if not anonymous or intermediate type.
1102 addString(&Buffer, dwarf::DW_AT_name, Name);
1104 // An unspecified type only has a name attribute.
1105 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1108 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1111 uint64_t Size = BTy.getSizeInBits() >> 3;
1112 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1115 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1116 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1117 // Get core information.
1118 StringRef Name = DTy.getName();
1119 uint64_t Size = DTy.getSizeInBits() >> 3;
1120 uint16_t Tag = Buffer.getTag();
1122 // Map to main type, void will not have a type.
1123 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1125 addType(&Buffer, FromTy);
1127 // Add name if not anonymous or intermediate type.
1129 addString(&Buffer, dwarf::DW_AT_name, Name);
1131 // Add size if non-zero (derived types might be zero-sized.)
1132 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1133 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1135 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1136 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1137 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1138 // Add source line info if available and TyDesc is not a forward declaration.
1139 if (!DTy.isForwardDecl())
1140 addSourceLine(&Buffer, DTy);
1143 /// constructTypeDIE - Construct type DIE from DICompositeType.
1144 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1145 // Add name if not anonymous or intermediate type.
1146 StringRef Name = CTy.getName();
1148 uint64_t Size = CTy.getSizeInBits() >> 3;
1149 uint16_t Tag = Buffer.getTag();
1152 case dwarf::DW_TAG_array_type:
1153 constructArrayTypeDIE(Buffer, CTy);
1155 case dwarf::DW_TAG_enumeration_type:
1156 constructEnumTypeDIE(Buffer, CTy);
1158 case dwarf::DW_TAG_subroutine_type: {
1159 // Add return type. A void return won't have a type.
1160 DIArray Elements = CTy.getTypeArray();
1161 DIType RTy(Elements.getElement(0));
1163 addType(&Buffer, RTy);
1165 bool isPrototyped = true;
1167 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1168 DIDescriptor Ty = Elements.getElement(i);
1169 if (Ty.isUnspecifiedParameter()) {
1170 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1171 isPrototyped = false;
1173 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1174 addType(Arg, DIType(Ty));
1175 if (DIType(Ty).isArtificial())
1176 addFlag(Arg, dwarf::DW_AT_artificial);
1179 // Add prototype flag if we're dealing with a C language and the
1180 // function has been prototyped.
1181 uint16_t Language = getLanguage();
1183 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1184 Language == dwarf::DW_LANG_ObjC))
1185 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1187 if (CTy.isLValueReference())
1188 addFlag(&Buffer, dwarf::DW_AT_reference);
1190 if (CTy.isRValueReference())
1191 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1193 case dwarf::DW_TAG_structure_type:
1194 case dwarf::DW_TAG_union_type:
1195 case dwarf::DW_TAG_class_type: {
1196 // Add elements to structure type.
1197 DIArray Elements = CTy.getTypeArray();
1198 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1199 DIDescriptor Element = Elements.getElement(i);
1200 DIE *ElemDie = NULL;
1201 if (Element.isSubprogram())
1202 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1203 else if (Element.isDerivedType()) {
1204 DIDerivedType DDTy(Element);
1205 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1206 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1207 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1208 dwarf::DW_AT_friend);
1209 } else if (DDTy.isStaticMember()) {
1210 getOrCreateStaticMemberDIE(DDTy);
1212 constructMemberDIE(Buffer, DDTy);
1214 } else if (Element.isObjCProperty()) {
1215 DIObjCProperty Property(Element);
1216 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1217 StringRef PropertyName = Property.getObjCPropertyName();
1218 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1219 if (Property.getType())
1220 addType(ElemDie, Property.getType());
1221 addSourceLine(ElemDie, Property);
1222 StringRef GetterName = Property.getObjCPropertyGetterName();
1223 if (!GetterName.empty())
1224 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1225 StringRef SetterName = Property.getObjCPropertySetterName();
1226 if (!SetterName.empty())
1227 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1228 unsigned PropertyAttributes = 0;
1229 if (Property.isReadOnlyObjCProperty())
1230 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1231 if (Property.isReadWriteObjCProperty())
1232 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1233 if (Property.isAssignObjCProperty())
1234 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1235 if (Property.isRetainObjCProperty())
1236 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1237 if (Property.isCopyObjCProperty())
1238 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1239 if (Property.isNonAtomicObjCProperty())
1240 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1241 if (PropertyAttributes)
1242 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1243 PropertyAttributes);
1245 DIEEntry *Entry = getDIEEntry(Element);
1247 Entry = createDIEEntry(ElemDie);
1248 insertDIEEntry(Element, Entry);
1254 if (CTy.isAppleBlockExtension())
1255 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1257 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1259 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1260 getOrCreateTypeDIE(ContainingType));
1262 if (CTy.isObjcClassComplete())
1263 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1265 // Add template parameters to a class, structure or union types.
1266 // FIXME: The support isn't in the metadata for this yet.
1267 if (Tag == dwarf::DW_TAG_class_type ||
1268 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1269 addTemplateParams(Buffer, CTy.getTemplateParams());
1277 // Add name if not anonymous or intermediate type.
1279 addString(&Buffer, dwarf::DW_AT_name, Name);
1281 if (Tag == dwarf::DW_TAG_enumeration_type ||
1282 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1283 Tag == dwarf::DW_TAG_union_type) {
1284 // Add size if non-zero (derived types might be zero-sized.)
1285 // TODO: Do we care about size for enum forward declarations?
1287 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1288 else if (!CTy.isForwardDecl())
1289 // Add zero size if it is not a forward declaration.
1290 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1292 // If we're a forward decl, say so.
1293 if (CTy.isForwardDecl())
1294 addFlag(&Buffer, dwarf::DW_AT_declaration);
1296 // Add source line info if available.
1297 if (!CTy.isForwardDecl())
1298 addSourceLine(&Buffer, CTy);
1300 // No harm in adding the runtime language to the declaration.
1301 unsigned RLang = CTy.getRunTimeLang();
1303 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1308 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1309 /// DITemplateTypeParameter.
1310 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1311 DITemplateTypeParameter TP) {
1313 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1314 // Add the type if it exists, it could be void and therefore no type.
1316 addType(ParamDIE, resolve(TP.getType()));
1317 if (!TP.getName().empty())
1318 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1321 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1322 /// DITemplateValueParameter.
1324 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1325 DITemplateValueParameter VP) {
1326 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1328 // Add the type if there is one, template template and template parameter
1329 // packs will not have a type.
1330 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1331 addType(ParamDIE, resolve(VP.getType()));
1332 if (!VP.getName().empty())
1333 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1334 if (Value *Val = VP.getValue()) {
1335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1336 addConstantValue(ParamDIE, CI,
1337 isUnsignedDIType(DD, resolve(VP.getType())));
1338 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1339 // For declaration non-type template parameters (such as global values and
1341 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1342 addOpAddress(Loc, Asm->getSymbol(GV));
1343 // Emit DW_OP_stack_value to use the address as the immediate value of the
1344 // parameter, rather than a pointer to it.
1345 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1346 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1347 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1348 assert(isa<MDString>(Val));
1349 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1350 cast<MDString>(Val)->getString());
1351 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1352 assert(isa<MDNode>(Val));
1353 DIArray A(cast<MDNode>(Val));
1354 addTemplateParams(*ParamDIE, A);
1359 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1360 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1361 // Construct the context before querying for the existence of the DIE in case
1362 // such construction creates the DIE.
1363 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1365 DIE *NDie = getDIE(NS);
1368 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1370 if (!NS.getName().empty()) {
1371 addString(NDie, dwarf::DW_AT_name, NS.getName());
1372 addAccelNamespace(NS.getName(), NDie);
1373 addGlobalName(NS.getName(), NDie, NS.getContext());
1375 addAccelNamespace("(anonymous namespace)", NDie);
1376 addSourceLine(NDie, NS);
1380 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1381 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1382 // Construct the context before querying for the existence of the DIE in case
1383 // such construction creates the DIE (as is the case for member function
1385 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1387 DIE *SPDie = getDIE(SP);
1391 DISubprogram SPDecl = SP.getFunctionDeclaration();
1392 if (SPDecl.isSubprogram())
1393 // Add subprogram definitions to the CU die directly.
1394 ContextDIE = UnitDie.get();
1396 // DW_TAG_inlined_subroutine may refer to this DIE.
1397 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1399 DIE *DeclDie = NULL;
1400 if (SPDecl.isSubprogram())
1401 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1403 // Add function template parameters.
1404 addTemplateParams(*SPDie, SP.getTemplateParams());
1406 // If this DIE is going to refer declaration info using AT_specification
1407 // then there is no need to add other attributes.
1409 // Refer function declaration directly.
1410 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1415 // Add the linkage name if we have one.
1416 StringRef LinkageName = SP.getLinkageName();
1417 if (!LinkageName.empty())
1418 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1419 GlobalValue::getRealLinkageName(LinkageName));
1421 // Constructors and operators for anonymous aggregates do not have names.
1422 if (!SP.getName().empty())
1423 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1425 addSourceLine(SPDie, SP);
1427 // Add the prototype if we have a prototype and we have a C like
1429 uint16_t Language = getLanguage();
1430 if (SP.isPrototyped() &&
1431 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1432 Language == dwarf::DW_LANG_ObjC))
1433 addFlag(SPDie, dwarf::DW_AT_prototyped);
1435 DICompositeType SPTy = SP.getType();
1436 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1437 "the type of a subprogram should be a subroutine");
1439 DIArray Args = SPTy.getTypeArray();
1440 // Add a return type. If this is a type like a C/C++ void type we don't add a
1442 if (Args.getElement(0))
1443 addType(SPDie, DIType(Args.getElement(0)));
1445 unsigned VK = SP.getVirtuality();
1447 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1448 DIELoc *Block = getDIELoc();
1449 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1450 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1451 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1452 ContainingTypeMap.insert(
1453 std::make_pair(SPDie, resolve(SP.getContainingType())));
1456 if (!SP.isDefinition()) {
1457 addFlag(SPDie, dwarf::DW_AT_declaration);
1459 // Add arguments. Do not add arguments for subprogram definition. They will
1460 // be handled while processing variables.
1461 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1462 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1463 DIType ATy(Args.getElement(i));
1465 if (ATy.isArtificial())
1466 addFlag(Arg, dwarf::DW_AT_artificial);
1470 if (SP.isArtificial())
1471 addFlag(SPDie, dwarf::DW_AT_artificial);
1473 if (!SP.isLocalToUnit())
1474 addFlag(SPDie, dwarf::DW_AT_external);
1476 if (SP.isOptimized())
1477 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1479 if (unsigned isa = Asm->getISAEncoding()) {
1480 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1483 if (SP.isLValueReference())
1484 addFlag(SPDie, dwarf::DW_AT_reference);
1486 if (SP.isRValueReference())
1487 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1489 if (SP.isProtected())
1490 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1491 dwarf::DW_ACCESS_protected);
1492 else if (SP.isPrivate())
1493 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1494 dwarf::DW_ACCESS_private);
1496 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1497 dwarf::DW_ACCESS_public);
1499 if (SP.isExplicit())
1500 addFlag(SPDie, dwarf::DW_AT_explicit);
1505 // Return const expression if value is a GEP to access merged global
1507 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1508 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1509 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1510 if (!CE || CE->getNumOperands() != 3 ||
1511 CE->getOpcode() != Instruction::GetElementPtr)
1514 // First operand points to a global struct.
1515 Value *Ptr = CE->getOperand(0);
1516 if (!isa<GlobalValue>(Ptr) ||
1517 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1520 // Second operand is zero.
1521 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1522 if (!CI || !CI->isZero())
1525 // Third operand is offset.
1526 if (!isa<ConstantInt>(CE->getOperand(2)))
1532 /// createGlobalVariableDIE - create global variable DIE.
1533 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1534 // Check for pre-existence.
1538 assert(GV.isGlobalVariable());
1540 DIScope GVContext = GV.getContext();
1541 DIType GTy = GV.getType();
1543 // If this is a static data member definition, some attributes belong
1544 // to the declaration DIE.
1545 DIE *VariableDIE = NULL;
1546 bool IsStaticMember = false;
1547 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1548 if (SDMDecl.Verify()) {
1549 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1550 // We need the declaration DIE that is in the static member's class.
1551 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1552 IsStaticMember = true;
1555 // If this is not a static data member definition, create the variable
1556 // DIE and add the initial set of attributes to it.
1558 // Construct the context before querying for the existence of the DIE in
1559 // case such construction creates the DIE.
1560 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1563 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1565 // Add name and type.
1566 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1567 addType(VariableDIE, GTy);
1569 // Add scoping info.
1570 if (!GV.isLocalToUnit())
1571 addFlag(VariableDIE, dwarf::DW_AT_external);
1573 // Add line number info.
1574 addSourceLine(VariableDIE, GV);
1578 bool addToAccelTable = false;
1579 DIE *VariableSpecDIE = NULL;
1580 bool isGlobalVariable = GV.getGlobal() != NULL;
1581 if (isGlobalVariable) {
1582 addToAccelTable = true;
1583 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1584 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1585 if (GV.getGlobal()->isThreadLocal()) {
1586 // FIXME: Make this work with -gsplit-dwarf.
1587 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1588 assert((PointerSize == 4 || PointerSize == 8) &&
1589 "Add support for other sizes if necessary");
1590 // Based on GCC's support for TLS:
1591 if (!DD->useSplitDwarf()) {
1592 // 1) Start with a constNu of the appropriate pointer size
1593 addUInt(Loc, dwarf::DW_FORM_data1,
1594 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1595 // 2) containing the (relocated) offset of the TLS variable
1596 // within the module's TLS block.
1597 addExpr(Loc, dwarf::DW_FORM_udata,
1598 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1600 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1601 addUInt(Loc, dwarf::DW_FORM_udata,
1602 DU->getAddrPoolIndex(Sym, /* TLS */ true));
1604 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1605 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1607 DD->addArangeLabel(SymbolCU(this, Sym));
1608 addOpAddress(Loc, Sym);
1610 // Do not create specification DIE if context is either compile unit
1612 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1613 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1614 // Create specification DIE.
1615 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1616 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1617 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc);
1618 // A static member's declaration is already flagged as such.
1619 if (!SDMDecl.Verify())
1620 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1622 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1624 // Add the linkage name.
1625 StringRef LinkageName = GV.getLinkageName();
1626 if (!LinkageName.empty())
1627 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1628 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1630 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1632 dwarf::DW_AT_MIPS_linkage_name,
1633 GlobalValue::getRealLinkageName(LinkageName));
1634 } else if (const ConstantInt *CI =
1635 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1636 // AT_const_value was added when the static member was created. To avoid
1637 // emitting AT_const_value multiple times, we only add AT_const_value when
1638 // it is not a static member.
1639 if (!IsStaticMember)
1640 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1641 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1642 addToAccelTable = true;
1643 // GV is a merged global.
1644 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1645 Value *Ptr = CE->getOperand(0);
1646 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1647 DD->addArangeLabel(SymbolCU(this, Sym));
1648 addOpAddress(Loc, Sym);
1649 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1650 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1651 addUInt(Loc, dwarf::DW_FORM_udata,
1652 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1653 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1654 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1657 if (addToAccelTable) {
1658 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1659 addAccelName(GV.getName(), AddrDIE);
1661 // If the linkage name is different than the name, go ahead and output
1662 // that as well into the name table.
1663 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1664 addAccelName(GV.getLinkageName(), AddrDIE);
1667 if (!GV.isLocalToUnit())
1668 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1672 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1673 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1674 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1675 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1677 // The LowerBound value defines the lower bounds which is typically zero for
1678 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1679 // Count == -1 then the array is unbounded and we do not emit
1680 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1681 // Count == 0, then the array has zero elements in which case we do not emit
1683 int64_t LowerBound = SR.getLo();
1684 int64_t DefaultLowerBound = getDefaultLowerBound();
1685 int64_t Count = SR.getCount();
1687 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1688 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1690 if (Count != -1 && Count != 0)
1691 // FIXME: An unbounded array should reference the expression that defines
1693 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1694 LowerBound + Count - 1);
1697 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1698 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1700 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1702 // Emit the element type.
1703 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1705 // Get an anonymous type for index type.
1706 // FIXME: This type should be passed down from the front end
1707 // as different languages may have different sizes for indexes.
1708 DIE *IdxTy = getIndexTyDie();
1710 // Construct an anonymous type for index type.
1711 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1712 addString(IdxTy, dwarf::DW_AT_name, "int");
1713 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1714 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1715 dwarf::DW_ATE_signed);
1716 setIndexTyDie(IdxTy);
1719 // Add subranges to array type.
1720 DIArray Elements = CTy.getTypeArray();
1721 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1722 DIDescriptor Element = Elements.getElement(i);
1723 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1724 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1728 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1729 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1730 DIArray Elements = CTy.getTypeArray();
1732 // Add enumerators to enumeration type.
1733 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1734 DIEnumerator Enum(Elements.getElement(i));
1735 if (Enum.isEnumerator()) {
1736 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1737 StringRef Name = Enum.getName();
1738 addString(Enumerator, dwarf::DW_AT_name, Name);
1739 int64_t Value = Enum.getEnumValue();
1740 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1744 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1746 addType(&Buffer, DTy);
1747 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1751 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1753 void DwarfUnit::constructContainingTypeDIEs() {
1754 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1755 CE = ContainingTypeMap.end();
1757 DIE *SPDie = CI->first;
1758 DIDescriptor D(CI->second);
1761 DIE *NDie = getDIE(D);
1764 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1768 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1769 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1770 StringRef Name = DV.getName();
1772 // Define variable debug information entry.
1773 DIE *VariableDie = new DIE(DV.getTag());
1774 DbgVariable *AbsVar = DV.getAbstractVariable();
1775 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1777 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1780 addString(VariableDie, dwarf::DW_AT_name, Name);
1781 addSourceLine(VariableDie, DV.getVariable());
1782 addType(VariableDie, DV.getType());
1785 if (DV.isArtificial())
1786 addFlag(VariableDie, dwarf::DW_AT_artificial);
1788 if (isScopeAbstract) {
1789 DV.setDIE(VariableDie);
1793 // Add variable address.
1795 unsigned Offset = DV.getDotDebugLocOffset();
1796 if (Offset != ~0U) {
1797 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1798 Asm->GetTempSymbol("debug_loc", Offset));
1799 DV.setDIE(VariableDie);
1803 // Check if variable is described by a DBG_VALUE instruction.
1804 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1805 assert(DVInsn->getNumOperands() == 3);
1806 if (DVInsn->getOperand(0).isReg()) {
1807 const MachineOperand RegOp = DVInsn->getOperand(0);
1808 // If the second operand is an immediate, this is an indirect value.
1809 if (DVInsn->getOperand(1).isImm()) {
1810 MachineLocation Location(RegOp.getReg(),
1811 DVInsn->getOperand(1).getImm());
1812 addVariableAddress(DV, VariableDie, Location);
1813 } else if (RegOp.getReg())
1814 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1815 } else if (DVInsn->getOperand(0).isImm())
1816 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1817 else if (DVInsn->getOperand(0).isFPImm())
1818 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1819 else if (DVInsn->getOperand(0).isCImm())
1820 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1821 isUnsignedDIType(DD, DV.getType()));
1823 DV.setDIE(VariableDie);
1826 // .. else use frame index.
1827 int FI = DV.getFrameIndex();
1829 unsigned FrameReg = 0;
1830 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1831 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1832 MachineLocation Location(FrameReg, Offset);
1833 addVariableAddress(DV, VariableDie, Location);
1837 DV.setDIE(VariableDie);
1841 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1842 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1843 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1844 StringRef Name = DT.getName();
1846 addString(MemberDie, dwarf::DW_AT_name, Name);
1848 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1850 addSourceLine(MemberDie, DT);
1852 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1854 // For C++, virtual base classes are not at fixed offset. Use following
1855 // expression to extract appropriate offset from vtable.
1856 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1858 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1859 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1860 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1861 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1862 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1863 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1864 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1865 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1867 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1869 uint64_t Size = DT.getSizeInBits();
1870 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1871 uint64_t OffsetInBytes;
1873 if (Size != FieldSize) {
1875 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1876 getBaseTypeSize(DD, DT) >> 3);
1877 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1879 uint64_t Offset = DT.getOffsetInBits();
1880 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1881 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1882 uint64_t FieldOffset = (HiMark - FieldSize);
1883 Offset -= FieldOffset;
1885 // Maybe we need to work from the other end.
1886 if (Asm->getDataLayout().isLittleEndian())
1887 Offset = FieldSize - (Offset + Size);
1888 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1890 // Here DW_AT_data_member_location points to the anonymous
1891 // field that includes this bit field.
1892 OffsetInBytes = FieldOffset >> 3;
1894 // This is not a bitfield.
1895 OffsetInBytes = DT.getOffsetInBits() >> 3;
1897 if (DD->getDwarfVersion() <= 2) {
1898 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1899 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1900 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1901 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1903 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1907 if (DT.isProtected())
1908 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1909 dwarf::DW_ACCESS_protected);
1910 else if (DT.isPrivate())
1911 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1912 dwarf::DW_ACCESS_private);
1913 // Otherwise C++ member and base classes are considered public.
1915 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1916 dwarf::DW_ACCESS_public);
1918 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1919 dwarf::DW_VIRTUALITY_virtual);
1921 // Objective-C properties.
1922 if (MDNode *PNode = DT.getObjCProperty())
1923 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1924 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1927 if (DT.isArtificial())
1928 addFlag(MemberDie, dwarf::DW_AT_artificial);
1931 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1932 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1936 // Construct the context before querying for the existence of the DIE in case
1937 // such construction creates the DIE.
1938 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1939 assert(dwarf::isType(ContextDIE->getTag()) &&
1940 "Static member should belong to a type.");
1942 DIE *StaticMemberDIE = getDIE(DT);
1943 if (StaticMemberDIE)
1944 return StaticMemberDIE;
1946 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1948 DIType Ty = resolve(DT.getTypeDerivedFrom());
1950 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1951 addType(StaticMemberDIE, Ty);
1952 addSourceLine(StaticMemberDIE, DT);
1953 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1954 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1956 // FIXME: We could omit private if the parent is a class_type, and
1957 // public if the parent is something else.
1958 if (DT.isProtected())
1959 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1960 dwarf::DW_ACCESS_protected);
1961 else if (DT.isPrivate())
1962 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1963 dwarf::DW_ACCESS_private);
1965 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1966 dwarf::DW_ACCESS_public);
1968 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1969 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1970 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1971 addConstantFPValue(StaticMemberDIE, CFP);
1973 return StaticMemberDIE;
1976 void DwarfUnit::emitHeader(const MCSection *ASection,
1977 const MCSymbol *ASectionSym) const {
1978 Asm->OutStreamer.AddComment("DWARF version number");
1979 Asm->EmitInt16(DD->getDwarfVersion());
1980 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1981 // We share one abbreviations table across all units so it's always at the
1982 // start of the section. Use a relocatable offset where needed to ensure
1983 // linking doesn't invalidate that offset.
1984 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1985 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1986 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1989 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
1990 // Define start line table label for each Compile Unit.
1991 MCSymbol *LineTableStartSym =
1992 Asm->GetTempSymbol("line_table_start", getUniqueID());
1993 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
1996 // Use a single line table if we are generating assembly.
1997 bool UseTheFirstCU =
1998 Asm->OutStreamer.hasRawTextSupport() || (getUniqueID() == 0);
2000 stmtListIndex = UnitDie->getValues().size();
2002 // DW_AT_stmt_list is a offset of line number information for this
2003 // compile unit in debug_line section. For split dwarf this is
2004 // left in the skeleton CU and so not included.
2005 // The line table entries are not always emitted in assembly, so it
2006 // is not okay to use line_table_start here.
2007 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2008 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list,
2009 UseTheFirstCU ? DwarfLineSectionSym : LineTableStartSym);
2010 else if (UseTheFirstCU)
2011 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
2013 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2014 DwarfLineSectionSym);
2017 void DwarfCompileUnit::applyStmtList(DIE &D) {
2018 D.addValue(dwarf::DW_AT_stmt_list,
2019 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2020 UnitDie->getValues()[stmtListIndex]);
2023 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2024 const MCSymbol *ASectionSym) const {
2025 DwarfUnit::emitHeader(ASection, ASectionSym);
2026 Asm->OutStreamer.AddComment("Type Signature");
2027 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2028 Asm->OutStreamer.AddComment("Type DIE Offset");
2029 // In a skeleton type unit there is no type DIE so emit a zero offset.
2030 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2031 sizeof(Ty->getOffset()));
2034 void DwarfTypeUnit::initSection(const MCSection *Section) {
2035 assert(!this->Section);
2036 this->Section = Section;
2037 // Since each type unit is contained in its own COMDAT section, the begin
2038 // label and the section label are the same. Using the begin label emission in
2039 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2040 // the only other alternative of lazily constructing start-of-section labels
2041 // and storing a mapping in DwarfDebug (or AsmPrinter).
2042 this->SectionSym = this->LabelBegin =
2043 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2045 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2046 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());