1 //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Unit ------------===//
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 "DwarfCompileUnit.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/MC/MCSection.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Target/Mangler.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
35 /// CompileUnit - Compile unit constructor.
36 CompileUnit::CompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
37 AsmPrinter *A, DwarfDebug *DW, DwarfUnits *DWU)
38 : UniqueID(UID), Node(Node), CUDie(D), Asm(A), DD(DW), DU(DWU),
39 IndexTyDie(0), DebugInfoOffset(0) {
40 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
44 /// ~CompileUnit - Destructor for compile unit.
45 CompileUnit::~CompileUnit() {
46 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
47 DIEBlocks[j]->~DIEBlock();
50 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
51 /// information entry.
52 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
53 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
57 /// getDefaultLowerBound - Return the default lower bound for an array. If the
58 /// DWARF version doesn't handle the language, return -1.
59 int64_t CompileUnit::getDefaultLowerBound() const {
60 switch (getLanguage()) {
64 case dwarf::DW_LANG_C89:
65 case dwarf::DW_LANG_C99:
66 case dwarf::DW_LANG_C:
67 case dwarf::DW_LANG_C_plus_plus:
68 case dwarf::DW_LANG_ObjC:
69 case dwarf::DW_LANG_ObjC_plus_plus:
72 case dwarf::DW_LANG_Fortran77:
73 case dwarf::DW_LANG_Fortran90:
74 case dwarf::DW_LANG_Fortran95:
77 // The languages below have valid values only if the DWARF version >= 4.
78 case dwarf::DW_LANG_Java:
79 case dwarf::DW_LANG_Python:
80 case dwarf::DW_LANG_UPC:
81 case dwarf::DW_LANG_D:
82 if (dwarf::DWARF_VERSION >= 4)
86 case dwarf::DW_LANG_Ada83:
87 case dwarf::DW_LANG_Ada95:
88 case dwarf::DW_LANG_Cobol74:
89 case dwarf::DW_LANG_Cobol85:
90 case dwarf::DW_LANG_Modula2:
91 case dwarf::DW_LANG_Pascal83:
92 case dwarf::DW_LANG_PLI:
93 if (dwarf::DWARF_VERSION >= 4)
101 /// Check whether the DIE for this MDNode can be shared across CUs.
102 static bool isShareableAcrossCUs(DIDescriptor D) {
103 // When the MDNode can be part of the type system, the DIE can be
104 // shared across CUs.
106 (D.isSubprogram() && !DISubprogram(D).isDefinition());
109 /// getDIE - Returns the debug information entry map slot for the
110 /// specified debug variable. We delegate the request to DwarfDebug
111 /// when the DIE for this MDNode can be shared across CUs. The mappings
112 /// will be kept in DwarfDebug for shareable DIEs.
113 DIE *CompileUnit::getDIE(DIDescriptor D) const {
114 if (isShareableAcrossCUs(D))
115 return DD->getDIE(D);
116 return MDNodeToDieMap.lookup(D);
119 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
120 /// when the DIE for this MDNode can be shared across CUs. The mappings
121 /// will be kept in DwarfDebug for shareable DIEs.
122 void CompileUnit::insertDIE(DIDescriptor Desc, DIE *D) {
123 if (isShareableAcrossCUs(Desc)) {
124 DD->insertDIE(Desc, D);
127 MDNodeToDieMap.insert(std::make_pair(Desc, D));
130 /// addFlag - Add a flag that is true.
131 void CompileUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
132 if (DD->getDwarfVersion() >= 4)
133 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
135 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
138 /// addUInt - Add an unsigned integer attribute data and value.
140 void CompileUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
141 Optional<dwarf::Form> Form, uint64_t Integer) {
143 Form = DIEInteger::BestForm(false, Integer);
144 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
146 Die->addValue(Attribute, *Form, Value);
149 void CompileUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
150 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
153 /// addSInt - Add an signed integer attribute data and value.
155 void CompileUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
156 Optional<dwarf::Form> Form, int64_t Integer) {
158 Form = DIEInteger::BestForm(true, Integer);
159 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
160 Die->addValue(Attribute, *Form, Value);
163 void CompileUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
165 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
168 /// addString - Add a string attribute data and value. We always emit a
169 /// reference to the string pool instead of immediate strings so that DIEs have
170 /// more predictable sizes. In the case of split dwarf we emit an index
171 /// into another table which gets us the static offset into the string
173 void CompileUnit::addString(DIE *Die, dwarf::Attribute Attribute,
177 if (!DD->useSplitDwarf()) {
178 MCSymbol *Symb = DU->getStringPoolEntry(String);
179 if (Asm->needsRelocationsForDwarfStringPool())
180 Value = new (DIEValueAllocator) DIELabel(Symb);
182 MCSymbol *StringPool = DU->getStringPoolSym();
183 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
185 Form = dwarf::DW_FORM_strp;
187 unsigned idx = DU->getStringPoolIndex(String);
188 Value = new (DIEValueAllocator) DIEInteger(idx);
189 Form = dwarf::DW_FORM_GNU_str_index;
191 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
192 Die->addValue(Attribute, Form, Str);
195 /// addLocalString - Add a string attribute data and value. This is guaranteed
196 /// to be in the local string pool instead of indirected.
197 void CompileUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
199 MCSymbol *Symb = DU->getStringPoolEntry(String);
201 if (Asm->needsRelocationsForDwarfStringPool())
202 Value = new (DIEValueAllocator) DIELabel(Symb);
204 MCSymbol *StringPool = DU->getStringPoolSym();
205 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
207 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
210 /// addExpr - Add a Dwarf expression attribute data and value.
212 void CompileUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
213 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
214 Die->addValue((dwarf::Attribute)0, Form, Value);
217 /// addLabel - Add a Dwarf label attribute data and value.
219 void CompileUnit::addLabel(DIE *Die, dwarf::Attribute Attribute,
220 dwarf::Form Form, const MCSymbol *Label) {
221 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
222 Die->addValue(Attribute, Form, Value);
225 void CompileUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
226 const MCSymbol *Label) {
227 addLabel(Die, (dwarf::Attribute)0, Form, Label);
230 /// addSectionLabel - Add a Dwarf section label attribute data and value.
232 void CompileUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
233 const MCSymbol *Label) {
234 if (DD->getDwarfVersion() >= 4)
235 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
237 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
240 /// addSectionOffset - Add an offset into a section attribute data and value.
242 void CompileUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
244 if (DD->getDwarfVersion() >= 4)
245 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
247 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
250 /// addLabelAddress - Add a dwarf label attribute data and value using
251 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
253 void CompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
256 DD->addArangeLabel(SymbolCU(this, Label));
258 if (!DD->useSplitDwarf()) {
260 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
261 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
263 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
264 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
267 unsigned idx = DU->getAddrPoolIndex(Label);
268 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
269 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
273 /// addOpAddress - Add a dwarf op address data and value using the
274 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
276 void CompileUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
277 DD->addArangeLabel(SymbolCU(this, Sym));
278 if (!DD->useSplitDwarf()) {
279 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
280 addLabel(Die, dwarf::DW_FORM_udata, Sym);
282 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
283 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
287 /// addSectionDelta - Add a section label delta attribute data and value.
289 void CompileUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
290 const MCSymbol *Hi, const MCSymbol *Lo) {
291 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
292 if (DD->getDwarfVersion() >= 4)
293 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
295 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
298 /// addDIEEntry - Add a DIE attribute data and value.
300 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
302 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
305 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
307 const DIE *DieCU = Die->getCompileUnitOrNull();
308 const DIE *EntryCU = Entry->getEntry()->getCompileUnitOrNull();
310 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
313 EntryCU = getCUDie();
314 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
315 : dwarf::DW_FORM_ref_addr,
319 /// Create a DIE with the given Tag, add the DIE to its parent, and
320 /// call insertDIE if MD is not null.
321 DIE *CompileUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
322 DIE *Die = new DIE(Tag);
323 Parent.addChild(Die);
329 /// addBlock - Add block data.
331 void CompileUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
333 Block->ComputeSize(Asm);
334 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
335 Die->addValue(Attribute, Block->BestForm(), Block);
338 /// addSourceLine - Add location information to specified debug information
340 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
345 unsigned Line = V.getLineNumber();
349 DD->getOrCreateSourceID(V.getContext().getFilename(),
350 V.getContext().getDirectory(), getUniqueID());
351 assert(FileID && "Invalid file id");
352 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
353 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
356 /// addSourceLine - Add location information to specified debug information
358 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
359 // Verify global variable.
360 if (!G.isGlobalVariable())
363 unsigned Line = G.getLineNumber();
367 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
368 assert(FileID && "Invalid file id");
369 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
370 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
373 /// addSourceLine - Add location information to specified debug information
375 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
376 // Verify subprogram.
377 if (!SP.isSubprogram())
380 // If the line number is 0, don't add it.
381 unsigned Line = SP.getLineNumber();
385 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
387 assert(FileID && "Invalid file id");
388 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
389 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
392 /// addSourceLine - Add location information to specified debug information
394 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
399 unsigned Line = Ty.getLineNumber();
402 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
404 assert(FileID && "Invalid file id");
405 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
406 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
409 /// addSourceLine - Add location information to specified debug information
411 void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
413 if (!Ty.isObjCProperty())
416 unsigned Line = Ty.getLineNumber();
419 DIFile File = Ty.getFile();
420 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
421 File.getDirectory(), getUniqueID());
422 assert(FileID && "Invalid file id");
423 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
424 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
427 /// addSourceLine - Add location information to specified debug information
429 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
434 unsigned Line = NS.getLineNumber();
437 StringRef FN = NS.getFilename();
440 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
441 assert(FileID && "Invalid file id");
442 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
443 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
446 /// addVariableAddress - Add DW_AT_location attribute for a
447 /// DbgVariable based on provided MachineLocation.
448 void CompileUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
449 MachineLocation Location) {
450 if (DV.variableHasComplexAddress())
451 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
452 else if (DV.isBlockByrefVariable())
453 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
455 addAddress(Die, dwarf::DW_AT_location, Location,
456 DV.getVariable().isIndirect());
459 /// addRegisterOp - Add register operand.
460 void CompileUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
461 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
462 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
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);
471 /// addRegisterOffset - Add register offset.
472 void CompileUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
474 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
475 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
476 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
477 if (Reg == TRI->getFrameRegister(*Asm->MF))
478 // If variable offset is based in frame register then use fbreg.
479 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
481 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
483 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
484 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
486 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
489 /// addAddress - Add an address attribute to a die based on the location
491 void CompileUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
492 const MachineLocation &Location, bool Indirect) {
493 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
495 if (Location.isReg() && !Indirect)
496 addRegisterOp(Block, Location.getReg());
498 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
499 if (Indirect && !Location.isReg()) {
500 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
504 // Now attach the location information to the DIE.
505 addBlock(Die, Attribute, Block);
508 /// addComplexAddress - Start with the address based on the location provided,
509 /// and generate the DWARF information necessary to find the actual variable
510 /// given the extra address information encoded in the DIVariable, starting from
511 /// the starting location. Add the DWARF information to the die.
513 void CompileUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
514 dwarf::Attribute Attribute,
515 const MachineLocation &Location) {
516 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
517 unsigned N = DV.getNumAddrElements();
519 if (Location.isReg()) {
520 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
521 // If first address element is OpPlus then emit
522 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
523 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
526 addRegisterOp(Block, Location.getReg());
528 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
531 uint64_t Element = DV.getAddrElement(i);
532 if (Element == DIBuilder::OpPlus) {
533 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
534 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
535 } else if (Element == DIBuilder::OpDeref) {
536 if (!Location.isReg())
537 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
539 llvm_unreachable("unknown DIBuilder Opcode");
542 // Now attach the location information to the DIE.
543 addBlock(Die, Attribute, Block);
546 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
547 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
548 gives the variable VarName either the struct, or a pointer to the struct, as
549 its type. This is necessary for various behind-the-scenes things the
550 compiler needs to do with by-reference variables in Blocks.
552 However, as far as the original *programmer* is concerned, the variable
553 should still have type 'SomeType', as originally declared.
555 The function getBlockByrefType dives into the __Block_byref_x_VarName
556 struct to find the original type of the variable, which is then assigned to
557 the variable's Debug Information Entry as its real type. So far, so good.
558 However now the debugger will expect the variable VarName to have the type
559 SomeType. So we need the location attribute for the variable to be an
560 expression that explains to the debugger how to navigate through the
561 pointers and struct to find the actual variable of type SomeType.
563 The following function does just that. We start by getting
564 the "normal" location for the variable. This will be the location
565 of either the struct __Block_byref_x_VarName or the pointer to the
566 struct __Block_byref_x_VarName.
568 The struct will look something like:
570 struct __Block_byref_x_VarName {
572 struct __Block_byref_x_VarName *forwarding;
573 ... <various other fields>
575 ... <maybe more fields>
578 If we are given the struct directly (as our starting point) we
579 need to tell the debugger to:
581 1). Add the offset of the forwarding field.
583 2). Follow that pointer to get the real __Block_byref_x_VarName
584 struct to use (the real one may have been copied onto the heap).
586 3). Add the offset for the field VarName, to find the actual variable.
588 If we started with a pointer to the struct, then we need to
589 dereference that pointer first, before the other steps.
590 Translating this into DWARF ops, we will need to append the following
591 to the current location description for the variable:
593 DW_OP_deref -- optional, if we start with a pointer
594 DW_OP_plus_uconst <forward_fld_offset>
596 DW_OP_plus_uconst <varName_fld_offset>
598 That is what this function does. */
600 /// addBlockByrefAddress - Start with the address based on the location
601 /// provided, and generate the DWARF information necessary to find the
602 /// actual Block variable (navigating the Block struct) based on the
603 /// starting location. Add the DWARF information to the die. For
604 /// more information, read large comment just above here.
606 void CompileUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
607 dwarf::Attribute Attribute,
608 const MachineLocation &Location) {
609 DIType Ty = DV.getType();
611 uint16_t Tag = Ty.getTag();
612 bool isPointer = false;
614 StringRef varName = DV.getName();
616 if (Tag == dwarf::DW_TAG_pointer_type) {
617 DIDerivedType DTy(Ty);
618 TmpTy = resolve(DTy.getTypeDerivedFrom());
622 DICompositeType blockStruct(TmpTy);
624 // Find the __forwarding field and the variable field in the __Block_byref
626 DIArray Fields = blockStruct.getTypeArray();
627 DIDerivedType varField;
628 DIDerivedType forwardingField;
630 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
631 DIDerivedType DT(Fields.getElement(i));
632 StringRef fieldName = DT.getName();
633 if (fieldName == "__forwarding")
634 forwardingField = DT;
635 else if (fieldName == varName)
639 // Get the offsets for the forwarding field and the variable field.
640 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
641 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
643 // Decode the original location, and use that as the start of the byref
644 // variable's location.
645 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
647 if (Location.isReg())
648 addRegisterOp(Block, Location.getReg());
650 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
652 // If we started with a pointer to the __Block_byref... struct, then
653 // the first thing we need to do is dereference the pointer (DW_OP_deref).
655 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
657 // Next add the offset for the '__forwarding' field:
658 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
659 // adding the offset if it's 0.
660 if (forwardingFieldOffset > 0) {
661 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
662 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
665 // Now dereference the __forwarding field to get to the real __Block_byref
666 // struct: DW_OP_deref.
667 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
669 // Now that we've got the real __Block_byref... struct, add the offset
670 // for the variable's field to get to the location of the actual variable:
671 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
672 if (varFieldOffset > 0) {
673 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
674 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
677 // Now attach the location information to the DIE.
678 addBlock(Die, Attribute, Block);
681 /// isTypeSigned - Return true if the type is signed.
682 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
683 if (Ty.isDerivedType())
684 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
686 if (Ty.isBasicType())
687 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
688 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
689 *SizeInBits = Ty.getSizeInBits();
695 /// Return true if type encoding is unsigned.
696 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
697 DIDerivedType DTy(Ty);
698 if (DTy.isDerivedType())
699 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
702 if (BTy.isBasicType()) {
703 unsigned Encoding = BTy.getEncoding();
704 if (Encoding == dwarf::DW_ATE_unsigned ||
705 Encoding == dwarf::DW_ATE_unsigned_char ||
706 Encoding == dwarf::DW_ATE_boolean)
712 /// If this type is derived from a base type then return base type size.
713 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
714 unsigned Tag = Ty.getTag();
716 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
717 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
718 Tag != dwarf::DW_TAG_restrict_type)
719 return Ty.getSizeInBits();
721 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
723 // If this type is not derived from any type then take conservative approach.
724 if (!BaseType.isValid())
725 return Ty.getSizeInBits();
727 // If this is a derived type, go ahead and get the base type, unless it's a
728 // reference then it's just the size of the field. Pointer types have no need
729 // of this since they're a different type of qualification on the type.
730 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
731 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
732 return Ty.getSizeInBits();
734 if (BaseType.isDerivedType())
735 return getBaseTypeSize(DD, DIDerivedType(BaseType));
737 return BaseType.getSizeInBits();
740 /// addConstantValue - Add constant value entry in variable DIE.
741 void CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
743 // FIXME: This is a bit conservative/simple - it emits negative values at
744 // their maximum bit width which is a bit unfortunate (& doesn't prefer
745 // udata/sdata over dataN as suggested by the DWARF spec)
746 assert(MO.isImm() && "Invalid machine operand!");
748 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
751 // If we're a signed constant definitely use sdata.
752 if (SignedConstant) {
753 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
757 // Else use data for now unless it's larger than we can deal with.
758 switch (SizeInBits) {
760 Form = dwarf::DW_FORM_data1;
763 Form = dwarf::DW_FORM_data2;
766 Form = dwarf::DW_FORM_data4;
769 Form = dwarf::DW_FORM_data8;
772 Form = dwarf::DW_FORM_udata;
773 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
776 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
779 /// addConstantFPValue - Add constant value entry in variable DIE.
780 void CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
781 assert(MO.isFPImm() && "Invalid machine operand!");
782 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
783 APFloat FPImm = MO.getFPImm()->getValueAPF();
785 // Get the raw data form of the floating point.
786 const APInt FltVal = FPImm.bitcastToAPInt();
787 const char *FltPtr = (const char *)FltVal.getRawData();
789 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
790 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
791 int Incr = (LittleEndian ? 1 : -1);
792 int Start = (LittleEndian ? 0 : NumBytes - 1);
793 int Stop = (LittleEndian ? NumBytes : -1);
795 // Output the constant to DWARF one byte at a time.
796 for (; Start != Stop; Start += Incr)
797 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
799 addBlock(Die, dwarf::DW_AT_const_value, Block);
802 /// addConstantFPValue - Add constant value entry in variable DIE.
803 void CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
804 // Pass this down to addConstantValue as an unsigned bag of bits.
805 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
808 /// addConstantValue - Add constant value entry in variable DIE.
809 void CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
811 addConstantValue(Die, CI->getValue(), Unsigned);
814 // addConstantValue - Add constant value entry in variable DIE.
815 void CompileUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
816 unsigned CIBitWidth = Val.getBitWidth();
817 if (CIBitWidth <= 64) {
818 // If we're a signed constant definitely use sdata.
820 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
825 // Else use data for now unless it's larger than we can deal with.
827 switch (CIBitWidth) {
829 Form = dwarf::DW_FORM_data1;
832 Form = dwarf::DW_FORM_data2;
835 Form = dwarf::DW_FORM_data4;
838 Form = dwarf::DW_FORM_data8;
841 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
845 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
849 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
851 // Get the raw data form of the large APInt.
852 const uint64_t *Ptr64 = Val.getRawData();
854 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
855 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
857 // Output the constant to DWARF one byte at a time.
858 for (int i = 0; i < NumBytes; i++) {
861 c = Ptr64[i / 8] >> (8 * (i & 7));
863 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
864 addUInt(Block, dwarf::DW_FORM_data1, c);
867 addBlock(Die, dwarf::DW_AT_const_value, Block);
870 /// addTemplateParams - Add template parameters into buffer.
871 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
872 // Add template parameters.
873 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
874 DIDescriptor Element = TParams.getElement(i);
875 if (Element.isTemplateTypeParameter())
876 constructTemplateTypeParameterDIE(Buffer,
877 DITemplateTypeParameter(Element));
878 else if (Element.isTemplateValueParameter())
879 constructTemplateValueParameterDIE(Buffer,
880 DITemplateValueParameter(Element));
884 /// getOrCreateContextDIE - Get context owner's DIE.
885 DIE *CompileUnit::getOrCreateContextDIE(DIScope Context) {
886 if (!Context || Context.isFile())
888 if (Context.isType())
889 return getOrCreateTypeDIE(DIType(Context));
890 if (Context.isNameSpace())
891 return getOrCreateNameSpace(DINameSpace(Context));
892 if (Context.isSubprogram())
893 return getOrCreateSubprogramDIE(DISubprogram(Context));
894 return getDIE(Context);
897 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
899 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
906 // Construct the context before querying for the existence of the DIE in case
907 // such construction creates the DIE.
908 DIE *ContextDIE = getOrCreateContextDIE(resolve(Ty.getContext()));
911 DIE *TyDIE = getDIE(Ty);
916 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
918 if (Ty.isBasicType())
919 constructTypeDIE(*TyDIE, DIBasicType(Ty));
920 else if (Ty.isCompositeType())
921 constructTypeDIE(*TyDIE, DICompositeType(Ty));
923 assert(Ty.isDerivedType() && "Unknown kind of DIType");
924 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
926 // If this is a named finished type then include it in the list of types
927 // for the accelerator tables.
928 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
929 bool IsImplementation = 0;
930 if (Ty.isCompositeType()) {
931 DICompositeType CT(Ty);
932 // A runtime language of 0 actually means C/C++ and that any
933 // non-negative value is some version of Objective-C/C++.
934 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
936 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
937 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
943 /// addType - Add a new type attribute to the specified entity.
944 void CompileUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
945 assert(Ty && "Trying to add a type that doesn't exist?");
947 // Check for pre-existence.
948 DIEEntry *Entry = getDIEEntry(Ty);
949 // If it exists then use the existing value.
951 addDIEEntry(Entity, Attribute, Entry);
956 DIE *Buffer = getOrCreateTypeDIE(Ty);
959 Entry = createDIEEntry(Buffer);
960 insertDIEEntry(Ty, Entry);
961 addDIEEntry(Entity, Attribute, Entry);
963 // If this is a complete composite type then include it in the
964 // list of global types.
968 // Accelerator table mutators - add each name along with its companion
969 // DIE to the proper table while ensuring that the name that we're going
970 // to reference is in the string table. We do this since the names we
971 // add may not only be identical to the names in the DIE.
972 void CompileUnit::addAccelName(StringRef Name, DIE *Die) {
973 DU->getStringPoolEntry(Name);
974 std::vector<DIE *> &DIEs = AccelNames[Name];
978 void CompileUnit::addAccelObjC(StringRef Name, DIE *Die) {
979 DU->getStringPoolEntry(Name);
980 std::vector<DIE *> &DIEs = AccelObjC[Name];
984 void CompileUnit::addAccelNamespace(StringRef Name, DIE *Die) {
985 DU->getStringPoolEntry(Name);
986 std::vector<DIE *> &DIEs = AccelNamespace[Name];
990 void CompileUnit::addAccelType(StringRef Name, std::pair<DIE *, unsigned> Die) {
991 DU->getStringPoolEntry(Name);
992 std::vector<std::pair<DIE *, unsigned> > &DIEs = AccelTypes[Name];
996 /// addGlobalName - Add a new global name to the compile unit.
997 void CompileUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
998 std::string FullName = getParentContextString(Context) + Name.str();
999 GlobalNames[FullName] = Die;
1002 /// addGlobalType - Add a new global type to the compile unit.
1004 void CompileUnit::addGlobalType(DIType Ty) {
1005 DIScope Context = resolve(Ty.getContext());
1006 if (!Ty.getName().empty() && !Ty.isForwardDecl() &&
1007 (!Context || Context.isCompileUnit() || Context.isFile() ||
1008 Context.isNameSpace()))
1009 if (DIEEntry *Entry = getDIEEntry(Ty)) {
1010 std::string FullName =
1011 getParentContextString(Context) + Ty.getName().str();
1012 GlobalTypes[FullName] = Entry->getEntry();
1016 /// getParentContextString - Walks the metadata parent chain in a language
1017 /// specific manner (using the compile unit language) and returns
1018 /// it as a string. This is done at the metadata level because DIEs may
1019 /// not currently have been added to the parent context and walking the
1020 /// DIEs looking for names is more expensive than walking the metadata.
1021 std::string CompileUnit::getParentContextString(DIScope Context) const {
1025 // FIXME: Decide whether to implement this for non-C++ languages.
1026 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1030 SmallVector<DIScope, 1> Parents;
1031 while (!Context.isCompileUnit()) {
1032 Parents.push_back(Context);
1033 if (Context.getContext())
1034 Context = resolve(Context.getContext());
1036 // Structure, etc types will have a NULL context if they're at the top
1041 // Reverse iterate over our list to go from the outermost construct to the
1043 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1047 StringRef Name = Ctx.getName();
1048 if (!Name.empty()) {
1056 /// addPubTypes - Add subprogram argument types for pubtypes section.
1057 void CompileUnit::addPubTypes(DISubprogram SP) {
1058 DICompositeType SPTy = SP.getType();
1059 uint16_t SPTag = SPTy.getTag();
1060 if (SPTag != dwarf::DW_TAG_subroutine_type)
1063 DIArray Args = SPTy.getTypeArray();
1064 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1065 DIType ATy(Args.getElement(i));
1072 /// constructTypeDIE - Construct basic type die from DIBasicType.
1073 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1074 // Get core information.
1075 StringRef Name = BTy.getName();
1076 // Add name if not anonymous or intermediate type.
1078 addString(&Buffer, dwarf::DW_AT_name, Name);
1080 // An unspecified type only has a name attribute.
1081 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1084 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1087 uint64_t Size = BTy.getSizeInBits() >> 3;
1088 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1091 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1092 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1093 // Get core information.
1094 StringRef Name = DTy.getName();
1095 uint64_t Size = DTy.getSizeInBits() >> 3;
1096 uint16_t Tag = Buffer.getTag();
1098 // Map to main type, void will not have a type.
1099 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1101 addType(&Buffer, FromTy);
1103 // Add name if not anonymous or intermediate type.
1105 addString(&Buffer, dwarf::DW_AT_name, Name);
1107 // Add size if non-zero (derived types might be zero-sized.)
1108 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1109 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1111 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1112 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1113 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1114 // Add source line info if available and TyDesc is not a forward declaration.
1115 if (!DTy.isForwardDecl())
1116 addSourceLine(&Buffer, DTy);
1119 /// Return true if the type is appropriately scoped to be contained inside
1120 /// its own type unit.
1121 static bool isTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
1122 DIScope Parent = DD->resolve(Ty.getContext());
1124 // Don't generate a hash for anything scoped inside a function.
1125 if (Parent.isSubprogram())
1127 Parent = DD->resolve(Parent.getContext());
1132 /// Return true if the type should be split out into a type unit.
1133 static bool shouldCreateTypeUnit(DICompositeType CTy, const DwarfDebug *DD) {
1134 uint16_t Tag = CTy.getTag();
1137 case dwarf::DW_TAG_structure_type:
1138 case dwarf::DW_TAG_union_type:
1139 case dwarf::DW_TAG_enumeration_type:
1140 case dwarf::DW_TAG_class_type:
1141 // If this is a class, structure, union, or enumeration type
1142 // that is a definition (not a declaration), and not scoped
1143 // inside a function then separate this out as a type unit.
1144 return !CTy.isForwardDecl() && isTypeUnitScoped(CTy, DD);
1150 /// constructTypeDIE - Construct type DIE from DICompositeType.
1151 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1152 // Get core information.
1153 StringRef Name = CTy.getName();
1155 uint64_t Size = CTy.getSizeInBits() >> 3;
1156 uint16_t Tag = Buffer.getTag();
1159 case dwarf::DW_TAG_array_type:
1160 constructArrayTypeDIE(Buffer, CTy);
1162 case dwarf::DW_TAG_enumeration_type:
1163 constructEnumTypeDIE(Buffer, CTy);
1165 case dwarf::DW_TAG_subroutine_type: {
1166 // Add return type. A void return won't have a type.
1167 DIArray Elements = CTy.getTypeArray();
1168 DIType RTy(Elements.getElement(0));
1170 addType(&Buffer, RTy);
1172 bool isPrototyped = true;
1174 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1175 DIDescriptor Ty = Elements.getElement(i);
1176 if (Ty.isUnspecifiedParameter()) {
1177 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1178 isPrototyped = false;
1180 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1181 addType(Arg, DIType(Ty));
1182 if (DIType(Ty).isArtificial())
1183 addFlag(Arg, dwarf::DW_AT_artificial);
1186 // Add prototype flag if we're dealing with a C language and the
1187 // function has been prototyped.
1188 uint16_t Language = getLanguage();
1190 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1191 Language == dwarf::DW_LANG_ObjC))
1192 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1194 case dwarf::DW_TAG_structure_type:
1195 case dwarf::DW_TAG_union_type:
1196 case dwarf::DW_TAG_class_type: {
1197 // Add elements to structure type.
1198 DIArray Elements = CTy.getTypeArray();
1199 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1200 DIDescriptor Element = Elements.getElement(i);
1201 DIE *ElemDie = NULL;
1202 if (Element.isSubprogram()) {
1203 DISubprogram SP(Element);
1204 ElemDie = getOrCreateSubprogramDIE(SP);
1205 if (SP.isProtected())
1206 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1207 dwarf::DW_ACCESS_protected);
1208 else if (SP.isPrivate())
1209 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1210 dwarf::DW_ACCESS_private);
1212 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1213 dwarf::DW_ACCESS_public);
1214 if (SP.isExplicit())
1215 addFlag(ElemDie, dwarf::DW_AT_explicit);
1216 } else if (Element.isDerivedType()) {
1217 DIDerivedType DDTy(Element);
1218 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1219 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1220 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1221 dwarf::DW_AT_friend);
1222 } else if (DDTy.isStaticMember()) {
1223 getOrCreateStaticMemberDIE(DDTy);
1225 constructMemberDIE(Buffer, DDTy);
1227 } else if (Element.isObjCProperty()) {
1228 DIObjCProperty Property(Element);
1229 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1230 StringRef PropertyName = Property.getObjCPropertyName();
1231 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1232 addType(ElemDie, Property.getType());
1233 addSourceLine(ElemDie, Property);
1234 StringRef GetterName = Property.getObjCPropertyGetterName();
1235 if (!GetterName.empty())
1236 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1237 StringRef SetterName = Property.getObjCPropertySetterName();
1238 if (!SetterName.empty())
1239 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1240 unsigned PropertyAttributes = 0;
1241 if (Property.isReadOnlyObjCProperty())
1242 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1243 if (Property.isReadWriteObjCProperty())
1244 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1245 if (Property.isAssignObjCProperty())
1246 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1247 if (Property.isRetainObjCProperty())
1248 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1249 if (Property.isCopyObjCProperty())
1250 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1251 if (Property.isNonAtomicObjCProperty())
1252 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1253 if (PropertyAttributes)
1254 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1255 PropertyAttributes);
1257 DIEEntry *Entry = getDIEEntry(Element);
1259 Entry = createDIEEntry(ElemDie);
1260 insertDIEEntry(Element, Entry);
1266 if (CTy.isAppleBlockExtension())
1267 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1269 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1271 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1272 getOrCreateTypeDIE(ContainingType));
1274 if (CTy.isObjcClassComplete())
1275 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1277 // Add template parameters to a class, structure or union types.
1278 // FIXME: The support isn't in the metadata for this yet.
1279 if (Tag == dwarf::DW_TAG_class_type ||
1280 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1281 addTemplateParams(Buffer, CTy.getTemplateParams());
1289 // Add name if not anonymous or intermediate type.
1291 addString(&Buffer, dwarf::DW_AT_name, Name);
1293 if (Tag == dwarf::DW_TAG_enumeration_type ||
1294 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1295 Tag == dwarf::DW_TAG_union_type) {
1296 // Add size if non-zero (derived types might be zero-sized.)
1297 // TODO: Do we care about size for enum forward declarations?
1299 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1300 else if (!CTy.isForwardDecl())
1301 // Add zero size if it is not a forward declaration.
1302 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1304 // If we're a forward decl, say so.
1305 if (CTy.isForwardDecl())
1306 addFlag(&Buffer, dwarf::DW_AT_declaration);
1308 // Add source line info if available.
1309 if (!CTy.isForwardDecl())
1310 addSourceLine(&Buffer, CTy);
1312 // No harm in adding the runtime language to the declaration.
1313 unsigned RLang = CTy.getRunTimeLang();
1315 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1318 // If this is a type applicable to a type unit it then add it to the
1319 // list of types we'll compute a hash for later.
1320 if (shouldCreateTypeUnit(CTy, DD))
1321 DD->addTypeUnitType(&Buffer);
1324 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1325 /// DITemplateTypeParameter.
1327 CompileUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1328 DITemplateTypeParameter TP) {
1330 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1331 // Add the type if it exists, it could be void and therefore no type.
1333 addType(ParamDIE, resolve(TP.getType()));
1334 if (!TP.getName().empty())
1335 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1338 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1339 /// DITemplateValueParameter.
1341 CompileUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1342 DITemplateValueParameter VP) {
1343 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1345 // Add the type if there is one, template template and template parameter
1346 // packs will not have a type.
1347 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1348 addType(ParamDIE, resolve(VP.getType()));
1349 if (!VP.getName().empty())
1350 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1351 if (Value *Val = VP.getValue()) {
1352 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1353 addConstantValue(ParamDIE, CI,
1354 isUnsignedDIType(DD, resolve(VP.getType())));
1355 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1356 // For declaration non-type template parameters (such as global values and
1358 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1359 addOpAddress(Block, Asm->getSymbol(GV));
1360 // Emit DW_OP_stack_value to use the address as the immediate value of the
1361 // parameter, rather than a pointer to it.
1362 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1363 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1364 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1365 assert(isa<MDString>(Val));
1366 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1367 cast<MDString>(Val)->getString());
1368 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1369 assert(isa<MDNode>(Val));
1370 DIArray A(cast<MDNode>(Val));
1371 addTemplateParams(*ParamDIE, A);
1376 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1377 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1378 // Construct the context before querying for the existence of the DIE in case
1379 // such construction creates the DIE.
1380 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1382 DIE *NDie = getDIE(NS);
1385 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1387 if (!NS.getName().empty()) {
1388 addString(NDie, dwarf::DW_AT_name, NS.getName());
1389 addAccelNamespace(NS.getName(), NDie);
1390 addGlobalName(NS.getName(), NDie, NS.getContext());
1392 addAccelNamespace("(anonymous namespace)", NDie);
1393 addSourceLine(NDie, NS);
1397 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1398 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1399 // Construct the context before querying for the existence of the DIE in case
1400 // such construction creates the DIE (as is the case for member function
1402 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1404 DIE *SPDie = getDIE(SP);
1408 DISubprogram SPDecl = SP.getFunctionDeclaration();
1409 if (SPDecl.isSubprogram())
1410 // Add subprogram definitions to the CU die directly.
1411 ContextDIE = CUDie.get();
1413 // DW_TAG_inlined_subroutine may refer to this DIE.
1414 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1416 DIE *DeclDie = NULL;
1417 if (SPDecl.isSubprogram())
1418 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1420 // Add function template parameters.
1421 addTemplateParams(*SPDie, SP.getTemplateParams());
1423 // If this DIE is going to refer declaration info using AT_specification
1424 // then there is no need to add other attributes.
1426 // Refer function declaration directly.
1427 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1432 // Add the linkage name if we have one.
1433 StringRef LinkageName = SP.getLinkageName();
1434 if (!LinkageName.empty())
1435 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1436 GlobalValue::getRealLinkageName(LinkageName));
1438 // Constructors and operators for anonymous aggregates do not have names.
1439 if (!SP.getName().empty())
1440 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1442 addSourceLine(SPDie, SP);
1444 // Add the prototype if we have a prototype and we have a C like
1446 uint16_t Language = getLanguage();
1447 if (SP.isPrototyped() &&
1448 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1449 Language == dwarf::DW_LANG_ObjC))
1450 addFlag(SPDie, dwarf::DW_AT_prototyped);
1452 DICompositeType SPTy = SP.getType();
1453 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1454 "the type of a subprogram should be a subroutine");
1456 DIArray Args = SPTy.getTypeArray();
1457 // Add a return type. If this is a type like a C/C++ void type we don't add a
1459 if (Args.getElement(0))
1460 addType(SPDie, DIType(Args.getElement(0)));
1462 unsigned VK = SP.getVirtuality();
1464 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1465 DIEBlock *Block = getDIEBlock();
1466 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1467 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1468 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1469 ContainingTypeMap.insert(
1470 std::make_pair(SPDie, resolve(SP.getContainingType())));
1473 if (!SP.isDefinition()) {
1474 addFlag(SPDie, dwarf::DW_AT_declaration);
1476 // Add arguments. Do not add arguments for subprogram definition. They will
1477 // be handled while processing variables.
1478 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1479 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1480 DIType ATy(Args.getElement(i));
1482 if (ATy.isArtificial())
1483 addFlag(Arg, dwarf::DW_AT_artificial);
1487 if (SP.isArtificial())
1488 addFlag(SPDie, dwarf::DW_AT_artificial);
1490 if (!SP.isLocalToUnit())
1491 addFlag(SPDie, dwarf::DW_AT_external);
1493 if (SP.isOptimized())
1494 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1496 if (unsigned isa = Asm->getISAEncoding()) {
1497 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1503 // Return const expression if value is a GEP to access merged global
1505 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1506 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1507 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1508 if (!CE || CE->getNumOperands() != 3 ||
1509 CE->getOpcode() != Instruction::GetElementPtr)
1512 // First operand points to a global struct.
1513 Value *Ptr = CE->getOperand(0);
1514 if (!isa<GlobalValue>(Ptr) ||
1515 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1518 // Second operand is zero.
1519 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1520 if (!CI || !CI->isZero())
1523 // Third operand is offset.
1524 if (!isa<ConstantInt>(CE->getOperand(2)))
1530 /// createGlobalVariableDIE - create global variable DIE.
1531 void CompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1533 // Check for pre-existence.
1537 if (!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 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
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 const MCExpr *Expr =
1591 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1592 // Based on GCC's support for TLS:
1593 if (!DD->useSplitDwarf()) {
1594 // 1) Start with a constNu of the appropriate pointer size
1595 addUInt(Block, dwarf::DW_FORM_data1,
1596 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1597 // 2) containing the (relocated) offset of the TLS variable
1598 // within the module's TLS block.
1599 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1601 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1602 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1604 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1605 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1607 addOpAddress(Block, Sym);
1608 // Do not create specification DIE if context is either compile unit
1610 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1611 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1612 // Create specification DIE.
1613 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *CUDie);
1614 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1615 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1616 // A static member's declaration is already flagged as such.
1617 if (!SDMDecl.Verify())
1618 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1620 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1622 // Add the linkage name.
1623 StringRef LinkageName = GV.getLinkageName();
1624 if (!LinkageName.empty())
1625 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1626 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1628 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1630 dwarf::DW_AT_MIPS_linkage_name,
1631 GlobalValue::getRealLinkageName(LinkageName));
1632 } else if (const ConstantInt *CI =
1633 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1634 // AT_const_value was added when the static member was created. To avoid
1635 // emitting AT_const_value multiple times, we only add AT_const_value when
1636 // it is not a static member.
1637 if (!IsStaticMember)
1638 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1639 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1640 addToAccelTable = true;
1641 // GV is a merged global.
1642 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1643 Value *Ptr = CE->getOperand(0);
1644 addOpAddress(Block, Asm->getSymbol(cast<GlobalValue>(Ptr)));
1645 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1646 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1647 addUInt(Block, dwarf::DW_FORM_udata,
1648 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1649 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1650 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1653 if (addToAccelTable) {
1654 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1655 addAccelName(GV.getName(), AddrDIE);
1657 // If the linkage name is different than the name, go ahead and output
1658 // that as well into the name table.
1659 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1660 addAccelName(GV.getLinkageName(), AddrDIE);
1663 if (!GV.isLocalToUnit())
1664 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1668 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1669 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1671 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1672 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1674 // The LowerBound value defines the lower bounds which is typically zero for
1675 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1676 // Count == -1 then the array is unbounded and we do not emit
1677 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1678 // Count == 0, then the array has zero elements in which case we do not emit
1680 int64_t LowerBound = SR.getLo();
1681 int64_t DefaultLowerBound = getDefaultLowerBound();
1682 int64_t Count = SR.getCount();
1684 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1685 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1687 if (Count != -1 && Count != 0)
1688 // FIXME: An unbounded array should reference the expression that defines
1690 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1691 LowerBound + Count - 1);
1694 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1695 void CompileUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1697 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1699 // Emit the element type.
1700 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1702 // Get an anonymous type for index type.
1703 // FIXME: This type should be passed down from the front end
1704 // as different languages may have different sizes for indexes.
1705 DIE *IdxTy = getIndexTyDie();
1707 // Construct an anonymous type for index type.
1708 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *CUDie.get());
1709 addString(IdxTy, dwarf::DW_AT_name, "int");
1710 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1711 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1712 dwarf::DW_ATE_signed);
1713 setIndexTyDie(IdxTy);
1716 // Add subranges to array type.
1717 DIArray Elements = CTy.getTypeArray();
1718 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1719 DIDescriptor Element = Elements.getElement(i);
1720 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1721 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1725 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1726 void CompileUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1727 DIArray Elements = CTy.getTypeArray();
1729 // Add enumerators to enumeration type.
1730 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1731 DIEnumerator Enum(Elements.getElement(i));
1732 if (Enum.isEnumerator()) {
1733 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1734 StringRef Name = Enum.getName();
1735 addString(Enumerator, dwarf::DW_AT_name, Name);
1736 int64_t Value = Enum.getEnumValue();
1737 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1740 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1742 addType(&Buffer, DTy);
1743 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1747 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1749 void CompileUnit::constructContainingTypeDIEs() {
1750 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1751 CE = ContainingTypeMap.end();
1753 DIE *SPDie = CI->first;
1754 DIDescriptor D(CI->second);
1757 DIE *NDie = getDIE(D);
1760 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1764 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1765 DIE *CompileUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1766 StringRef Name = DV.getName();
1768 // Define variable debug information entry.
1769 DIE *VariableDie = new DIE(DV.getTag());
1770 DbgVariable *AbsVar = DV.getAbstractVariable();
1771 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1773 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1776 addString(VariableDie, dwarf::DW_AT_name, Name);
1777 addSourceLine(VariableDie, DV.getVariable());
1778 addType(VariableDie, DV.getType());
1781 if (DV.isArtificial())
1782 addFlag(VariableDie, dwarf::DW_AT_artificial);
1784 if (isScopeAbstract) {
1785 DV.setDIE(VariableDie);
1789 // Add variable address.
1791 unsigned Offset = DV.getDotDebugLocOffset();
1792 if (Offset != ~0U) {
1793 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1794 Asm->GetTempSymbol("debug_loc", Offset));
1795 DV.setDIE(VariableDie);
1799 // Check if variable is described by a DBG_VALUE instruction.
1800 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1801 assert(DVInsn->getNumOperands() == 3);
1802 if (DVInsn->getOperand(0).isReg()) {
1803 const MachineOperand RegOp = DVInsn->getOperand(0);
1804 // If the second operand is an immediate, this is an indirect value.
1805 if (DVInsn->getOperand(1).isImm()) {
1806 MachineLocation Location(RegOp.getReg(),
1807 DVInsn->getOperand(1).getImm());
1808 addVariableAddress(DV, VariableDie, Location);
1809 } else if (RegOp.getReg())
1810 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1811 } else if (DVInsn->getOperand(0).isImm())
1812 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1813 else if (DVInsn->getOperand(0).isFPImm())
1814 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1815 else if (DVInsn->getOperand(0).isCImm())
1816 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1817 isUnsignedDIType(DD, DV.getType()));
1819 DV.setDIE(VariableDie);
1822 // .. else use frame index.
1823 int FI = DV.getFrameIndex();
1825 unsigned FrameReg = 0;
1826 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1827 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1828 MachineLocation Location(FrameReg, Offset);
1829 addVariableAddress(DV, VariableDie, Location);
1833 DV.setDIE(VariableDie);
1837 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1838 void CompileUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1839 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1840 StringRef Name = DT.getName();
1842 addString(MemberDie, dwarf::DW_AT_name, Name);
1844 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1846 addSourceLine(MemberDie, DT);
1848 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1850 // For C++, virtual base classes are not at fixed offset. Use following
1851 // expression to extract appropriate offset from vtable.
1852 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1854 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1855 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1856 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1857 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1858 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1859 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1860 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1861 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1863 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1865 uint64_t Size = DT.getSizeInBits();
1866 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1867 uint64_t OffsetInBytes;
1869 if (Size != FieldSize) {
1871 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1872 getBaseTypeSize(DD, DT) >> 3);
1873 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1875 uint64_t Offset = DT.getOffsetInBits();
1876 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1877 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1878 uint64_t FieldOffset = (HiMark - FieldSize);
1879 Offset -= FieldOffset;
1881 // Maybe we need to work from the other end.
1882 if (Asm->getDataLayout().isLittleEndian())
1883 Offset = FieldSize - (Offset + Size);
1884 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1886 // Here WD_AT_data_member_location points to the anonymous
1887 // field that includes this bit field.
1888 OffsetInBytes = FieldOffset >> 3;
1890 // This is not a bitfield.
1891 OffsetInBytes = DT.getOffsetInBits() >> 3;
1893 if (DD->getDwarfVersion() <= 2) {
1894 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1895 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1896 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1897 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1899 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1903 if (DT.isProtected())
1904 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1905 dwarf::DW_ACCESS_protected);
1906 else if (DT.isPrivate())
1907 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1908 dwarf::DW_ACCESS_private);
1909 // Otherwise C++ member and base classes are considered public.
1911 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1912 dwarf::DW_ACCESS_public);
1914 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1915 dwarf::DW_VIRTUALITY_virtual);
1917 // Objective-C properties.
1918 if (MDNode *PNode = DT.getObjCProperty())
1919 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1920 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1923 if (DT.isArtificial())
1924 addFlag(MemberDie, dwarf::DW_AT_artificial);
1927 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1928 DIE *CompileUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1932 // Construct the context before querying for the existence of the DIE in case
1933 // such construction creates the DIE.
1934 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1935 assert(dwarf::isType(ContextDIE->getTag()) &&
1936 "Static member should belong to a type.");
1938 DIE *StaticMemberDIE = getDIE(DT);
1939 if (StaticMemberDIE)
1940 return StaticMemberDIE;
1942 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1944 DIType Ty = resolve(DT.getTypeDerivedFrom());
1946 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1947 addType(StaticMemberDIE, Ty);
1948 addSourceLine(StaticMemberDIE, DT);
1949 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1950 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1952 // FIXME: We could omit private if the parent is a class_type, and
1953 // public if the parent is something else.
1954 if (DT.isProtected())
1955 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1956 dwarf::DW_ACCESS_protected);
1957 else if (DT.isPrivate())
1958 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1959 dwarf::DW_ACCESS_private);
1961 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1962 dwarf::DW_ACCESS_public);
1964 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1965 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1966 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1967 addConstantFPValue(StaticMemberDIE, CFP);
1969 return StaticMemberDIE;
1972 void CompileUnit::emitHeader(const MCSection *ASection,
1973 const MCSymbol *ASectionSym) {
1974 Asm->OutStreamer.AddComment("DWARF version number");
1975 Asm->EmitInt16(DD->getDwarfVersion());
1976 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1977 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1979 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1980 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());