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 "AddressPool.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/MC/MachineLocation.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "dwarfdebug"
48 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
49 cl::desc("Generate DWARF4 type units."),
52 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
54 : DwarfExpression(AP.getDwarfVersion()), AP(AP), DU(DU),
57 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
58 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
61 void DIEDwarfExpression::EmitSigned(int64_t Value) {
62 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
65 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) {
66 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
69 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
70 unsigned MachineReg) {
71 return MachineReg == TRI.getFrameRegister(*AP.MF);
74 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
75 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
76 : DIEUnit(A->getDwarfVersion(), A->getPointerSize(), UnitTag), CUNode(Node),
77 Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) {
80 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
81 DwarfDebug *DW, DwarfFile *DWU,
82 MCDwarfDwoLineTable *SplitLineTable)
83 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
84 SplitLineTable(SplitLineTable) {
86 addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
89 DwarfUnit::~DwarfUnit() {
90 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
91 DIEBlocks[j]->~DIEBlock();
92 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
93 DIELocs[j]->~DIELoc();
96 int64_t DwarfUnit::getDefaultLowerBound() const {
97 switch (getLanguage()) {
101 case dwarf::DW_LANG_C89:
102 case dwarf::DW_LANG_C99:
103 case dwarf::DW_LANG_C:
104 case dwarf::DW_LANG_C_plus_plus:
105 case dwarf::DW_LANG_ObjC:
106 case dwarf::DW_LANG_ObjC_plus_plus:
109 case dwarf::DW_LANG_Fortran77:
110 case dwarf::DW_LANG_Fortran90:
111 case dwarf::DW_LANG_Fortran95:
114 // The languages below have valid values only if the DWARF version >= 4.
115 case dwarf::DW_LANG_Java:
116 case dwarf::DW_LANG_Python:
117 case dwarf::DW_LANG_UPC:
118 case dwarf::DW_LANG_D:
119 if (dwarf::DWARF_VERSION >= 4)
123 case dwarf::DW_LANG_Ada83:
124 case dwarf::DW_LANG_Ada95:
125 case dwarf::DW_LANG_Cobol74:
126 case dwarf::DW_LANG_Cobol85:
127 case dwarf::DW_LANG_Modula2:
128 case dwarf::DW_LANG_Pascal83:
129 case dwarf::DW_LANG_PLI:
130 if (dwarf::DWARF_VERSION >= 4)
134 // The languages below have valid values only if the DWARF version >= 5.
135 case dwarf::DW_LANG_OpenCL:
136 case dwarf::DW_LANG_Go:
137 case dwarf::DW_LANG_Haskell:
138 case dwarf::DW_LANG_C_plus_plus_03:
139 case dwarf::DW_LANG_C_plus_plus_11:
140 case dwarf::DW_LANG_OCaml:
141 case dwarf::DW_LANG_Rust:
142 case dwarf::DW_LANG_C11:
143 case dwarf::DW_LANG_Swift:
144 case dwarf::DW_LANG_Dylan:
145 case dwarf::DW_LANG_C_plus_plus_14:
146 if (dwarf::DWARF_VERSION >= 5)
150 case dwarf::DW_LANG_Modula3:
151 case dwarf::DW_LANG_Julia:
152 case dwarf::DW_LANG_Fortran03:
153 case dwarf::DW_LANG_Fortran08:
154 if (dwarf::DWARF_VERSION >= 5)
162 /// Check whether the DIE for this MDNode can be shared across CUs.
163 static bool isShareableAcrossCUs(const DINode *D) {
164 // When the MDNode can be part of the type system, the DIE can be shared
166 // Combining type units and cross-CU DIE sharing is lower value (since
167 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
168 // level already) but may be implementable for some value in projects
169 // building multiple independent libraries with LTO and then linking those
171 return (isa<DIType>(D) ||
172 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
173 !GenerateDwarfTypeUnits;
176 DIE *DwarfUnit::getDIE(const DINode *D) const {
177 if (isShareableAcrossCUs(D))
178 return DU->getDIE(D);
179 return MDNodeToDieMap.lookup(D);
182 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
183 if (isShareableAcrossCUs(Desc)) {
184 DU->insertDIE(Desc, D);
187 MDNodeToDieMap.insert(std::make_pair(Desc, D));
190 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
191 if (DD->getDwarfVersion() >= 4)
192 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
195 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
199 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
200 Optional<dwarf::Form> Form, uint64_t Integer) {
202 Form = DIEInteger::BestForm(false, Integer);
203 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
206 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
208 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
211 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
212 Optional<dwarf::Form> Form, int64_t Integer) {
214 Form = DIEInteger::BestForm(true, Integer);
215 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
218 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
220 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
223 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
225 Die.addValue(DIEValueAllocator, Attribute,
226 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
227 DIEString(DU->getStringPool().getEntry(*Asm, String)));
230 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
231 dwarf::Attribute Attribute,
233 const MCSymbol *Label) {
234 return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
237 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
238 addLabel(Die, (dwarf::Attribute)0, Form, Label);
241 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
243 if (DD->getDwarfVersion() >= 4)
244 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
246 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
249 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
250 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
251 : getCU().getOrCreateSourceID(FileName, DirName);
254 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
255 if (!DD->useSplitDwarf()) {
256 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
257 addLabel(Die, dwarf::DW_FORM_udata, Sym);
259 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
260 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
261 DD->getAddressPool().getIndex(Sym));
265 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
266 const MCSymbol *Hi, const MCSymbol *Lo) {
267 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
268 new (DIEValueAllocator) DIEDelta(Hi, Lo));
271 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
272 addDIEEntry(Die, Attribute, DIEEntry(Entry));
275 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
276 // Flag the type unit reference as a declaration so that if it contains
277 // members (implicit special members, static data member definitions, member
278 // declarations for definitions in this CU, etc) consumers don't get confused
279 // and think this is a full definition.
280 addFlag(Die, dwarf::DW_AT_declaration);
282 Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
283 dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
286 void DwarfUnit::addDIETypeSignature(DIE &Die, dwarf::Attribute Attribute,
287 StringRef Identifier) {
288 uint64_t Signature = DD->makeTypeSignature(Identifier);
289 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_ref_sig8,
290 DIEInteger(Signature));
293 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
295 const DIEUnit *CU = Die.getUnit();
296 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
298 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
299 CU = getUnitDie().getUnit();
301 EntryCU = getUnitDie().getUnit();
302 Die.addValue(DIEValueAllocator, Attribute,
303 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
307 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
308 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
314 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
315 Loc->ComputeSize(Asm);
316 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
317 Die.addValue(DIEValueAllocator, Attribute,
318 Loc->BestForm(DD->getDwarfVersion()), Loc);
321 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
323 Block->ComputeSize(Asm);
324 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
325 Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
328 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
329 StringRef Directory) {
333 unsigned FileID = getOrCreateSourceID(File, Directory);
334 assert(FileID && "Invalid file id");
335 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
336 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
339 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
342 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
343 V->getScope()->getDirectory());
346 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
349 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
352 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
355 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
358 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
361 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
364 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
367 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
370 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
371 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
374 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
375 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
376 gives the variable VarName either the struct, or a pointer to the struct, as
377 its type. This is necessary for various behind-the-scenes things the
378 compiler needs to do with by-reference variables in Blocks.
380 However, as far as the original *programmer* is concerned, the variable
381 should still have type 'SomeType', as originally declared.
383 The function getBlockByrefType dives into the __Block_byref_x_VarName
384 struct to find the original type of the variable, which is then assigned to
385 the variable's Debug Information Entry as its real type. So far, so good.
386 However now the debugger will expect the variable VarName to have the type
387 SomeType. So we need the location attribute for the variable to be an
388 expression that explains to the debugger how to navigate through the
389 pointers and struct to find the actual variable of type SomeType.
391 The following function does just that. We start by getting
392 the "normal" location for the variable. This will be the location
393 of either the struct __Block_byref_x_VarName or the pointer to the
394 struct __Block_byref_x_VarName.
396 The struct will look something like:
398 struct __Block_byref_x_VarName {
400 struct __Block_byref_x_VarName *forwarding;
401 ... <various other fields>
403 ... <maybe more fields>
406 If we are given the struct directly (as our starting point) we
407 need to tell the debugger to:
409 1). Add the offset of the forwarding field.
411 2). Follow that pointer to get the real __Block_byref_x_VarName
412 struct to use (the real one may have been copied onto the heap).
414 3). Add the offset for the field VarName, to find the actual variable.
416 If we started with a pointer to the struct, then we need to
417 dereference that pointer first, before the other steps.
418 Translating this into DWARF ops, we will need to append the following
419 to the current location description for the variable:
421 DW_OP_deref -- optional, if we start with a pointer
422 DW_OP_plus_uconst <forward_fld_offset>
424 DW_OP_plus_uconst <varName_fld_offset>
426 That is what this function does. */
428 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
429 dwarf::Attribute Attribute,
430 const MachineLocation &Location) {
431 const DIType *Ty = DV.getType();
432 const DIType *TmpTy = Ty;
433 uint16_t Tag = Ty->getTag();
434 bool isPointer = false;
436 StringRef varName = DV.getName();
438 if (Tag == dwarf::DW_TAG_pointer_type) {
439 auto *DTy = cast<DIDerivedType>(Ty);
440 TmpTy = resolve(DTy->getBaseType());
444 // Find the __forwarding field and the variable field in the __Block_byref
446 DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
447 const DIDerivedType *varField = nullptr;
448 const DIDerivedType *forwardingField = nullptr;
450 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
451 auto *DT = cast<DIDerivedType>(Fields[i]);
452 StringRef fieldName = DT->getName();
453 if (fieldName == "__forwarding")
454 forwardingField = DT;
455 else if (fieldName == varName)
459 // Get the offsets for the forwarding field and the variable field.
460 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
461 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
463 // Decode the original location, and use that as the start of the byref
464 // variable's location.
465 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
466 SmallVector<uint64_t, 6> DIExpr;
467 DIEDwarfExpression Expr(*Asm, *this, *Loc);
470 if (Location.isReg())
471 validReg = Expr.AddMachineReg(*Asm->MF->getSubtarget().getRegisterInfo(),
475 Expr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(),
476 Location.getReg(), Location.getOffset());
481 // If we started with a pointer to the __Block_byref... struct, then
482 // the first thing we need to do is dereference the pointer (DW_OP_deref).
484 DIExpr.push_back(dwarf::DW_OP_deref);
486 // Next add the offset for the '__forwarding' field:
487 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
488 // adding the offset if it's 0.
489 if (forwardingFieldOffset > 0) {
490 DIExpr.push_back(dwarf::DW_OP_plus);
491 DIExpr.push_back(forwardingFieldOffset);
494 // Now dereference the __forwarding field to get to the real __Block_byref
495 // struct: DW_OP_deref.
496 DIExpr.push_back(dwarf::DW_OP_deref);
498 // Now that we've got the real __Block_byref... struct, add the offset
499 // for the variable's field to get to the location of the actual variable:
500 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
501 if (varFieldOffset > 0) {
502 DIExpr.push_back(dwarf::DW_OP_plus);
503 DIExpr.push_back(varFieldOffset);
505 Expr.AddExpression(makeArrayRef(DIExpr));
508 // Now attach the location information to the DIE.
509 addBlock(Die, Attribute, Loc);
512 /// Return true if type encoding is unsigned.
513 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
514 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
515 // FIXME: Enums without a fixed underlying type have unknown signedness
516 // here, leading to incorrectly emitted constants.
517 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
520 // (Pieces of) aggregate types that get hacked apart by SROA may be
521 // represented by a constant. Encode them as unsigned bytes.
525 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
526 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
527 // Encode pointer constants as unsigned bytes. This is used at least for
528 // null pointer constant emission.
529 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
530 // here, but accept them for now due to a bug in SROA producing bogus
532 if (T == dwarf::DW_TAG_pointer_type ||
533 T == dwarf::DW_TAG_ptr_to_member_type ||
534 T == dwarf::DW_TAG_reference_type ||
535 T == dwarf::DW_TAG_rvalue_reference_type)
537 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
538 T == dwarf::DW_TAG_volatile_type ||
539 T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
540 DITypeRef Deriv = DTy->getBaseType();
541 assert(Deriv && "Expected valid base type");
542 return isUnsignedDIType(DD, DD->resolve(Deriv));
545 auto *BTy = cast<DIBasicType>(Ty);
546 unsigned Encoding = BTy->getEncoding();
547 assert((Encoding == dwarf::DW_ATE_unsigned ||
548 Encoding == dwarf::DW_ATE_unsigned_char ||
549 Encoding == dwarf::DW_ATE_signed ||
550 Encoding == dwarf::DW_ATE_signed_char ||
551 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
552 Encoding == dwarf::DW_ATE_boolean ||
553 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
554 Ty->getName() == "decltype(nullptr)")) &&
555 "Unsupported encoding");
556 return Encoding == dwarf::DW_ATE_unsigned ||
557 Encoding == dwarf::DW_ATE_unsigned_char ||
558 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
559 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
562 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
563 assert(MO.isFPImm() && "Invalid machine operand!");
564 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
565 APFloat FPImm = MO.getFPImm()->getValueAPF();
567 // Get the raw data form of the floating point.
568 const APInt FltVal = FPImm.bitcastToAPInt();
569 const char *FltPtr = (const char *)FltVal.getRawData();
571 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
572 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
573 int Incr = (LittleEndian ? 1 : -1);
574 int Start = (LittleEndian ? 0 : NumBytes - 1);
575 int Stop = (LittleEndian ? NumBytes : -1);
577 // Output the constant to DWARF one byte at a time.
578 for (; Start != Stop; Start += Incr)
579 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
581 addBlock(Die, dwarf::DW_AT_const_value, Block);
584 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
585 // Pass this down to addConstantValue as an unsigned bag of bits.
586 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
589 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
591 addConstantValue(Die, CI->getValue(), Ty);
594 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
596 assert(MO.isImm() && "Invalid machine operand!");
598 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
601 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
602 // FIXME: This is a bit conservative/simple - it emits negative values always
603 // sign extended to 64 bits rather than minimizing the number of bytes.
604 addUInt(Die, dwarf::DW_AT_const_value,
605 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
608 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
609 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
612 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
613 unsigned CIBitWidth = Val.getBitWidth();
614 if (CIBitWidth <= 64) {
615 addConstantValue(Die, Unsigned,
616 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
620 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
622 // Get the raw data form of the large APInt.
623 const uint64_t *Ptr64 = Val.getRawData();
625 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
626 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
628 // Output the constant to DWARF one byte at a time.
629 for (int i = 0; i < NumBytes; i++) {
632 c = Ptr64[i / 8] >> (8 * (i & 7));
634 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
635 addUInt(*Block, dwarf::DW_FORM_data1, c);
638 addBlock(Die, dwarf::DW_AT_const_value, Block);
641 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
642 if (!LinkageName.empty())
644 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
645 : dwarf::DW_AT_MIPS_linkage_name,
646 GlobalValue::getRealLinkageName(LinkageName));
649 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
650 // Add template parameters.
651 for (const auto *Element : TParams) {
652 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
653 constructTemplateTypeParameterDIE(Buffer, TTP);
654 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
655 constructTemplateValueParameterDIE(Buffer, TVP);
659 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
660 if (!Context || isa<DIFile>(Context))
661 return &getUnitDie();
662 if (auto *T = dyn_cast<DIType>(Context))
663 return getOrCreateTypeDIE(T);
664 if (auto *NS = dyn_cast<DINamespace>(Context))
665 return getOrCreateNameSpace(NS);
666 if (auto *SP = dyn_cast<DISubprogram>(Context))
667 return getOrCreateSubprogramDIE(SP);
668 if (auto *M = dyn_cast<DIModule>(Context))
669 return getOrCreateModule(M);
670 return getDIE(Context);
673 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
674 auto *Context = resolve(Ty->getScope());
675 DIE *ContextDIE = getOrCreateContextDIE(Context);
677 if (DIE *TyDIE = getDIE(Ty))
681 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
683 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
685 if (!Ty->isExternalTypeRef())
686 updateAcceleratorTables(Context, Ty, TyDIE);
690 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
694 auto *Ty = cast<DIType>(TyNode);
696 // DW_TAG_restrict_type is not supported in DWARF2
697 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
698 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
700 // DW_TAG_atomic_type is not supported in DWARF < 5
701 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
702 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
704 // Construct the context before querying for the existence of the DIE in case
705 // such construction creates the DIE.
706 auto *Context = resolve(Ty->getScope());
707 DIE *ContextDIE = getOrCreateContextDIE(Context);
710 if (DIE *TyDIE = getDIE(Ty))
714 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
716 updateAcceleratorTables(Context, Ty, TyDIE);
718 if (auto *BT = dyn_cast<DIBasicType>(Ty))
719 constructTypeDIE(TyDIE, BT);
720 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
721 constructTypeDIE(TyDIE, STy);
722 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
723 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
724 if (MDString *TypeId = CTy->getRawIdentifier()) {
725 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
726 // Skip updating the accelerator tables since this is not the full type.
729 constructTypeDIE(TyDIE, CTy);
731 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
737 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
738 const DIType *Ty, const DIE &TyDIE) {
739 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
740 bool IsImplementation = false;
741 if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
742 // A runtime language of 0 actually means C/C++ and that any
743 // non-negative value is some version of Objective-C/C++.
744 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
746 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
747 DD->addAccelType(Ty->getName(), TyDIE, Flags);
749 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
750 isa<DINamespace>(Context))
751 addGlobalType(Ty, TyDIE, Context);
755 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
756 dwarf::Attribute Attribute) {
757 assert(Ty && "Trying to add a type that doesn't exist?");
758 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
761 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
765 // FIXME: Decide whether to implement this for non-C++ languages.
766 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
770 SmallVector<const DIScope *, 1> Parents;
771 while (!isa<DICompileUnit>(Context)) {
772 Parents.push_back(Context);
773 if (Context->getScope())
774 Context = resolve(Context->getScope());
776 // Structure, etc types will have a NULL context if they're at the top
781 // Reverse iterate over our list to go from the outermost construct to the
783 for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
784 StringRef Name = Ctx->getName();
785 if (Name.empty() && isa<DINamespace>(Ctx))
786 Name = "(anonymous namespace)";
795 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
796 // Get core information.
797 StringRef Name = BTy->getName();
798 // Add name if not anonymous or intermediate type.
800 addString(Buffer, dwarf::DW_AT_name, Name);
802 // An unspecified type only has a name attribute.
803 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
806 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
809 uint64_t Size = BTy->getSizeInBits() >> 3;
810 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
813 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
814 // Get core information.
815 StringRef Name = DTy->getName();
816 uint64_t Size = DTy->getSizeInBits() >> 3;
817 uint16_t Tag = Buffer.getTag();
819 // Map to main type, void will not have a type.
820 const DIType *FromTy = resolve(DTy->getBaseType());
822 addType(Buffer, FromTy);
824 // Add name if not anonymous or intermediate type.
826 addString(Buffer, dwarf::DW_AT_name, Name);
828 // Add size if non-zero (derived types might be zero-sized.)
829 if (Size && Tag != dwarf::DW_TAG_pointer_type
830 && Tag != dwarf::DW_TAG_ptr_to_member_type
831 && Tag != dwarf::DW_TAG_reference_type
832 && Tag != dwarf::DW_TAG_rvalue_reference_type)
833 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
835 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
837 Buffer, dwarf::DW_AT_containing_type,
838 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
839 // Add source line info if available and TyDesc is not a forward declaration.
840 if (!DTy->isForwardDecl())
841 addSourceLine(Buffer, DTy);
844 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
845 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
846 const DIType *Ty = resolve(Args[i]);
848 assert(i == N-1 && "Unspecified parameter must be the last argument");
849 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
851 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
853 if (Ty->isArtificial())
854 addFlag(Arg, dwarf::DW_AT_artificial);
859 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
860 // Add return type. A void return won't have a type.
861 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
863 if (auto RTy = resolve(Elements[0]))
864 addType(Buffer, RTy);
866 bool isPrototyped = true;
867 if (Elements.size() == 2 && !Elements[1])
868 isPrototyped = false;
870 constructSubprogramArguments(Buffer, Elements);
872 // Add prototype flag if we're dealing with a C language and the function has
874 uint16_t Language = getLanguage();
876 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
877 Language == dwarf::DW_LANG_ObjC))
878 addFlag(Buffer, dwarf::DW_AT_prototyped);
880 // Add a DW_AT_calling_convention if this has an explicit convention.
881 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
882 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
885 if (CTy->isLValueReference())
886 addFlag(Buffer, dwarf::DW_AT_reference);
888 if (CTy->isRValueReference())
889 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
892 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
893 if (CTy->isExternalTypeRef()) {
894 StringRef Identifier = CTy->getIdentifier();
895 assert(!Identifier.empty() && "external type ref without identifier");
896 addFlag(Buffer, dwarf::DW_AT_declaration);
897 return addDIETypeSignature(Buffer, dwarf::DW_AT_signature, Identifier);
900 // Add name if not anonymous or intermediate type.
901 StringRef Name = CTy->getName();
903 uint64_t Size = CTy->getSizeInBits() >> 3;
904 uint16_t Tag = Buffer.getTag();
907 case dwarf::DW_TAG_array_type:
908 constructArrayTypeDIE(Buffer, CTy);
910 case dwarf::DW_TAG_enumeration_type:
911 constructEnumTypeDIE(Buffer, CTy);
913 case dwarf::DW_TAG_structure_type:
914 case dwarf::DW_TAG_union_type:
915 case dwarf::DW_TAG_class_type: {
916 // Add elements to structure type.
917 DINodeArray Elements = CTy->getElements();
918 for (const auto *Element : Elements) {
921 if (auto *SP = dyn_cast<DISubprogram>(Element))
922 getOrCreateSubprogramDIE(SP);
923 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
924 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
925 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
926 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
927 } else if (DDTy->isStaticMember()) {
928 getOrCreateStaticMemberDIE(DDTy);
930 constructMemberDIE(Buffer, DDTy);
932 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
933 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
934 StringRef PropertyName = Property->getName();
935 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
936 if (Property->getType())
937 addType(ElemDie, resolve(Property->getType()));
938 addSourceLine(ElemDie, Property);
939 StringRef GetterName = Property->getGetterName();
940 if (!GetterName.empty())
941 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
942 StringRef SetterName = Property->getSetterName();
943 if (!SetterName.empty())
944 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
945 if (unsigned PropertyAttributes = Property->getAttributes())
946 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
951 if (CTy->isAppleBlockExtension())
952 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
954 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
955 // inside C++ composite types to point to the base class with the vtable.
956 if (auto *ContainingType =
957 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
958 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
959 *getOrCreateTypeDIE(ContainingType));
961 if (CTy->isObjcClassComplete())
962 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
964 // Add template parameters to a class, structure or union types.
965 // FIXME: The support isn't in the metadata for this yet.
966 if (Tag == dwarf::DW_TAG_class_type ||
967 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
968 addTemplateParams(Buffer, CTy->getTemplateParams());
976 // Add name if not anonymous or intermediate type.
978 addString(Buffer, dwarf::DW_AT_name, Name);
980 if (Tag == dwarf::DW_TAG_enumeration_type ||
981 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
982 Tag == dwarf::DW_TAG_union_type) {
983 // Add size if non-zero (derived types might be zero-sized.)
984 // TODO: Do we care about size for enum forward declarations?
986 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
987 else if (!CTy->isForwardDecl())
988 // Add zero size if it is not a forward declaration.
989 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
991 // If we're a forward decl, say so.
992 if (CTy->isForwardDecl())
993 addFlag(Buffer, dwarf::DW_AT_declaration);
995 // Add source line info if available.
996 if (!CTy->isForwardDecl())
997 addSourceLine(Buffer, CTy);
999 // No harm in adding the runtime language to the declaration.
1000 unsigned RLang = CTy->getRuntimeLang();
1002 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1005 // Add align info if available.
1006 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1007 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1012 void DwarfUnit::constructTemplateTypeParameterDIE(
1013 DIE &Buffer, const DITemplateTypeParameter *TP) {
1015 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1016 // Add the type if it exists, it could be void and therefore no type.
1018 addType(ParamDIE, resolve(TP->getType()));
1019 if (!TP->getName().empty())
1020 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1023 void DwarfUnit::constructTemplateValueParameterDIE(
1024 DIE &Buffer, const DITemplateValueParameter *VP) {
1025 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1027 // Add the type if there is one, template template and template parameter
1028 // packs will not have a type.
1029 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1030 addType(ParamDIE, resolve(VP->getType()));
1031 if (!VP->getName().empty())
1032 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1033 if (Metadata *Val = VP->getValue()) {
1034 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1035 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1036 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1037 // We cannot describe the location of dllimport'd entities: the
1038 // computation of their address requires loads from the IAT.
1039 if (!GV->hasDLLImportStorageClass()) {
1040 // For declaration non-type template parameters (such as global values
1042 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1043 addOpAddress(*Loc, Asm->getSymbol(GV));
1044 // Emit DW_OP_stack_value to use the address as the immediate value of
1045 // the parameter, rather than a pointer to it.
1046 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1047 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1049 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1050 assert(isa<MDString>(Val));
1051 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1052 cast<MDString>(Val)->getString());
1053 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1054 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1059 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1060 // Construct the context before querying for the existence of the DIE in case
1061 // such construction creates the DIE.
1062 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1064 if (DIE *NDie = getDIE(NS))
1066 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1068 StringRef Name = NS->getName();
1070 addString(NDie, dwarf::DW_AT_name, NS->getName());
1072 Name = "(anonymous namespace)";
1073 DD->addAccelNamespace(Name, NDie);
1074 addGlobalName(Name, NDie, NS->getScope());
1075 addSourceLine(NDie, NS);
1076 if (NS->getExportSymbols())
1077 addFlag(NDie, dwarf::DW_AT_export_symbols);
1081 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1082 // Construct the context before querying for the existence of the DIE in case
1083 // such construction creates the DIE.
1084 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1086 if (DIE *MDie = getDIE(M))
1088 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1090 if (!M->getName().empty()) {
1091 addString(MDie, dwarf::DW_AT_name, M->getName());
1092 addGlobalName(M->getName(), MDie, M->getScope());
1094 if (!M->getConfigurationMacros().empty())
1095 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1096 M->getConfigurationMacros());
1097 if (!M->getIncludePath().empty())
1098 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1099 if (!M->getISysRoot().empty())
1100 addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1105 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1106 // Construct the context before querying for the existence of the DIE in case
1107 // such construction creates the DIE (as is the case for member function
1110 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1112 if (DIE *SPDie = getDIE(SP))
1115 if (auto *SPDecl = SP->getDeclaration()) {
1117 // Add subprogram definitions to the CU die directly.
1118 ContextDIE = &getUnitDie();
1119 // Build the decl now to ensure it precedes the definition.
1120 getOrCreateSubprogramDIE(SPDecl);
1124 // DW_TAG_inlined_subroutine may refer to this DIE.
1125 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1127 // Stop here and fill this in later, depending on whether or not this
1128 // subprogram turns out to have inlined instances or not.
1129 if (SP->isDefinition())
1132 applySubprogramAttributes(SP, SPDie);
1136 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1138 DIE *DeclDie = nullptr;
1139 StringRef DeclLinkageName;
1140 if (auto *SPDecl = SP->getDeclaration()) {
1141 DeclDie = getDIE(SPDecl);
1142 assert(DeclDie && "This DIE should've already been constructed when the "
1143 "definition DIE was created in "
1144 "getOrCreateSubprogramDIE");
1145 // Look at the Decl's linkage name only if we emitted it.
1146 if (DD->useAllLinkageNames())
1147 DeclLinkageName = SPDecl->getLinkageName();
1149 getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1150 unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1151 if (DeclID != DefID)
1152 addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1154 if (SP->getLine() != SPDecl->getLine())
1155 addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1158 // Add function template parameters.
1159 addTemplateParams(SPDie, SP->getTemplateParams());
1161 // Add the linkage name if we have one and it isn't in the Decl.
1162 StringRef LinkageName = SP->getLinkageName();
1163 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1164 LinkageName == DeclLinkageName) &&
1165 "decl has a linkage name and it is different");
1166 if (DeclLinkageName.empty() &&
1167 // Always emit it for abstract subprograms.
1168 (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1169 addLinkageName(SPDie, LinkageName);
1174 // Refer to the function declaration where all the other attributes will be
1176 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1180 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1183 if (applySubprogramDefinitionAttributes(SP, SPDie))
1186 // Constructors and operators for anonymous aggregates do not have names.
1187 if (!SP->getName().empty())
1188 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1190 // Skip the rest of the attributes under -gmlt to save space.
1194 addSourceLine(SPDie, SP);
1196 // Add the prototype if we have a prototype and we have a C like
1198 uint16_t Language = getLanguage();
1199 if (SP->isPrototyped() &&
1200 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1201 Language == dwarf::DW_LANG_ObjC))
1202 addFlag(SPDie, dwarf::DW_AT_prototyped);
1205 DITypeRefArray Args;
1206 if (const DISubroutineType *SPTy = SP->getType()) {
1207 Args = SPTy->getTypeArray();
1211 // Add a DW_AT_calling_convention if this has an explicit convention.
1212 if (CC && CC != dwarf::DW_CC_normal)
1213 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1215 // Add a return type. If this is a type like a C/C++ void type we don't add a
1218 if (auto Ty = resolve(Args[0]))
1221 unsigned VK = SP->getVirtuality();
1223 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1224 if (SP->getVirtualIndex() != -1u) {
1225 DIELoc *Block = getDIELoc();
1226 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1227 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1228 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1230 ContainingTypeMap.insert(
1231 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1234 if (!SP->isDefinition()) {
1235 addFlag(SPDie, dwarf::DW_AT_declaration);
1237 // Add arguments. Do not add arguments for subprogram definition. They will
1238 // be handled while processing variables.
1239 constructSubprogramArguments(SPDie, Args);
1242 if (SP->isArtificial())
1243 addFlag(SPDie, dwarf::DW_AT_artificial);
1245 if (!SP->isLocalToUnit())
1246 addFlag(SPDie, dwarf::DW_AT_external);
1248 if (DD->useAppleExtensionAttributes()) {
1249 if (SP->isOptimized())
1250 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1252 if (unsigned isa = Asm->getISAEncoding())
1253 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1256 if (SP->isLValueReference())
1257 addFlag(SPDie, dwarf::DW_AT_reference);
1259 if (SP->isRValueReference())
1260 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1262 if (SP->isNoReturn())
1263 addFlag(SPDie, dwarf::DW_AT_noreturn);
1265 if (SP->isProtected())
1266 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1267 dwarf::DW_ACCESS_protected);
1268 else if (SP->isPrivate())
1269 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1270 dwarf::DW_ACCESS_private);
1271 else if (SP->isPublic())
1272 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1273 dwarf::DW_ACCESS_public);
1275 if (SP->isExplicit())
1276 addFlag(SPDie, dwarf::DW_AT_explicit);
1278 if (SP->isMainSubprogram())
1279 addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1282 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1284 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1285 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1287 // The LowerBound value defines the lower bounds which is typically zero for
1288 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1289 // Count == -1 then the array is unbounded and we do not emit
1290 // DW_AT_lower_bound and DW_AT_count attributes.
1291 int64_t LowerBound = SR->getLowerBound();
1292 int64_t DefaultLowerBound = getDefaultLowerBound();
1293 int64_t Count = SR->getCount();
1295 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1296 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1299 // FIXME: An unbounded array should reference the expression that defines
1301 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1304 DIE *DwarfUnit::getIndexTyDie() {
1307 // Construct an integer type to use for indexes.
1308 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1309 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1310 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1311 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1312 dwarf::DW_ATE_unsigned);
1316 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1317 if (CTy->isVector())
1318 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1320 // Emit the element type.
1321 addType(Buffer, resolve(CTy->getBaseType()));
1323 // Get an anonymous type for index type.
1324 // FIXME: This type should be passed down from the front end
1325 // as different languages may have different sizes for indexes.
1326 DIE *IdxTy = getIndexTyDie();
1328 // Add subranges to array type.
1329 DINodeArray Elements = CTy->getElements();
1330 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1331 // FIXME: Should this really be such a loose cast?
1332 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1333 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1334 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1338 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1339 DINodeArray Elements = CTy->getElements();
1341 // Add enumerators to enumeration type.
1342 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1343 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1345 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1346 StringRef Name = Enum->getName();
1347 addString(Enumerator, dwarf::DW_AT_name, Name);
1348 int64_t Value = Enum->getValue();
1349 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1353 const DIType *DTy = resolve(CTy->getBaseType());
1355 addType(Buffer, DTy);
1356 addFlag(Buffer, dwarf::DW_AT_enum_class);
1360 void DwarfUnit::constructContainingTypeDIEs() {
1361 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1363 DIE &SPDie = *CI->first;
1364 const DINode *D = CI->second;
1367 DIE *NDie = getDIE(D);
1370 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1374 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1375 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1376 StringRef Name = DT->getName();
1378 addString(MemberDie, dwarf::DW_AT_name, Name);
1380 addType(MemberDie, resolve(DT->getBaseType()));
1382 addSourceLine(MemberDie, DT);
1384 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1386 // For C++, virtual base classes are not at fixed offset. Use following
1387 // expression to extract appropriate offset from vtable.
1388 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1390 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1391 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1392 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1393 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1394 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1395 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1396 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1397 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1399 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1401 uint64_t Size = DT->getSizeInBits();
1402 uint64_t FieldSize = DD->getBaseTypeSize(DT);
1403 uint32_t AlignInBytes = DT->getAlignInBytes();
1404 uint64_t OffsetInBytes;
1406 bool IsBitfield = FieldSize && Size != FieldSize;
1408 // Handle bitfield, assume bytes are 8 bits.
1409 if (DD->useDWARF2Bitfields())
1410 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1411 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1413 uint64_t Offset = DT->getOffsetInBits();
1414 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1415 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1416 // which can't be done with bitfields. Thus we use FieldSize here.
1417 uint32_t AlignInBits = FieldSize;
1418 uint32_t AlignMask = ~(AlignInBits - 1);
1419 // The bits from the start of the storage unit to the start of the field.
1420 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1421 // The byte offset of the field's aligned storage unit inside the struct.
1422 OffsetInBytes = (Offset - StartBitOffset) / 8;
1424 if (DD->useDWARF2Bitfields()) {
1425 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1426 uint64_t FieldOffset = (HiMark - FieldSize);
1427 Offset -= FieldOffset;
1429 // Maybe we need to work from the other end.
1430 if (Asm->getDataLayout().isLittleEndian())
1431 Offset = FieldSize - (Offset + Size);
1433 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1434 OffsetInBytes = FieldOffset >> 3;
1436 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1439 // This is not a bitfield.
1440 OffsetInBytes = DT->getOffsetInBits() / 8;
1442 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1446 if (DD->getDwarfVersion() <= 2) {
1447 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1448 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1449 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1450 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1451 } else if (!IsBitfield || DD->useDWARF2Bitfields())
1452 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1456 if (DT->isProtected())
1457 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1458 dwarf::DW_ACCESS_protected);
1459 else if (DT->isPrivate())
1460 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1461 dwarf::DW_ACCESS_private);
1462 // Otherwise C++ member and base classes are considered public.
1463 else if (DT->isPublic())
1464 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1465 dwarf::DW_ACCESS_public);
1466 if (DT->isVirtual())
1467 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1468 dwarf::DW_VIRTUALITY_virtual);
1470 // Objective-C properties.
1471 if (DINode *PNode = DT->getObjCProperty())
1472 if (DIE *PDie = getDIE(PNode))
1473 MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1474 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1476 if (DT->isArtificial())
1477 addFlag(MemberDie, dwarf::DW_AT_artificial);
1480 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1484 // Construct the context before querying for the existence of the DIE in case
1485 // such construction creates the DIE.
1486 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1487 assert(dwarf::isType(ContextDIE->getTag()) &&
1488 "Static member should belong to a type.");
1490 if (DIE *StaticMemberDIE = getDIE(DT))
1491 return StaticMemberDIE;
1493 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1495 const DIType *Ty = resolve(DT->getBaseType());
1497 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1498 addType(StaticMemberDIE, Ty);
1499 addSourceLine(StaticMemberDIE, DT);
1500 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1501 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1503 // FIXME: We could omit private if the parent is a class_type, and
1504 // public if the parent is something else.
1505 if (DT->isProtected())
1506 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1507 dwarf::DW_ACCESS_protected);
1508 else if (DT->isPrivate())
1509 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1510 dwarf::DW_ACCESS_private);
1511 else if (DT->isPublic())
1512 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1513 dwarf::DW_ACCESS_public);
1515 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1516 addConstantValue(StaticMemberDIE, CI, Ty);
1517 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1518 addConstantFPValue(StaticMemberDIE, CFP);
1520 if (uint32_t AlignInBytes = DT->getAlignInBytes())
1521 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1524 return &StaticMemberDIE;
1527 void DwarfUnit::emitHeader(bool UseOffsets) {
1528 // Emit size of content not including length itself
1529 Asm->OutStreamer->AddComment("Length of Unit");
1530 Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1532 Asm->OutStreamer->AddComment("DWARF version number");
1533 Asm->EmitInt16(DD->getDwarfVersion());
1534 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1536 // We share one abbreviations table across all units so it's always at the
1537 // start of the section. Use a relocatable offset where needed to ensure
1538 // linking doesn't invalidate that offset.
1539 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1543 Asm->emitDwarfSymbolReference(
1544 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1546 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1547 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1550 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1551 DwarfUnit::emitHeader(UseOffsets);
1552 Asm->OutStreamer->AddComment("Type Signature");
1553 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1554 Asm->OutStreamer->AddComment("Type DIE Offset");
1555 // In a skeleton type unit there is no type DIE so emit a zero offset.
1556 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1557 sizeof(Ty->getOffset()));
1560 bool DwarfTypeUnit::isDwoUnit() const {
1561 // Since there are no skeleton type units, all type units are dwo type units
1562 // when split DWARF is being used.
1563 return DD->useSplitDwarf();