1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfUnit.h"
15 #include "DwarfAccelTable.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "dwarfdebug"
43 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
44 cl::desc("Generate DWARF4 type units."),
47 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
49 : DwarfExpression(*AP.MF->getSubtarget().getRegisterInfo(),
50 AP.getDwarfDebug()->getDwarfVersion()),
51 AP(AP), DU(DU), DIE(DIE) {}
53 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
54 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
56 void DIEDwarfExpression::EmitSigned(int64_t Value) {
57 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
59 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) {
60 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
62 bool DIEDwarfExpression::isFrameRegister(unsigned MachineReg) {
63 return MachineReg == TRI.getFrameRegister(*AP.MF);
66 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag,
67 const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW,
69 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
70 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
71 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
72 UnitTag == dwarf::DW_TAG_type_unit);
73 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
76 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
77 DwarfDebug *DW, DwarfFile *DWU,
78 MCDwarfDwoLineTable *SplitLineTable)
79 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
80 CU(CU), SplitLineTable(SplitLineTable) {
82 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
85 DwarfUnit::~DwarfUnit() {
86 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
87 DIEBlocks[j]->~DIEBlock();
88 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
89 DIELocs[j]->~DIELoc();
92 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
93 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
97 int64_t DwarfUnit::getDefaultLowerBound() const {
98 switch (getLanguage()) {
102 case dwarf::DW_LANG_C89:
103 case dwarf::DW_LANG_C99:
104 case dwarf::DW_LANG_C:
105 case dwarf::DW_LANG_C_plus_plus:
106 case dwarf::DW_LANG_ObjC:
107 case dwarf::DW_LANG_ObjC_plus_plus:
110 case dwarf::DW_LANG_Fortran77:
111 case dwarf::DW_LANG_Fortran90:
112 case dwarf::DW_LANG_Fortran95:
115 // The languages below have valid values only if the DWARF version >= 4.
116 case dwarf::DW_LANG_Java:
117 case dwarf::DW_LANG_Python:
118 case dwarf::DW_LANG_UPC:
119 case dwarf::DW_LANG_D:
120 if (dwarf::DWARF_VERSION >= 4)
124 case dwarf::DW_LANG_Ada83:
125 case dwarf::DW_LANG_Ada95:
126 case dwarf::DW_LANG_Cobol74:
127 case dwarf::DW_LANG_Cobol85:
128 case dwarf::DW_LANG_Modula2:
129 case dwarf::DW_LANG_Pascal83:
130 case dwarf::DW_LANG_PLI:
131 if (dwarf::DWARF_VERSION >= 4)
135 // The languages below have valid values only if the DWARF version >= 5.
136 case dwarf::DW_LANG_OpenCL:
137 case dwarf::DW_LANG_Go:
138 case dwarf::DW_LANG_Haskell:
139 case dwarf::DW_LANG_C_plus_plus_03:
140 case dwarf::DW_LANG_C_plus_plus_11:
141 case dwarf::DW_LANG_OCaml:
142 case dwarf::DW_LANG_Rust:
143 case dwarf::DW_LANG_C11:
144 case dwarf::DW_LANG_Swift:
145 case dwarf::DW_LANG_Dylan:
146 case dwarf::DW_LANG_C_plus_plus_14:
147 if (dwarf::DWARF_VERSION >= 5)
151 case dwarf::DW_LANG_Modula3:
152 case dwarf::DW_LANG_Julia:
153 case dwarf::DW_LANG_Fortran03:
154 case dwarf::DW_LANG_Fortran08:
155 if (dwarf::DWARF_VERSION >= 5)
163 /// Check whether the DIE for this MDNode can be shared across CUs.
164 static bool isShareableAcrossCUs(const DINode *D) {
165 // When the MDNode can be part of the type system, the DIE can be shared
167 // Combining type units and cross-CU DIE sharing is lower value (since
168 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
169 // level already) but may be implementable for some value in projects
170 // building multiple independent libraries with LTO and then linking those
172 return (isa<DIType>(D) ||
173 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
174 !GenerateDwarfTypeUnits;
177 DIE *DwarfUnit::getDIE(const DINode *D) const {
178 if (isShareableAcrossCUs(D))
179 return DU->getDIE(D);
180 return MDNodeToDieMap.lookup(D);
183 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
184 if (isShareableAcrossCUs(Desc)) {
185 DU->insertDIE(Desc, D);
188 MDNodeToDieMap.insert(std::make_pair(Desc, D));
191 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
192 if (DD->getDwarfVersion() >= 4)
193 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
195 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
198 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
199 Optional<dwarf::Form> Form, uint64_t Integer) {
201 Form = DIEInteger::BestForm(false, Integer);
202 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
204 Die.addValue(Attribute, *Form, Value);
207 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
208 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
211 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
212 Optional<dwarf::Form> Form, int64_t Integer) {
214 Form = DIEInteger::BestForm(true, Integer);
215 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
216 Die.addValue(Attribute, *Form, Value);
219 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
221 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
224 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
227 return addLocalString(Die, Attribute, String);
229 addIndexedString(Die, Attribute, String);
232 void DwarfUnit::addIndexedString(DIE &Die, dwarf::Attribute Attribute,
234 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
235 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
236 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
237 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
240 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
242 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
243 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
245 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
246 Value = new (DIEValueAllocator) DIELabel(Symb);
248 Value = new (DIEValueAllocator)
249 DIEDelta(Symb, TLOF.getDwarfStrSection()->getBeginSymbol());
250 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
251 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
254 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
255 const MCSymbol *Label) {
256 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
257 Die.addValue(Attribute, Form, Value);
260 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
261 addLabel(Die, (dwarf::Attribute)0, Form, Label);
264 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
266 if (DD->getDwarfVersion() >= 4)
267 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
269 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
272 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
273 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
274 : getCU().getOrCreateSourceID(FileName, DirName);
277 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *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,
284 DD->getAddressPool().getIndex(Sym));
288 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
289 const MCSymbol *Hi, const MCSymbol *Lo) {
290 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
291 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
294 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
295 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
298 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
299 // Flag the type unit reference as a declaration so that if it contains
300 // members (implicit special members, static data member definitions, member
301 // declarations for definitions in this CU, etc) consumers don't get confused
302 // and think this is a full definition.
303 addFlag(Die, dwarf::DW_AT_declaration);
305 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
306 new (DIEValueAllocator) DIETypeSignature(Type));
309 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
311 const DIE *DieCU = Die.getUnitOrNull();
312 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
314 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
315 DieCU = &getUnitDie();
317 EntryCU = &getUnitDie();
318 Die.addValue(Attribute,
319 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
323 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
324 assert(Tag != dwarf::DW_TAG_auto_variable &&
325 Tag != dwarf::DW_TAG_arg_variable);
326 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
327 DIE &Die = *Parent.getChildren().back();
333 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
334 Loc->ComputeSize(Asm);
335 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
336 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
339 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
341 Block->ComputeSize(Asm);
342 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
343 Die.addValue(Attribute, Block->BestForm(), Block);
346 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
347 StringRef Directory) {
351 unsigned FileID = getOrCreateSourceID(File, Directory);
352 assert(FileID && "Invalid file id");
353 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
354 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
357 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
360 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
361 V->getScope()->getDirectory());
364 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
367 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
370 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
373 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
376 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
379 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
382 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
385 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
388 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
389 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
392 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
393 unsigned SizeInBits, unsigned OffsetInBits) {
394 DIEDwarfExpression Expr(*Asm, *this, TheDie);
395 Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
399 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
401 DIEDwarfExpression Expr(*Asm, *this, TheDie);
402 return Expr.AddMachineRegIndirect(Reg, Offset);
405 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
406 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
407 gives the variable VarName either the struct, or a pointer to the struct, as
408 its type. This is necessary for various behind-the-scenes things the
409 compiler needs to do with by-reference variables in Blocks.
411 However, as far as the original *programmer* is concerned, the variable
412 should still have type 'SomeType', as originally declared.
414 The function getBlockByrefType dives into the __Block_byref_x_VarName
415 struct to find the original type of the variable, which is then assigned to
416 the variable's Debug Information Entry as its real type. So far, so good.
417 However now the debugger will expect the variable VarName to have the type
418 SomeType. So we need the location attribute for the variable to be an
419 expression that explains to the debugger how to navigate through the
420 pointers and struct to find the actual variable of type SomeType.
422 The following function does just that. We start by getting
423 the "normal" location for the variable. This will be the location
424 of either the struct __Block_byref_x_VarName or the pointer to the
425 struct __Block_byref_x_VarName.
427 The struct will look something like:
429 struct __Block_byref_x_VarName {
431 struct __Block_byref_x_VarName *forwarding;
432 ... <various other fields>
434 ... <maybe more fields>
437 If we are given the struct directly (as our starting point) we
438 need to tell the debugger to:
440 1). Add the offset of the forwarding field.
442 2). Follow that pointer to get the real __Block_byref_x_VarName
443 struct to use (the real one may have been copied onto the heap).
445 3). Add the offset for the field VarName, to find the actual variable.
447 If we started with a pointer to the struct, then we need to
448 dereference that pointer first, before the other steps.
449 Translating this into DWARF ops, we will need to append the following
450 to the current location description for the variable:
452 DW_OP_deref -- optional, if we start with a pointer
453 DW_OP_plus_uconst <forward_fld_offset>
455 DW_OP_plus_uconst <varName_fld_offset>
457 That is what this function does. */
459 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
460 dwarf::Attribute Attribute,
461 const MachineLocation &Location) {
462 const DIType *Ty = DV.getType();
463 const DIType *TmpTy = Ty;
464 uint16_t Tag = Ty->getTag();
465 bool isPointer = false;
467 StringRef varName = DV.getName();
469 if (Tag == dwarf::DW_TAG_pointer_type) {
470 auto *DTy = cast<DIDerivedType>(Ty);
471 TmpTy = resolve(DTy->getBaseType());
475 // Find the __forwarding field and the variable field in the __Block_byref
477 DINodeArray Fields = cast<DICompositeTypeBase>(TmpTy)->getElements();
478 const DIDerivedType *varField = nullptr;
479 const DIDerivedType *forwardingField = nullptr;
481 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
482 auto *DT = cast<DIDerivedType>(Fields[i]);
483 StringRef fieldName = DT->getName();
484 if (fieldName == "__forwarding")
485 forwardingField = DT;
486 else if (fieldName == varName)
490 // Get the offsets for the forwarding field and the variable field.
491 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
492 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
494 // Decode the original location, and use that as the start of the byref
495 // variable's location.
496 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
499 if (Location.isReg())
500 validReg = addRegisterOpPiece(*Loc, Location.getReg());
502 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
507 // If we started with a pointer to the __Block_byref... struct, then
508 // the first thing we need to do is dereference the pointer (DW_OP_deref).
510 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
512 // Next add the offset for the '__forwarding' field:
513 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
514 // adding the offset if it's 0.
515 if (forwardingFieldOffset > 0) {
516 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
517 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
520 // Now dereference the __forwarding field to get to the real __Block_byref
521 // struct: DW_OP_deref.
522 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
524 // Now that we've got the real __Block_byref... struct, add the offset
525 // for the variable's field to get to the location of the actual variable:
526 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
527 if (varFieldOffset > 0) {
528 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
529 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
532 // Now attach the location information to the DIE.
533 addBlock(Die, Attribute, Loc);
536 /// Return true if type encoding is unsigned.
537 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
538 if (auto *DTy = dyn_cast<DIDerivedTypeBase>(Ty)) {
539 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
540 // Encode pointer constants as unsigned bytes. This is used at least for
541 // null pointer constant emission.
542 // (Pieces of) aggregate types that get hacked apart by SROA may also be
543 // represented by a constant. Encode them as unsigned bytes.
544 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
545 // here, but accept them for now due to a bug in SROA producing bogus
547 if (T == dwarf::DW_TAG_array_type ||
548 T == dwarf::DW_TAG_class_type ||
549 T == dwarf::DW_TAG_pointer_type ||
550 T == dwarf::DW_TAG_ptr_to_member_type ||
551 T == dwarf::DW_TAG_reference_type ||
552 T == dwarf::DW_TAG_rvalue_reference_type ||
553 T == dwarf::DW_TAG_structure_type ||
554 T == dwarf::DW_TAG_union_type)
556 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
557 T == dwarf::DW_TAG_volatile_type ||
558 T == dwarf::DW_TAG_restrict_type ||
559 T == dwarf::DW_TAG_enumeration_type);
560 if (DITypeRef Deriv = DTy->getBaseType())
561 return isUnsignedDIType(DD, DD->resolve(Deriv));
562 // FIXME: Enums without a fixed underlying type have unknown signedness
563 // here, leading to incorrectly emitted constants.
564 assert(DTy->getTag() == dwarf::DW_TAG_enumeration_type);
568 auto *BTy = cast<DIBasicType>(Ty);
569 unsigned Encoding = BTy->getEncoding();
570 assert((Encoding == dwarf::DW_ATE_unsigned ||
571 Encoding == dwarf::DW_ATE_unsigned_char ||
572 Encoding == dwarf::DW_ATE_signed ||
573 Encoding == dwarf::DW_ATE_signed_char ||
574 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
575 Encoding == dwarf::DW_ATE_boolean ||
576 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
577 Ty->getName() == "decltype(nullptr)")) &&
578 "Unsupported encoding");
579 return Encoding == dwarf::DW_ATE_unsigned ||
580 Encoding == dwarf::DW_ATE_unsigned_char ||
581 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
582 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
585 /// If this type is derived from a base type then return base type size.
586 static uint64_t getBaseTypeSize(DwarfDebug *DD, const DIDerivedType *Ty) {
587 unsigned Tag = Ty->getTag();
589 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
590 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
591 Tag != dwarf::DW_TAG_restrict_type)
592 return Ty->getSizeInBits();
594 auto *BaseType = DD->resolve(Ty->getBaseType());
596 assert(BaseType && "Unexpected invalid base type");
598 // If this is a derived type, go ahead and get the base type, unless it's a
599 // reference then it's just the size of the field. Pointer types have no need
600 // of this since they're a different type of qualification on the type.
601 if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
602 BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
603 return Ty->getSizeInBits();
605 if (auto *DT = dyn_cast<DIDerivedType>(BaseType))
606 return getBaseTypeSize(DD, DT);
608 return BaseType->getSizeInBits();
611 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
612 assert(MO.isFPImm() && "Invalid machine operand!");
613 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
614 APFloat FPImm = MO.getFPImm()->getValueAPF();
616 // Get the raw data form of the floating point.
617 const APInt FltVal = FPImm.bitcastToAPInt();
618 const char *FltPtr = (const char *)FltVal.getRawData();
620 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
621 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
622 int Incr = (LittleEndian ? 1 : -1);
623 int Start = (LittleEndian ? 0 : NumBytes - 1);
624 int Stop = (LittleEndian ? NumBytes : -1);
626 // Output the constant to DWARF one byte at a time.
627 for (; Start != Stop; Start += Incr)
628 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
630 addBlock(Die, dwarf::DW_AT_const_value, Block);
633 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
634 // Pass this down to addConstantValue as an unsigned bag of bits.
635 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
638 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
640 addConstantValue(Die, CI->getValue(), Ty);
643 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
645 assert(MO.isImm() && "Invalid machine operand!");
647 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
650 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
651 // FIXME: This is a bit conservative/simple - it emits negative values always
652 // sign extended to 64 bits rather than minimizing the number of bytes.
653 addUInt(Die, dwarf::DW_AT_const_value,
654 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
657 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
658 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
661 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
662 unsigned CIBitWidth = Val.getBitWidth();
663 if (CIBitWidth <= 64) {
664 addConstantValue(Die, Unsigned,
665 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
669 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
671 // Get the raw data form of the large APInt.
672 const uint64_t *Ptr64 = Val.getRawData();
674 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
675 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
677 // Output the constant to DWARF one byte at a time.
678 for (int i = 0; i < NumBytes; i++) {
681 c = Ptr64[i / 8] >> (8 * (i & 7));
683 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
684 addUInt(*Block, dwarf::DW_FORM_data1, c);
687 addBlock(Die, dwarf::DW_AT_const_value, Block);
690 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
691 if (!LinkageName.empty())
693 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
694 : dwarf::DW_AT_MIPS_linkage_name,
695 GlobalValue::getRealLinkageName(LinkageName));
698 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
699 // Add template parameters.
700 for (const auto *Element : TParams) {
701 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
702 constructTemplateTypeParameterDIE(Buffer, TTP);
703 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
704 constructTemplateValueParameterDIE(Buffer, TVP);
708 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
709 if (!Context || isa<DIFile>(Context))
710 return &getUnitDie();
711 if (auto *T = dyn_cast<DIType>(Context))
712 return getOrCreateTypeDIE(T);
713 if (auto *NS = dyn_cast<DINamespace>(Context))
714 return getOrCreateNameSpace(NS);
715 if (auto *SP = dyn_cast<DISubprogram>(Context))
716 return getOrCreateSubprogramDIE(SP);
717 return getDIE(Context);
720 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
721 auto *Context = resolve(Ty->getScope());
722 DIE *ContextDIE = getOrCreateContextDIE(Context);
724 if (DIE *TyDIE = getDIE(Ty))
728 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
730 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
732 updateAcceleratorTables(Context, Ty, TyDIE);
736 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
740 auto *Ty = cast<DIType>(TyNode);
741 assert(Ty == resolve(Ty->getRef()) &&
742 "type was not uniqued, possible ODR violation.");
744 // DW_TAG_restrict_type is not supported in DWARF2
745 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
746 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
748 // Construct the context before querying for the existence of the DIE in case
749 // such construction creates the DIE.
750 auto *Context = resolve(Ty->getScope());
751 DIE *ContextDIE = getOrCreateContextDIE(Context);
754 if (DIE *TyDIE = getDIE(Ty))
758 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
760 updateAcceleratorTables(Context, Ty, TyDIE);
762 if (auto *BT = dyn_cast<DIBasicType>(Ty))
763 constructTypeDIE(TyDIE, BT);
764 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
765 constructTypeDIE(TyDIE, STy);
766 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
767 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
768 if (MDString *TypeId = CTy->getRawIdentifier()) {
769 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
770 // Skip updating the accelerator tables since this is not the full type.
773 constructTypeDIE(TyDIE, CTy);
775 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
781 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
782 const DIType *Ty, const DIE &TyDIE) {
783 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
784 bool IsImplementation = 0;
785 if (auto *CT = dyn_cast<DICompositeTypeBase>(Ty)) {
786 // A runtime language of 0 actually means C/C++ and that any
787 // non-negative value is some version of Objective-C/C++.
788 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
790 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
791 DD->addAccelType(Ty->getName(), TyDIE, Flags);
793 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
794 isa<DINamespace>(Context))
795 addGlobalType(Ty, TyDIE, Context);
799 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
800 dwarf::Attribute Attribute) {
801 assert(Ty && "Trying to add a type that doesn't exist?");
803 // Check for pre-existence.
804 DIEEntry *Entry = getDIEEntry(Ty);
805 // If it exists then use the existing value.
807 addDIEEntry(Entity, Attribute, Entry);
812 DIE *Buffer = getOrCreateTypeDIE(Ty);
815 Entry = createDIEEntry(*Buffer);
816 insertDIEEntry(Ty, Entry);
817 addDIEEntry(Entity, Attribute, Entry);
820 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
824 // FIXME: Decide whether to implement this for non-C++ languages.
825 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
829 SmallVector<const DIScope *, 1> Parents;
830 while (!isa<DICompileUnit>(Context)) {
831 Parents.push_back(Context);
832 if (Context->getScope())
833 Context = resolve(Context->getScope());
835 // Structure, etc types will have a NULL context if they're at the top
840 // Reverse iterate over our list to go from the outermost construct to the
842 for (auto I = Parents.rbegin(), E = Parents.rend(); I != E; ++I) {
843 const DIScope *Ctx = *I;
844 StringRef Name = Ctx->getName();
845 if (Name.empty() && isa<DINamespace>(Ctx))
846 Name = "(anonymous namespace)";
855 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
856 // Get core information.
857 StringRef Name = BTy->getName();
858 // Add name if not anonymous or intermediate type.
860 addString(Buffer, dwarf::DW_AT_name, Name);
862 // An unspecified type only has a name attribute.
863 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
866 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
869 uint64_t Size = BTy->getSizeInBits() >> 3;
870 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
873 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
874 // Get core information.
875 StringRef Name = DTy->getName();
876 uint64_t Size = DTy->getSizeInBits() >> 3;
877 uint16_t Tag = Buffer.getTag();
879 // Map to main type, void will not have a type.
880 const DIType *FromTy = resolve(DTy->getBaseType());
882 addType(Buffer, FromTy);
884 // Add name if not anonymous or intermediate type.
886 addString(Buffer, dwarf::DW_AT_name, Name);
888 // Add size if non-zero (derived types might be zero-sized.)
889 if (Size && Tag != dwarf::DW_TAG_pointer_type
890 && Tag != dwarf::DW_TAG_ptr_to_member_type)
891 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
893 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
895 Buffer, dwarf::DW_AT_containing_type,
896 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
897 // Add source line info if available and TyDesc is not a forward declaration.
898 if (!DTy->isForwardDecl())
899 addSourceLine(Buffer, DTy);
902 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
903 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
904 const DIType *Ty = resolve(Args[i]);
906 assert(i == N-1 && "Unspecified parameter must be the last argument");
907 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
909 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
911 if (Ty->isArtificial())
912 addFlag(Arg, dwarf::DW_AT_artificial);
917 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
918 // Add return type. A void return won't have a type.
919 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
921 if (auto RTy = resolve(Elements[0]))
922 addType(Buffer, RTy);
924 bool isPrototyped = true;
925 if (Elements.size() == 2 && !Elements[1])
926 isPrototyped = false;
928 constructSubprogramArguments(Buffer, Elements);
930 // Add prototype flag if we're dealing with a C language and the function has
932 uint16_t Language = getLanguage();
934 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
935 Language == dwarf::DW_LANG_ObjC))
936 addFlag(Buffer, dwarf::DW_AT_prototyped);
938 if (CTy->isLValueReference())
939 addFlag(Buffer, dwarf::DW_AT_reference);
941 if (CTy->isRValueReference())
942 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
945 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
946 // Add name if not anonymous or intermediate type.
947 StringRef Name = CTy->getName();
949 uint64_t Size = CTy->getSizeInBits() >> 3;
950 uint16_t Tag = Buffer.getTag();
953 case dwarf::DW_TAG_array_type:
954 constructArrayTypeDIE(Buffer, CTy);
956 case dwarf::DW_TAG_enumeration_type:
957 constructEnumTypeDIE(Buffer, CTy);
959 case dwarf::DW_TAG_structure_type:
960 case dwarf::DW_TAG_union_type:
961 case dwarf::DW_TAG_class_type: {
962 // Add elements to structure type.
963 DINodeArray Elements = CTy->getElements();
964 for (const auto *Element : Elements) {
967 if (auto *SP = dyn_cast<DISubprogram>(Element))
968 getOrCreateSubprogramDIE(SP);
969 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
970 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
971 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
972 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
973 } else if (DDTy->isStaticMember()) {
974 getOrCreateStaticMemberDIE(DDTy);
976 constructMemberDIE(Buffer, DDTy);
978 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
979 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
980 StringRef PropertyName = Property->getName();
981 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
982 if (Property->getType())
983 addType(ElemDie, Property->getType());
984 addSourceLine(ElemDie, Property);
985 StringRef GetterName = Property->getGetterName();
986 if (!GetterName.empty())
987 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
988 StringRef SetterName = Property->getSetterName();
989 if (!SetterName.empty())
990 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
991 if (unsigned PropertyAttributes = Property->getAttributes())
992 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
995 DIEEntry *Entry = getDIEEntry(Element);
997 Entry = createDIEEntry(ElemDie);
998 insertDIEEntry(Element, Entry);
1003 if (CTy->isAppleBlockExtension())
1004 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1006 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
1007 // inside C++ composite types to point to the base class with the vtable.
1008 if (auto *ContainingType =
1009 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
1010 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1011 *getOrCreateTypeDIE(ContainingType));
1013 if (CTy->isObjcClassComplete())
1014 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1016 // Add template parameters to a class, structure or union types.
1017 // FIXME: The support isn't in the metadata for this yet.
1018 if (Tag == dwarf::DW_TAG_class_type ||
1019 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1020 addTemplateParams(Buffer, CTy->getTemplateParams());
1028 // Add name if not anonymous or intermediate type.
1030 addString(Buffer, dwarf::DW_AT_name, Name);
1032 if (Tag == dwarf::DW_TAG_enumeration_type ||
1033 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1034 Tag == dwarf::DW_TAG_union_type) {
1035 // Add size if non-zero (derived types might be zero-sized.)
1036 // TODO: Do we care about size for enum forward declarations?
1038 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1039 else if (!CTy->isForwardDecl())
1040 // Add zero size if it is not a forward declaration.
1041 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1043 // If we're a forward decl, say so.
1044 if (CTy->isForwardDecl())
1045 addFlag(Buffer, dwarf::DW_AT_declaration);
1047 // Add source line info if available.
1048 if (!CTy->isForwardDecl())
1049 addSourceLine(Buffer, CTy);
1051 // No harm in adding the runtime language to the declaration.
1052 unsigned RLang = CTy->getRuntimeLang();
1054 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1059 void DwarfUnit::constructTemplateTypeParameterDIE(
1060 DIE &Buffer, const DITemplateTypeParameter *TP) {
1062 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1063 // Add the type if it exists, it could be void and therefore no type.
1065 addType(ParamDIE, resolve(TP->getType()));
1066 if (!TP->getName().empty())
1067 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1070 void DwarfUnit::constructTemplateValueParameterDIE(
1071 DIE &Buffer, const DITemplateValueParameter *VP) {
1072 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1074 // Add the type if there is one, template template and template parameter
1075 // packs will not have a type.
1076 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1077 addType(ParamDIE, resolve(VP->getType()));
1078 if (!VP->getName().empty())
1079 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1080 if (Metadata *Val = VP->getValue()) {
1081 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1082 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1083 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1084 // For declaration non-type template parameters (such as global values and
1086 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1087 addOpAddress(*Loc, Asm->getSymbol(GV));
1088 // Emit DW_OP_stack_value to use the address as the immediate value of the
1089 // parameter, rather than a pointer to it.
1090 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1091 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1092 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1093 assert(isa<MDString>(Val));
1094 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1095 cast<MDString>(Val)->getString());
1096 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1097 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1102 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1103 // Construct the context before querying for the existence of the DIE in case
1104 // such construction creates the DIE.
1105 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1107 if (DIE *NDie = getDIE(NS))
1109 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1111 StringRef Name = NS->getName();
1113 addString(NDie, dwarf::DW_AT_name, NS->getName());
1115 Name = "(anonymous namespace)";
1116 DD->addAccelNamespace(Name, NDie);
1117 addGlobalName(Name, NDie, NS->getScope());
1118 addSourceLine(NDie, NS);
1122 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1123 // Construct the context before querying for the existence of the DIE in case
1124 // such construction creates the DIE (as is the case for member function
1127 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1129 if (DIE *SPDie = getDIE(SP))
1132 if (auto *SPDecl = SP->getDeclaration()) {
1134 // Add subprogram definitions to the CU die directly.
1135 ContextDIE = &getUnitDie();
1136 // Build the decl now to ensure it precedes the definition.
1137 getOrCreateSubprogramDIE(SPDecl);
1141 // DW_TAG_inlined_subroutine may refer to this DIE.
1142 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1144 // Stop here and fill this in later, depending on whether or not this
1145 // subprogram turns out to have inlined instances or not.
1146 if (SP->isDefinition())
1149 applySubprogramAttributes(SP, SPDie);
1153 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1155 DIE *DeclDie = nullptr;
1156 StringRef DeclLinkageName;
1157 if (auto *SPDecl = SP->getDeclaration()) {
1158 DeclDie = getDIE(SPDecl);
1159 assert(DeclDie && "This DIE should've already been constructed when the "
1160 "definition DIE was created in "
1161 "getOrCreateSubprogramDIE");
1162 DeclLinkageName = SPDecl->getLinkageName();
1165 // Add function template parameters.
1166 addTemplateParams(SPDie, SP->getTemplateParams());
1168 // Add the linkage name if we have one and it isn't in the Decl.
1169 StringRef LinkageName = SP->getLinkageName();
1170 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1171 LinkageName == DeclLinkageName) &&
1172 "decl has a linkage name and it is different");
1173 if (DeclLinkageName.empty())
1174 addLinkageName(SPDie, LinkageName);
1179 // Refer to the function declaration where all the other attributes will be
1181 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1185 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1188 if (applySubprogramDefinitionAttributes(SP, SPDie))
1191 // Constructors and operators for anonymous aggregates do not have names.
1192 if (!SP->getName().empty())
1193 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1195 // Skip the rest of the attributes under -gmlt to save space.
1199 addSourceLine(SPDie, SP);
1201 // Add the prototype if we have a prototype and we have a C like
1203 uint16_t Language = getLanguage();
1204 if (SP->isPrototyped() &&
1205 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1206 Language == dwarf::DW_LANG_ObjC))
1207 addFlag(SPDie, dwarf::DW_AT_prototyped);
1209 const DISubroutineType *SPTy = SP->getType();
1210 assert(SPTy->getTag() == dwarf::DW_TAG_subroutine_type &&
1211 "the type of a subprogram should be a subroutine");
1213 auto Args = SPTy->getTypeArray();
1214 // Add a return type. If this is a type like a C/C++ void type we don't add a
1217 if (auto Ty = resolve(Args[0]))
1220 unsigned VK = SP->getVirtuality();
1222 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1223 DIELoc *Block = getDIELoc();
1224 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1225 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1226 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1227 ContainingTypeMap.insert(
1228 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1231 if (!SP->isDefinition()) {
1232 addFlag(SPDie, dwarf::DW_AT_declaration);
1234 // Add arguments. Do not add arguments for subprogram definition. They will
1235 // be handled while processing variables.
1236 constructSubprogramArguments(SPDie, Args);
1239 if (SP->isArtificial())
1240 addFlag(SPDie, dwarf::DW_AT_artificial);
1242 if (!SP->isLocalToUnit())
1243 addFlag(SPDie, dwarf::DW_AT_external);
1245 if (SP->isOptimized())
1246 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1248 if (unsigned isa = Asm->getISAEncoding())
1249 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1251 if (SP->isLValueReference())
1252 addFlag(SPDie, dwarf::DW_AT_reference);
1254 if (SP->isRValueReference())
1255 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1257 if (SP->isProtected())
1258 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1259 dwarf::DW_ACCESS_protected);
1260 else if (SP->isPrivate())
1261 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1262 dwarf::DW_ACCESS_private);
1263 else if (SP->isPublic())
1264 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1265 dwarf::DW_ACCESS_public);
1267 if (SP->isExplicit())
1268 addFlag(SPDie, dwarf::DW_AT_explicit);
1271 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1273 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1274 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1276 // The LowerBound value defines the lower bounds which is typically zero for
1277 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1278 // Count == -1 then the array is unbounded and we do not emit
1279 // DW_AT_lower_bound and DW_AT_count attributes.
1280 int64_t LowerBound = SR->getLowerBound();
1281 int64_t DefaultLowerBound = getDefaultLowerBound();
1282 int64_t Count = SR->getCount();
1284 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1285 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1288 // FIXME: An unbounded array should reference the expression that defines
1290 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1293 DIE *DwarfUnit::getIndexTyDie() {
1296 // Construct an integer type to use for indexes.
1297 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1298 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1299 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1300 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1301 dwarf::DW_ATE_unsigned);
1305 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1306 if (CTy->isVector())
1307 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1309 // Emit the element type.
1310 addType(Buffer, resolve(CTy->getBaseType()));
1312 // Get an anonymous type for index type.
1313 // FIXME: This type should be passed down from the front end
1314 // as different languages may have different sizes for indexes.
1315 DIE *IdxTy = getIndexTyDie();
1317 // Add subranges to array type.
1318 DINodeArray Elements = CTy->getElements();
1319 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1320 // FIXME: Should this really be such a loose cast?
1321 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1322 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1323 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1327 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1328 DINodeArray Elements = CTy->getElements();
1330 // Add enumerators to enumeration type.
1331 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1332 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1334 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1335 StringRef Name = Enum->getName();
1336 addString(Enumerator, dwarf::DW_AT_name, Name);
1337 int64_t Value = Enum->getValue();
1338 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1342 const DIType *DTy = resolve(CTy->getBaseType());
1344 addType(Buffer, DTy);
1345 addFlag(Buffer, dwarf::DW_AT_enum_class);
1349 void DwarfUnit::constructContainingTypeDIEs() {
1350 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1352 DIE &SPDie = *CI->first;
1353 const DINode *D = CI->second;
1356 DIE *NDie = getDIE(D);
1359 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1363 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1364 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1365 StringRef Name = DT->getName();
1367 addString(MemberDie, dwarf::DW_AT_name, Name);
1369 addType(MemberDie, resolve(DT->getBaseType()));
1371 addSourceLine(MemberDie, DT);
1373 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1375 // For C++, virtual base classes are not at fixed offset. Use following
1376 // expression to extract appropriate offset from vtable.
1377 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1379 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1380 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1381 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1382 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1383 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1384 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1385 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1386 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1388 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1390 uint64_t Size = DT->getSizeInBits();
1391 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1392 uint64_t OffsetInBytes;
1394 if (FieldSize && Size != FieldSize) {
1395 // Handle bitfield, assume bytes are 8 bits.
1396 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1397 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1399 uint64_t Offset = DT->getOffsetInBits();
1400 uint64_t AlignMask = ~(DT->getAlignInBits() - 1);
1401 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1402 uint64_t FieldOffset = (HiMark - FieldSize);
1403 Offset -= FieldOffset;
1405 // Maybe we need to work from the other end.
1406 if (Asm->getDataLayout().isLittleEndian())
1407 Offset = FieldSize - (Offset + Size);
1408 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1410 // Here DW_AT_data_member_location points to the anonymous
1411 // field that includes this bit field.
1412 OffsetInBytes = FieldOffset >> 3;
1414 // This is not a bitfield.
1415 OffsetInBytes = DT->getOffsetInBits() >> 3;
1417 if (DD->getDwarfVersion() <= 2) {
1418 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1419 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1420 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1421 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1423 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1427 if (DT->isProtected())
1428 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1429 dwarf::DW_ACCESS_protected);
1430 else if (DT->isPrivate())
1431 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1432 dwarf::DW_ACCESS_private);
1433 // Otherwise C++ member and base classes are considered public.
1434 else if (DT->isPublic())
1435 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1436 dwarf::DW_ACCESS_public);
1437 if (DT->isVirtual())
1438 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1439 dwarf::DW_VIRTUALITY_virtual);
1441 // Objective-C properties.
1442 if (MDNode *PNode = DT->getObjCProperty())
1443 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1444 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1447 if (DT->isArtificial())
1448 addFlag(MemberDie, dwarf::DW_AT_artificial);
1451 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1455 // Construct the context before querying for the existence of the DIE in case
1456 // such construction creates the DIE.
1457 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1458 assert(dwarf::isType(ContextDIE->getTag()) &&
1459 "Static member should belong to a type.");
1461 if (DIE *StaticMemberDIE = getDIE(DT))
1462 return StaticMemberDIE;
1464 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1466 const DIType *Ty = resolve(DT->getBaseType());
1468 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1469 addType(StaticMemberDIE, Ty);
1470 addSourceLine(StaticMemberDIE, DT);
1471 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1472 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1474 // FIXME: We could omit private if the parent is a class_type, and
1475 // public if the parent is something else.
1476 if (DT->isProtected())
1477 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1478 dwarf::DW_ACCESS_protected);
1479 else if (DT->isPrivate())
1480 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1481 dwarf::DW_ACCESS_private);
1482 else if (DT->isPublic())
1483 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1484 dwarf::DW_ACCESS_public);
1486 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1487 addConstantValue(StaticMemberDIE, CI, Ty);
1488 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1489 addConstantFPValue(StaticMemberDIE, CFP);
1491 return &StaticMemberDIE;
1494 void DwarfUnit::emitHeader(bool UseOffsets) {
1495 // Emit size of content not including length itself
1496 Asm->OutStreamer->AddComment("Length of Unit");
1497 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1499 Asm->OutStreamer->AddComment("DWARF version number");
1500 Asm->EmitInt16(DD->getDwarfVersion());
1501 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1503 // We share one abbreviations table across all units so it's always at the
1504 // start of the section. Use a relocatable offset where needed to ensure
1505 // linking doesn't invalidate that offset.
1506 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1508 Asm->emitSectionOffset(TLOF.getDwarfAbbrevSection()->getBeginSymbol());
1512 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1513 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1516 void DwarfUnit::initSection(const MCSection *Section) {
1517 assert(!this->Section);
1518 this->Section = Section;
1521 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1522 DwarfUnit::emitHeader(UseOffsets);
1523 Asm->OutStreamer->AddComment("Type Signature");
1524 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1525 Asm->OutStreamer->AddComment("Type DIE Offset");
1526 // In a skeleton type unit there is no type DIE so emit a zero offset.
1527 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1528 sizeof(Ty->getOffset()));
1531 bool DwarfTypeUnit::isDwoUnit() const {
1532 // Since there are no skeleton type units, all type units are dwo type units
1533 // when split DWARF is being used.
1534 return DD->useSplitDwarf();