DwarfUnit.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  1. //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for constructing a dwarf compile unit.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "DwarfUnit.h"
  13. #include "AddressPool.h"
  14. #include "DwarfCompileUnit.h"
  15. #include "DwarfExpression.h"
  16. #include "llvm/ADT/APFloat.h"
  17. #include "llvm/ADT/APInt.h"
  18. #include "llvm/ADT/iterator_range.h"
  19. #include "llvm/CodeGen/TargetRegisterInfo.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/GlobalValue.h"
  23. #include "llvm/IR/Metadata.h"
  24. #include "llvm/MC/MCAsmInfo.h"
  25. #include "llvm/MC/MCContext.h"
  26. #include "llvm/MC/MCDwarf.h"
  27. #include "llvm/MC/MCSection.h"
  28. #include "llvm/MC/MCStreamer.h"
  29. #include "llvm/Support/Casting.h"
  30. #include "llvm/Target/TargetLoweringObjectFile.h"
  31. #include <cassert>
  32. #include <cstdint>
  33. #include <string>
  34. #include <utility>
  35. using namespace llvm;
  36. #define DEBUG_TYPE "dwarfdebug"
  37. DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP,
  38. DwarfCompileUnit &CU, DIELoc &DIE)
  39. : DwarfExpression(AP.getDwarfVersion(), CU), AP(AP), OutDIE(DIE) {}
  40. void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
  41. CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Op);
  42. }
  43. void DIEDwarfExpression::emitSigned(int64_t Value) {
  44. CU.addSInt(getActiveDIE(), dwarf::DW_FORM_sdata, Value);
  45. }
  46. void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
  47. CU.addUInt(getActiveDIE(), dwarf::DW_FORM_udata, Value);
  48. }
  49. void DIEDwarfExpression::emitData1(uint8_t Value) {
  50. CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Value);
  51. }
  52. void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
  53. CU.addBaseTypeRef(getActiveDIE(), Idx);
  54. }
  55. void DIEDwarfExpression::enableTemporaryBuffer() {
  56. assert(!IsBuffering && "Already buffering?");
  57. IsBuffering = true;
  58. }
  59. void DIEDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
  60. unsigned DIEDwarfExpression::getTemporaryBufferSize() {
  61. return TmpDIE.computeSize(AP.getDwarfFormParams());
  62. }
  63. void DIEDwarfExpression::commitTemporaryBuffer() { OutDIE.takeValues(TmpDIE); }
  64. bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
  65. llvm::Register MachineReg) {
  66. return MachineReg == TRI.getFrameRegister(*AP.MF);
  67. }
  68. DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
  69. AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
  70. : DIEUnit(UnitTag), CUNode(Node), Asm(A), DD(DW), DU(DWU) {}
  71. DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
  72. DwarfDebug *DW, DwarfFile *DWU,
  73. MCDwarfDwoLineTable *SplitLineTable)
  74. : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
  75. SplitLineTable(SplitLineTable) {
  76. }
  77. DwarfUnit::~DwarfUnit() {
  78. for (DIEBlock *B : DIEBlocks)
  79. B->~DIEBlock();
  80. for (DIELoc *L : DIELocs)
  81. L->~DIELoc();
  82. }
  83. int64_t DwarfUnit::getDefaultLowerBound() const {
  84. switch (getLanguage()) {
  85. default:
  86. break;
  87. // The languages below have valid values in all DWARF versions.
  88. case dwarf::DW_LANG_C:
  89. case dwarf::DW_LANG_C89:
  90. case dwarf::DW_LANG_C_plus_plus:
  91. return 0;
  92. case dwarf::DW_LANG_Fortran77:
  93. case dwarf::DW_LANG_Fortran90:
  94. return 1;
  95. // The languages below have valid values only if the DWARF version >= 3.
  96. case dwarf::DW_LANG_C99:
  97. case dwarf::DW_LANG_ObjC:
  98. case dwarf::DW_LANG_ObjC_plus_plus:
  99. if (DD->getDwarfVersion() >= 3)
  100. return 0;
  101. break;
  102. case dwarf::DW_LANG_Fortran95:
  103. if (DD->getDwarfVersion() >= 3)
  104. return 1;
  105. break;
  106. // Starting with DWARF v4, all defined languages have valid values.
  107. case dwarf::DW_LANG_D:
  108. case dwarf::DW_LANG_Java:
  109. case dwarf::DW_LANG_Python:
  110. case dwarf::DW_LANG_UPC:
  111. if (DD->getDwarfVersion() >= 4)
  112. return 0;
  113. break;
  114. case dwarf::DW_LANG_Ada83:
  115. case dwarf::DW_LANG_Ada95:
  116. case dwarf::DW_LANG_Cobol74:
  117. case dwarf::DW_LANG_Cobol85:
  118. case dwarf::DW_LANG_Modula2:
  119. case dwarf::DW_LANG_Pascal83:
  120. case dwarf::DW_LANG_PLI:
  121. if (DD->getDwarfVersion() >= 4)
  122. return 1;
  123. break;
  124. // The languages below are new in DWARF v5.
  125. case dwarf::DW_LANG_BLISS:
  126. case dwarf::DW_LANG_C11:
  127. case dwarf::DW_LANG_C_plus_plus_03:
  128. case dwarf::DW_LANG_C_plus_plus_11:
  129. case dwarf::DW_LANG_C_plus_plus_14:
  130. case dwarf::DW_LANG_Dylan:
  131. case dwarf::DW_LANG_Go:
  132. case dwarf::DW_LANG_Haskell:
  133. case dwarf::DW_LANG_OCaml:
  134. case dwarf::DW_LANG_OpenCL:
  135. case dwarf::DW_LANG_RenderScript:
  136. case dwarf::DW_LANG_Rust:
  137. case dwarf::DW_LANG_Swift:
  138. if (DD->getDwarfVersion() >= 5)
  139. return 0;
  140. break;
  141. case dwarf::DW_LANG_Fortran03:
  142. case dwarf::DW_LANG_Fortran08:
  143. case dwarf::DW_LANG_Julia:
  144. case dwarf::DW_LANG_Modula3:
  145. if (DD->getDwarfVersion() >= 5)
  146. return 1;
  147. break;
  148. }
  149. return -1;
  150. }
  151. /// Check whether the DIE for this MDNode can be shared across CUs.
  152. bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const {
  153. // When the MDNode can be part of the type system, the DIE can be shared
  154. // across CUs.
  155. // Combining type units and cross-CU DIE sharing is lower value (since
  156. // cross-CU DIE sharing is used in LTO and removes type redundancy at that
  157. // level already) but may be implementable for some value in projects
  158. // building multiple independent libraries with LTO and then linking those
  159. // together.
  160. if (isDwoUnit() && !DD->shareAcrossDWOCUs())
  161. return false;
  162. return (isa<DIType>(D) ||
  163. (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
  164. !DD->generateTypeUnits();
  165. }
  166. DIE *DwarfUnit::getDIE(const DINode *D) const {
  167. if (isShareableAcrossCUs(D))
  168. return DU->getDIE(D);
  169. return MDNodeToDieMap.lookup(D);
  170. }
  171. void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
  172. if (isShareableAcrossCUs(Desc)) {
  173. DU->insertDIE(Desc, D);
  174. return;
  175. }
  176. MDNodeToDieMap.insert(std::make_pair(Desc, D));
  177. }
  178. void DwarfUnit::insertDIE(DIE *D) {
  179. MDNodeToDieMap.insert(std::make_pair(nullptr, D));
  180. }
  181. void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
  182. if (DD->getDwarfVersion() >= 4)
  183. addAttribute(Die, Attribute, dwarf::DW_FORM_flag_present, DIEInteger(1));
  184. else
  185. addAttribute(Die, Attribute, dwarf::DW_FORM_flag, DIEInteger(1));
  186. }
  187. void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
  188. std::optional<dwarf::Form> Form, uint64_t Integer) {
  189. if (!Form)
  190. Form = DIEInteger::BestForm(false, Integer);
  191. assert(Form != dwarf::DW_FORM_implicit_const &&
  192. "DW_FORM_implicit_const is used only for signed integers");
  193. addAttribute(Die, Attribute, *Form, DIEInteger(Integer));
  194. }
  195. void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
  196. uint64_t Integer) {
  197. addUInt(Block, (dwarf::Attribute)0, Form, Integer);
  198. }
  199. void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
  200. std::optional<dwarf::Form> Form, int64_t Integer) {
  201. if (!Form)
  202. Form = DIEInteger::BestForm(true, Integer);
  203. addAttribute(Die, Attribute, *Form, DIEInteger(Integer));
  204. }
  205. void DwarfUnit::addSInt(DIELoc &Die, std::optional<dwarf::Form> Form,
  206. int64_t Integer) {
  207. addSInt(Die, (dwarf::Attribute)0, Form, Integer);
  208. }
  209. void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
  210. StringRef String) {
  211. if (CUNode->isDebugDirectivesOnly())
  212. return;
  213. if (DD->useInlineStrings()) {
  214. addAttribute(Die, Attribute, dwarf::DW_FORM_string,
  215. new (DIEValueAllocator)
  216. DIEInlineString(String, DIEValueAllocator));
  217. return;
  218. }
  219. dwarf::Form IxForm =
  220. isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp;
  221. auto StringPoolEntry =
  222. useSegmentedStringOffsetsTable() || IxForm == dwarf::DW_FORM_GNU_str_index
  223. ? DU->getStringPool().getIndexedEntry(*Asm, String)
  224. : DU->getStringPool().getEntry(*Asm, String);
  225. // For DWARF v5 and beyond, use the smallest strx? form possible.
  226. if (useSegmentedStringOffsetsTable()) {
  227. IxForm = dwarf::DW_FORM_strx1;
  228. unsigned Index = StringPoolEntry.getIndex();
  229. if (Index > 0xffffff)
  230. IxForm = dwarf::DW_FORM_strx4;
  231. else if (Index > 0xffff)
  232. IxForm = dwarf::DW_FORM_strx3;
  233. else if (Index > 0xff)
  234. IxForm = dwarf::DW_FORM_strx2;
  235. }
  236. addAttribute(Die, Attribute, IxForm, DIEString(StringPoolEntry));
  237. }
  238. void DwarfUnit::addLabel(DIEValueList &Die, dwarf::Attribute Attribute,
  239. dwarf::Form Form, const MCSymbol *Label) {
  240. addAttribute(Die, Attribute, Form, DIELabel(Label));
  241. }
  242. void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
  243. addLabel(Die, (dwarf::Attribute)0, Form, Label);
  244. }
  245. void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
  246. uint64_t Integer) {
  247. addUInt(Die, Attribute, DD->getDwarfSectionOffsetForm(), Integer);
  248. }
  249. unsigned DwarfTypeUnit::getOrCreateSourceID(const DIFile *File) {
  250. if (!SplitLineTable)
  251. return getCU().getOrCreateSourceID(File);
  252. if (!UsedLineTable) {
  253. UsedLineTable = true;
  254. // This is a split type unit that needs a line table.
  255. addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
  256. }
  257. return SplitLineTable->getFile(
  258. File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
  259. Asm->OutContext.getDwarfVersion(), File->getSource());
  260. }
  261. void DwarfUnit::addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label) {
  262. bool UseAddrOffsetFormOrExpressions =
  263. DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
  264. const MCSymbol *Base = nullptr;
  265. if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
  266. Base = DD->getSectionLabel(&Label->getSection());
  267. uint32_t Index = DD->getAddressPool().getIndex(Base ? Base : Label);
  268. if (DD->getDwarfVersion() >= 5) {
  269. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addrx);
  270. addUInt(Die, dwarf::DW_FORM_addrx, Index);
  271. } else {
  272. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
  273. addUInt(Die, dwarf::DW_FORM_GNU_addr_index, Index);
  274. }
  275. if (Base && Base != Label) {
  276. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_const4u);
  277. addLabelDelta(Die, (dwarf::Attribute)0, Label, Base);
  278. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
  279. }
  280. }
  281. void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
  282. if (DD->getDwarfVersion() >= 5) {
  283. addPoolOpAddress(Die, Sym);
  284. return;
  285. }
  286. if (DD->useSplitDwarf()) {
  287. addPoolOpAddress(Die, Sym);
  288. return;
  289. }
  290. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
  291. addLabel(Die, dwarf::DW_FORM_addr, Sym);
  292. }
  293. void DwarfUnit::addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute,
  294. const MCSymbol *Hi, const MCSymbol *Lo) {
  295. addAttribute(Die, Attribute, dwarf::DW_FORM_data4,
  296. new (DIEValueAllocator) DIEDelta(Hi, Lo));
  297. }
  298. void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
  299. addDIEEntry(Die, Attribute, DIEEntry(Entry));
  300. }
  301. void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
  302. // Flag the type unit reference as a declaration so that if it contains
  303. // members (implicit special members, static data member definitions, member
  304. // declarations for definitions in this CU, etc) consumers don't get confused
  305. // and think this is a full definition.
  306. addFlag(Die, dwarf::DW_AT_declaration);
  307. addAttribute(Die, dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
  308. DIEInteger(Signature));
  309. }
  310. void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
  311. DIEEntry Entry) {
  312. const DIEUnit *CU = Die.getUnit();
  313. const DIEUnit *EntryCU = Entry.getEntry().getUnit();
  314. if (!CU)
  315. // We assume that Die belongs to this CU, if it is not linked to any CU yet.
  316. CU = getUnitDie().getUnit();
  317. if (!EntryCU)
  318. EntryCU = getUnitDie().getUnit();
  319. assert(EntryCU == CU || !DD->useSplitDwarf() || DD->shareAcrossDWOCUs() ||
  320. !static_cast<const DwarfUnit*>(CU)->isDwoUnit());
  321. addAttribute(Die, Attribute,
  322. EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
  323. Entry);
  324. }
  325. DIE &DwarfUnit::createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N) {
  326. DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, Tag));
  327. if (N)
  328. insertDIE(N, &Die);
  329. return Die;
  330. }
  331. void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
  332. Loc->computeSize(Asm->getDwarfFormParams());
  333. DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
  334. addAttribute(Die, Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
  335. }
  336. void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
  337. DIEBlock *Block) {
  338. Block->computeSize(Asm->getDwarfFormParams());
  339. DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
  340. addAttribute(Die, Attribute, Form, Block);
  341. }
  342. void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
  343. DIEBlock *Block) {
  344. addBlock(Die, Attribute, Block->BestForm(), Block);
  345. }
  346. void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, const DIFile *File) {
  347. if (Line == 0)
  348. return;
  349. unsigned FileID = getOrCreateSourceID(File);
  350. addUInt(Die, dwarf::DW_AT_decl_file, std::nullopt, FileID);
  351. addUInt(Die, dwarf::DW_AT_decl_line, std::nullopt, Line);
  352. }
  353. void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
  354. assert(V);
  355. addSourceLine(Die, V->getLine(), V->getFile());
  356. }
  357. void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
  358. assert(G);
  359. addSourceLine(Die, G->getLine(), G->getFile());
  360. }
  361. void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
  362. assert(SP);
  363. addSourceLine(Die, SP->getLine(), SP->getFile());
  364. }
  365. void DwarfUnit::addSourceLine(DIE &Die, const DILabel *L) {
  366. assert(L);
  367. addSourceLine(Die, L->getLine(), L->getFile());
  368. }
  369. void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
  370. assert(Ty);
  371. addSourceLine(Die, Ty->getLine(), Ty->getFile());
  372. }
  373. void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
  374. assert(Ty);
  375. addSourceLine(Die, Ty->getLine(), Ty->getFile());
  376. }
  377. void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
  378. // Pass this down to addConstantValue as an unsigned bag of bits.
  379. addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
  380. }
  381. void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
  382. const DIType *Ty) {
  383. addConstantValue(Die, CI->getValue(), Ty);
  384. }
  385. void DwarfUnit::addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty) {
  386. addConstantValue(Die, DD->isUnsignedDIType(Ty), Val);
  387. }
  388. void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
  389. // FIXME: This is a bit conservative/simple - it emits negative values always
  390. // sign extended to 64 bits rather than minimizing the number of bytes.
  391. addUInt(Die, dwarf::DW_AT_const_value,
  392. Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
  393. }
  394. void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
  395. addConstantValue(Die, Val, DD->isUnsignedDIType(Ty));
  396. }
  397. void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
  398. unsigned CIBitWidth = Val.getBitWidth();
  399. if (CIBitWidth <= 64) {
  400. addConstantValue(Die, Unsigned,
  401. Unsigned ? Val.getZExtValue() : Val.getSExtValue());
  402. return;
  403. }
  404. DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
  405. // Get the raw data form of the large APInt.
  406. const uint64_t *Ptr64 = Val.getRawData();
  407. int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
  408. bool LittleEndian = Asm->getDataLayout().isLittleEndian();
  409. // Output the constant to DWARF one byte at a time.
  410. for (int i = 0; i < NumBytes; i++) {
  411. uint8_t c;
  412. if (LittleEndian)
  413. c = Ptr64[i / 8] >> (8 * (i & 7));
  414. else
  415. c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
  416. addUInt(*Block, dwarf::DW_FORM_data1, c);
  417. }
  418. addBlock(Die, dwarf::DW_AT_const_value, Block);
  419. }
  420. void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
  421. if (!LinkageName.empty())
  422. addString(Die,
  423. DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
  424. : dwarf::DW_AT_MIPS_linkage_name,
  425. GlobalValue::dropLLVMManglingEscape(LinkageName));
  426. }
  427. void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
  428. // Add template parameters.
  429. for (const auto *Element : TParams) {
  430. if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
  431. constructTemplateTypeParameterDIE(Buffer, TTP);
  432. else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
  433. constructTemplateValueParameterDIE(Buffer, TVP);
  434. }
  435. }
  436. /// Add thrown types.
  437. void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
  438. for (const auto *Ty : ThrownTypes) {
  439. DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
  440. addType(TT, cast<DIType>(Ty));
  441. }
  442. }
  443. void DwarfUnit::addAccess(DIE &Die, DINode::DIFlags Flags) {
  444. if ((Flags & DINode::FlagAccessibility) == DINode::FlagProtected)
  445. addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  446. dwarf::DW_ACCESS_protected);
  447. else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPrivate)
  448. addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  449. dwarf::DW_ACCESS_private);
  450. else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPublic)
  451. addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  452. dwarf::DW_ACCESS_public);
  453. }
  454. DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
  455. if (!Context || isa<DIFile>(Context))
  456. return &getUnitDie();
  457. if (auto *T = dyn_cast<DIType>(Context))
  458. return getOrCreateTypeDIE(T);
  459. if (auto *NS = dyn_cast<DINamespace>(Context))
  460. return getOrCreateNameSpace(NS);
  461. if (auto *SP = dyn_cast<DISubprogram>(Context))
  462. return getOrCreateSubprogramDIE(SP);
  463. if (auto *M = dyn_cast<DIModule>(Context))
  464. return getOrCreateModule(M);
  465. return getDIE(Context);
  466. }
  467. DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
  468. auto *Context = Ty->getScope();
  469. DIE *ContextDIE = getOrCreateContextDIE(Context);
  470. if (DIE *TyDIE = getDIE(Ty))
  471. return TyDIE;
  472. // Create new type.
  473. DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
  474. constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
  475. updateAcceleratorTables(Context, Ty, TyDIE);
  476. return &TyDIE;
  477. }
  478. DIE *DwarfUnit::createTypeDIE(const DIScope *Context, DIE &ContextDIE,
  479. const DIType *Ty) {
  480. // Create new type.
  481. DIE &TyDIE = createAndAddDIE(Ty->getTag(), ContextDIE, Ty);
  482. updateAcceleratorTables(Context, Ty, TyDIE);
  483. if (auto *BT = dyn_cast<DIBasicType>(Ty))
  484. constructTypeDIE(TyDIE, BT);
  485. else if (auto *ST = dyn_cast<DIStringType>(Ty))
  486. constructTypeDIE(TyDIE, ST);
  487. else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
  488. constructTypeDIE(TyDIE, STy);
  489. else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
  490. if (DD->generateTypeUnits() && !Ty->isForwardDecl() &&
  491. (Ty->getRawName() || CTy->getRawIdentifier())) {
  492. // Skip updating the accelerator tables since this is not the full type.
  493. if (MDString *TypeId = CTy->getRawIdentifier())
  494. DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
  495. else
  496. finishNonUnitTypeDIE(TyDIE, CTy);
  497. return &TyDIE;
  498. }
  499. constructTypeDIE(TyDIE, CTy);
  500. } else {
  501. constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
  502. }
  503. return &TyDIE;
  504. }
  505. DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
  506. if (!TyNode)
  507. return nullptr;
  508. auto *Ty = cast<DIType>(TyNode);
  509. // DW_TAG_restrict_type is not supported in DWARF2
  510. if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
  511. return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
  512. // DW_TAG_atomic_type is not supported in DWARF < 5
  513. if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
  514. return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
  515. // Construct the context before querying for the existence of the DIE in case
  516. // such construction creates the DIE.
  517. auto *Context = Ty->getScope();
  518. DIE *ContextDIE = getOrCreateContextDIE(Context);
  519. assert(ContextDIE);
  520. if (DIE *TyDIE = getDIE(Ty))
  521. return TyDIE;
  522. return static_cast<DwarfUnit *>(ContextDIE->getUnit())
  523. ->createTypeDIE(Context, *ContextDIE, Ty);
  524. }
  525. void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
  526. const DIType *Ty, const DIE &TyDIE) {
  527. if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
  528. bool IsImplementation = false;
  529. if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
  530. // A runtime language of 0 actually means C/C++ and that any
  531. // non-negative value is some version of Objective-C/C++.
  532. IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
  533. }
  534. unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
  535. DD->addAccelType(*CUNode, Ty->getName(), TyDIE, Flags);
  536. if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
  537. isa<DINamespace>(Context) || isa<DICommonBlock>(Context))
  538. addGlobalType(Ty, TyDIE, Context);
  539. }
  540. }
  541. void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
  542. dwarf::Attribute Attribute) {
  543. assert(Ty && "Trying to add a type that doesn't exist?");
  544. addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
  545. }
  546. std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
  547. if (!Context)
  548. return "";
  549. // FIXME: Decide whether to implement this for non-C++ languages.
  550. if (!dwarf::isCPlusPlus((dwarf::SourceLanguage)getLanguage()))
  551. return "";
  552. std::string CS;
  553. SmallVector<const DIScope *, 1> Parents;
  554. while (!isa<DICompileUnit>(Context)) {
  555. Parents.push_back(Context);
  556. if (const DIScope *S = Context->getScope())
  557. Context = S;
  558. else
  559. // Structure, etc types will have a NULL context if they're at the top
  560. // level.
  561. break;
  562. }
  563. // Reverse iterate over our list to go from the outermost construct to the
  564. // innermost.
  565. for (const DIScope *Ctx : llvm::reverse(Parents)) {
  566. StringRef Name = Ctx->getName();
  567. if (Name.empty() && isa<DINamespace>(Ctx))
  568. Name = "(anonymous namespace)";
  569. if (!Name.empty()) {
  570. CS += Name;
  571. CS += "::";
  572. }
  573. }
  574. return CS;
  575. }
  576. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
  577. // Get core information.
  578. StringRef Name = BTy->getName();
  579. // Add name if not anonymous or intermediate type.
  580. if (!Name.empty())
  581. addString(Buffer, dwarf::DW_AT_name, Name);
  582. // An unspecified type only has a name attribute.
  583. if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
  584. return;
  585. if (BTy->getTag() != dwarf::DW_TAG_string_type)
  586. addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
  587. BTy->getEncoding());
  588. uint64_t Size = BTy->getSizeInBits() >> 3;
  589. addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size);
  590. if (BTy->isBigEndian())
  591. addUInt(Buffer, dwarf::DW_AT_endianity, std::nullopt, dwarf::DW_END_big);
  592. else if (BTy->isLittleEndian())
  593. addUInt(Buffer, dwarf::DW_AT_endianity, std::nullopt, dwarf::DW_END_little);
  594. }
  595. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIStringType *STy) {
  596. // Get core information.
  597. StringRef Name = STy->getName();
  598. // Add name if not anonymous or intermediate type.
  599. if (!Name.empty())
  600. addString(Buffer, dwarf::DW_AT_name, Name);
  601. if (DIVariable *Var = STy->getStringLength()) {
  602. if (auto *VarDIE = getDIE(Var))
  603. addDIEEntry(Buffer, dwarf::DW_AT_string_length, *VarDIE);
  604. } else if (DIExpression *Expr = STy->getStringLengthExp()) {
  605. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  606. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  607. // This is to describe the memory location of the
  608. // length of a Fortran deferred length string, so
  609. // lock it down as such.
  610. DwarfExpr.setMemoryLocationKind();
  611. DwarfExpr.addExpression(Expr);
  612. addBlock(Buffer, dwarf::DW_AT_string_length, DwarfExpr.finalize());
  613. } else {
  614. uint64_t Size = STy->getSizeInBits() >> 3;
  615. addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size);
  616. }
  617. if (DIExpression *Expr = STy->getStringLocationExp()) {
  618. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  619. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  620. // This is to describe the memory location of the
  621. // string, so lock it down as such.
  622. DwarfExpr.setMemoryLocationKind();
  623. DwarfExpr.addExpression(Expr);
  624. addBlock(Buffer, dwarf::DW_AT_data_location, DwarfExpr.finalize());
  625. }
  626. if (STy->getEncoding()) {
  627. // For eventual Unicode support.
  628. addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
  629. STy->getEncoding());
  630. }
  631. }
  632. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
  633. // Get core information.
  634. StringRef Name = DTy->getName();
  635. uint64_t Size = DTy->getSizeInBits() >> 3;
  636. uint16_t Tag = Buffer.getTag();
  637. // Map to main type, void will not have a type.
  638. const DIType *FromTy = DTy->getBaseType();
  639. if (FromTy)
  640. addType(Buffer, FromTy);
  641. // Add name if not anonymous or intermediate type.
  642. if (!Name.empty())
  643. addString(Buffer, dwarf::DW_AT_name, Name);
  644. addAnnotation(Buffer, DTy->getAnnotations());
  645. // If alignment is specified for a typedef , create and insert DW_AT_alignment
  646. // attribute in DW_TAG_typedef DIE.
  647. if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) {
  648. uint32_t AlignInBytes = DTy->getAlignInBytes();
  649. if (AlignInBytes > 0)
  650. addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  651. AlignInBytes);
  652. }
  653. // Add size if non-zero (derived types might be zero-sized.)
  654. if (Size && Tag != dwarf::DW_TAG_pointer_type
  655. && Tag != dwarf::DW_TAG_ptr_to_member_type
  656. && Tag != dwarf::DW_TAG_reference_type
  657. && Tag != dwarf::DW_TAG_rvalue_reference_type)
  658. addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size);
  659. if (Tag == dwarf::DW_TAG_ptr_to_member_type)
  660. addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
  661. *getOrCreateTypeDIE(cast<DIDerivedType>(DTy)->getClassType()));
  662. addAccess(Buffer, DTy->getFlags());
  663. // Add source line info if available and TyDesc is not a forward declaration.
  664. if (!DTy->isForwardDecl())
  665. addSourceLine(Buffer, DTy);
  666. // If DWARF address space value is other than None, add it. The IR
  667. // verifier checks that DWARF address space only exists for pointer
  668. // or reference types.
  669. if (DTy->getDWARFAddressSpace())
  670. addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
  671. *DTy->getDWARFAddressSpace());
  672. }
  673. void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
  674. for (unsigned i = 1, N = Args.size(); i < N; ++i) {
  675. const DIType *Ty = Args[i];
  676. if (!Ty) {
  677. assert(i == N-1 && "Unspecified parameter must be the last argument");
  678. createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
  679. } else {
  680. DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
  681. addType(Arg, Ty);
  682. if (Ty->isArtificial())
  683. addFlag(Arg, dwarf::DW_AT_artificial);
  684. }
  685. }
  686. }
  687. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
  688. // Add return type. A void return won't have a type.
  689. auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
  690. if (Elements.size())
  691. if (auto RTy = Elements[0])
  692. addType(Buffer, RTy);
  693. bool isPrototyped = true;
  694. if (Elements.size() == 2 && !Elements[1])
  695. isPrototyped = false;
  696. constructSubprogramArguments(Buffer, Elements);
  697. // Add prototype flag if we're dealing with a C language and the function has
  698. // been prototyped.
  699. if (isPrototyped && dwarf::isC((dwarf::SourceLanguage)getLanguage()))
  700. addFlag(Buffer, dwarf::DW_AT_prototyped);
  701. // Add a DW_AT_calling_convention if this has an explicit convention.
  702. if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
  703. addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
  704. CTy->getCC());
  705. if (CTy->isLValueReference())
  706. addFlag(Buffer, dwarf::DW_AT_reference);
  707. if (CTy->isRValueReference())
  708. addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
  709. }
  710. void DwarfUnit::addAnnotation(DIE &Buffer, DINodeArray Annotations) {
  711. if (!Annotations)
  712. return;
  713. for (const Metadata *Annotation : Annotations->operands()) {
  714. const MDNode *MD = cast<MDNode>(Annotation);
  715. const MDString *Name = cast<MDString>(MD->getOperand(0));
  716. const auto &Value = MD->getOperand(1);
  717. DIE &AnnotationDie = createAndAddDIE(dwarf::DW_TAG_LLVM_annotation, Buffer);
  718. addString(AnnotationDie, dwarf::DW_AT_name, Name->getString());
  719. if (const auto *Data = dyn_cast<MDString>(Value))
  720. addString(AnnotationDie, dwarf::DW_AT_const_value, Data->getString());
  721. else if (const auto *Data = dyn_cast<ConstantAsMetadata>(Value))
  722. addConstantValue(AnnotationDie, Data->getValue()->getUniqueInteger(),
  723. /*Unsigned=*/true);
  724. else
  725. assert(false && "Unsupported annotation value type");
  726. }
  727. }
  728. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
  729. // Add name if not anonymous or intermediate type.
  730. StringRef Name = CTy->getName();
  731. uint64_t Size = CTy->getSizeInBits() >> 3;
  732. uint16_t Tag = Buffer.getTag();
  733. switch (Tag) {
  734. case dwarf::DW_TAG_array_type:
  735. constructArrayTypeDIE(Buffer, CTy);
  736. break;
  737. case dwarf::DW_TAG_enumeration_type:
  738. constructEnumTypeDIE(Buffer, CTy);
  739. break;
  740. case dwarf::DW_TAG_variant_part:
  741. case dwarf::DW_TAG_structure_type:
  742. case dwarf::DW_TAG_union_type:
  743. case dwarf::DW_TAG_class_type:
  744. case dwarf::DW_TAG_namelist: {
  745. // Emit the discriminator for a variant part.
  746. DIDerivedType *Discriminator = nullptr;
  747. if (Tag == dwarf::DW_TAG_variant_part) {
  748. Discriminator = CTy->getDiscriminator();
  749. if (Discriminator) {
  750. // DWARF says:
  751. // If the variant part has a discriminant, the discriminant is
  752. // represented by a separate debugging information entry which is
  753. // a child of the variant part entry.
  754. DIE &DiscMember = constructMemberDIE(Buffer, Discriminator);
  755. addDIEEntry(Buffer, dwarf::DW_AT_discr, DiscMember);
  756. }
  757. }
  758. // Add template parameters to a class, structure or union types.
  759. if (Tag == dwarf::DW_TAG_class_type ||
  760. Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
  761. addTemplateParams(Buffer, CTy->getTemplateParams());
  762. // Add elements to structure type.
  763. DINodeArray Elements = CTy->getElements();
  764. for (const auto *Element : Elements) {
  765. if (!Element)
  766. continue;
  767. if (auto *SP = dyn_cast<DISubprogram>(Element))
  768. getOrCreateSubprogramDIE(SP);
  769. else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
  770. if (DDTy->getTag() == dwarf::DW_TAG_friend) {
  771. DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
  772. addType(ElemDie, DDTy->getBaseType(), dwarf::DW_AT_friend);
  773. } else if (DDTy->isStaticMember()) {
  774. getOrCreateStaticMemberDIE(DDTy);
  775. } else if (Tag == dwarf::DW_TAG_variant_part) {
  776. // When emitting a variant part, wrap each member in
  777. // DW_TAG_variant.
  778. DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
  779. if (const ConstantInt *CI =
  780. dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) {
  781. if (DD->isUnsignedDIType(Discriminator->getBaseType()))
  782. addUInt(Variant, dwarf::DW_AT_discr_value, std::nullopt,
  783. CI->getZExtValue());
  784. else
  785. addSInt(Variant, dwarf::DW_AT_discr_value, std::nullopt,
  786. CI->getSExtValue());
  787. }
  788. constructMemberDIE(Variant, DDTy);
  789. } else {
  790. constructMemberDIE(Buffer, DDTy);
  791. }
  792. } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
  793. DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
  794. StringRef PropertyName = Property->getName();
  795. addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
  796. if (Property->getType())
  797. addType(ElemDie, Property->getType());
  798. addSourceLine(ElemDie, Property);
  799. StringRef GetterName = Property->getGetterName();
  800. if (!GetterName.empty())
  801. addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
  802. StringRef SetterName = Property->getSetterName();
  803. if (!SetterName.empty())
  804. addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
  805. if (unsigned PropertyAttributes = Property->getAttributes())
  806. addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, std::nullopt,
  807. PropertyAttributes);
  808. } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
  809. if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
  810. DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer);
  811. constructTypeDIE(VariantPart, Composite);
  812. }
  813. } else if (Tag == dwarf::DW_TAG_namelist) {
  814. auto *Var = dyn_cast<DINode>(Element);
  815. auto *VarDIE = getDIE(Var);
  816. if (VarDIE) {
  817. DIE &ItemDie = createAndAddDIE(dwarf::DW_TAG_namelist_item, Buffer);
  818. addDIEEntry(ItemDie, dwarf::DW_AT_namelist_item, *VarDIE);
  819. }
  820. }
  821. }
  822. if (CTy->isAppleBlockExtension())
  823. addFlag(Buffer, dwarf::DW_AT_APPLE_block);
  824. if (CTy->getExportSymbols())
  825. addFlag(Buffer, dwarf::DW_AT_export_symbols);
  826. // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
  827. // inside C++ composite types to point to the base class with the vtable.
  828. // Rust uses DW_AT_containing_type to link a vtable to the type
  829. // for which it was created.
  830. if (auto *ContainingType = CTy->getVTableHolder())
  831. addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
  832. *getOrCreateTypeDIE(ContainingType));
  833. if (CTy->isObjcClassComplete())
  834. addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
  835. // Add the type's non-standard calling convention.
  836. // DW_CC_pass_by_value/DW_CC_pass_by_reference are introduced in DWARF 5.
  837. if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 5) {
  838. uint8_t CC = 0;
  839. if (CTy->isTypePassByValue())
  840. CC = dwarf::DW_CC_pass_by_value;
  841. else if (CTy->isTypePassByReference())
  842. CC = dwarf::DW_CC_pass_by_reference;
  843. if (CC)
  844. addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
  845. CC);
  846. }
  847. break;
  848. }
  849. default:
  850. break;
  851. }
  852. // Add name if not anonymous or intermediate type.
  853. if (!Name.empty())
  854. addString(Buffer, dwarf::DW_AT_name, Name);
  855. addAnnotation(Buffer, CTy->getAnnotations());
  856. if (Tag == dwarf::DW_TAG_enumeration_type ||
  857. Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
  858. Tag == dwarf::DW_TAG_union_type) {
  859. // Add size if non-zero (derived types might be zero-sized.)
  860. // Ignore the size if it's a non-enum forward decl.
  861. // TODO: Do we care about size for enum forward declarations?
  862. if (Size &&
  863. (!CTy->isForwardDecl() || Tag == dwarf::DW_TAG_enumeration_type))
  864. addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size);
  865. else if (!CTy->isForwardDecl())
  866. // Add zero size if it is not a forward declaration.
  867. addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, 0);
  868. // If we're a forward decl, say so.
  869. if (CTy->isForwardDecl())
  870. addFlag(Buffer, dwarf::DW_AT_declaration);
  871. // Add accessibility info if available.
  872. addAccess(Buffer, CTy->getFlags());
  873. // Add source line info if available.
  874. if (!CTy->isForwardDecl())
  875. addSourceLine(Buffer, CTy);
  876. // No harm in adding the runtime language to the declaration.
  877. unsigned RLang = CTy->getRuntimeLang();
  878. if (RLang)
  879. addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
  880. RLang);
  881. // Add align info if available.
  882. if (uint32_t AlignInBytes = CTy->getAlignInBytes())
  883. addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  884. AlignInBytes);
  885. }
  886. }
  887. void DwarfUnit::constructTemplateTypeParameterDIE(
  888. DIE &Buffer, const DITemplateTypeParameter *TP) {
  889. DIE &ParamDIE =
  890. createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
  891. // Add the type if it exists, it could be void and therefore no type.
  892. if (TP->getType())
  893. addType(ParamDIE, TP->getType());
  894. if (!TP->getName().empty())
  895. addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
  896. if (TP->isDefault() && isCompatibleWithVersion(5))
  897. addFlag(ParamDIE, dwarf::DW_AT_default_value);
  898. }
  899. void DwarfUnit::constructTemplateValueParameterDIE(
  900. DIE &Buffer, const DITemplateValueParameter *VP) {
  901. DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
  902. // Add the type if there is one, template template and template parameter
  903. // packs will not have a type.
  904. if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
  905. addType(ParamDIE, VP->getType());
  906. if (!VP->getName().empty())
  907. addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
  908. if (VP->isDefault() && isCompatibleWithVersion(5))
  909. addFlag(ParamDIE, dwarf::DW_AT_default_value);
  910. if (Metadata *Val = VP->getValue()) {
  911. if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
  912. addConstantValue(ParamDIE, CI, VP->getType());
  913. else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
  914. // We cannot describe the location of dllimport'd entities: the
  915. // computation of their address requires loads from the IAT.
  916. if (!GV->hasDLLImportStorageClass()) {
  917. // For declaration non-type template parameters (such as global values
  918. // and functions)
  919. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  920. addOpAddress(*Loc, Asm->getSymbol(GV));
  921. // Emit DW_OP_stack_value to use the address as the immediate value of
  922. // the parameter, rather than a pointer to it.
  923. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
  924. addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
  925. }
  926. } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
  927. assert(isa<MDString>(Val));
  928. addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
  929. cast<MDString>(Val)->getString());
  930. } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
  931. addTemplateParams(ParamDIE, cast<MDTuple>(Val));
  932. }
  933. }
  934. }
  935. DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
  936. // Construct the context before querying for the existence of the DIE in case
  937. // such construction creates the DIE.
  938. DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
  939. if (DIE *NDie = getDIE(NS))
  940. return NDie;
  941. DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
  942. StringRef Name = NS->getName();
  943. if (!Name.empty())
  944. addString(NDie, dwarf::DW_AT_name, NS->getName());
  945. else
  946. Name = "(anonymous namespace)";
  947. DD->addAccelNamespace(*CUNode, Name, NDie);
  948. addGlobalName(Name, NDie, NS->getScope());
  949. if (NS->getExportSymbols())
  950. addFlag(NDie, dwarf::DW_AT_export_symbols);
  951. return &NDie;
  952. }
  953. DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
  954. // Construct the context before querying for the existence of the DIE in case
  955. // such construction creates the DIE.
  956. DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
  957. if (DIE *MDie = getDIE(M))
  958. return MDie;
  959. DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
  960. if (!M->getName().empty()) {
  961. addString(MDie, dwarf::DW_AT_name, M->getName());
  962. addGlobalName(M->getName(), MDie, M->getScope());
  963. }
  964. if (!M->getConfigurationMacros().empty())
  965. addString(MDie, dwarf::DW_AT_LLVM_config_macros,
  966. M->getConfigurationMacros());
  967. if (!M->getIncludePath().empty())
  968. addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
  969. if (!M->getAPINotesFile().empty())
  970. addString(MDie, dwarf::DW_AT_LLVM_apinotes, M->getAPINotesFile());
  971. if (M->getFile())
  972. addUInt(MDie, dwarf::DW_AT_decl_file, std::nullopt,
  973. getOrCreateSourceID(M->getFile()));
  974. if (M->getLineNo())
  975. addUInt(MDie, dwarf::DW_AT_decl_line, std::nullopt, M->getLineNo());
  976. if (M->getIsDecl())
  977. addFlag(MDie, dwarf::DW_AT_declaration);
  978. return &MDie;
  979. }
  980. DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
  981. // Construct the context before querying for the existence of the DIE in case
  982. // such construction creates the DIE (as is the case for member function
  983. // declarations).
  984. DIE *ContextDIE =
  985. Minimal ? &getUnitDie() : getOrCreateContextDIE(SP->getScope());
  986. if (DIE *SPDie = getDIE(SP))
  987. return SPDie;
  988. if (auto *SPDecl = SP->getDeclaration()) {
  989. if (!Minimal) {
  990. // Add subprogram definitions to the CU die directly.
  991. ContextDIE = &getUnitDie();
  992. // Build the decl now to ensure it precedes the definition.
  993. getOrCreateSubprogramDIE(SPDecl);
  994. }
  995. }
  996. // DW_TAG_inlined_subroutine may refer to this DIE.
  997. DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
  998. // Stop here and fill this in later, depending on whether or not this
  999. // subprogram turns out to have inlined instances or not.
  1000. if (SP->isDefinition())
  1001. return &SPDie;
  1002. static_cast<DwarfUnit *>(SPDie.getUnit())
  1003. ->applySubprogramAttributes(SP, SPDie);
  1004. return &SPDie;
  1005. }
  1006. bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
  1007. DIE &SPDie, bool Minimal) {
  1008. DIE *DeclDie = nullptr;
  1009. StringRef DeclLinkageName;
  1010. if (auto *SPDecl = SP->getDeclaration()) {
  1011. if (!Minimal) {
  1012. DITypeRefArray DeclArgs, DefinitionArgs;
  1013. DeclArgs = SPDecl->getType()->getTypeArray();
  1014. DefinitionArgs = SP->getType()->getTypeArray();
  1015. if (DeclArgs.size() && DefinitionArgs.size())
  1016. if (DefinitionArgs[0] != nullptr && DeclArgs[0] != DefinitionArgs[0])
  1017. addType(SPDie, DefinitionArgs[0]);
  1018. DeclDie = getDIE(SPDecl);
  1019. assert(DeclDie && "This DIE should've already been constructed when the "
  1020. "definition DIE was created in "
  1021. "getOrCreateSubprogramDIE");
  1022. // Look at the Decl's linkage name only if we emitted it.
  1023. if (DD->useAllLinkageNames())
  1024. DeclLinkageName = SPDecl->getLinkageName();
  1025. unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
  1026. unsigned DefID = getOrCreateSourceID(SP->getFile());
  1027. if (DeclID != DefID)
  1028. addUInt(SPDie, dwarf::DW_AT_decl_file, std::nullopt, DefID);
  1029. if (SP->getLine() != SPDecl->getLine())
  1030. addUInt(SPDie, dwarf::DW_AT_decl_line, std::nullopt, SP->getLine());
  1031. }
  1032. }
  1033. // Add function template parameters.
  1034. addTemplateParams(SPDie, SP->getTemplateParams());
  1035. // Add the linkage name if we have one and it isn't in the Decl.
  1036. StringRef LinkageName = SP->getLinkageName();
  1037. assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
  1038. LinkageName == DeclLinkageName) &&
  1039. "decl has a linkage name and it is different");
  1040. if (DeclLinkageName.empty() &&
  1041. // Always emit it for abstract subprograms.
  1042. (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
  1043. addLinkageName(SPDie, LinkageName);
  1044. if (!DeclDie)
  1045. return false;
  1046. // Refer to the function declaration where all the other attributes will be
  1047. // found.
  1048. addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
  1049. return true;
  1050. }
  1051. void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
  1052. bool SkipSPAttributes) {
  1053. // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
  1054. // and its source location.
  1055. bool SkipSPSourceLocation = SkipSPAttributes &&
  1056. !CUNode->getDebugInfoForProfiling();
  1057. if (!SkipSPSourceLocation)
  1058. if (applySubprogramDefinitionAttributes(SP, SPDie, SkipSPAttributes))
  1059. return;
  1060. // Constructors and operators for anonymous aggregates do not have names.
  1061. if (!SP->getName().empty())
  1062. addString(SPDie, dwarf::DW_AT_name, SP->getName());
  1063. addAnnotation(SPDie, SP->getAnnotations());
  1064. if (!SkipSPSourceLocation)
  1065. addSourceLine(SPDie, SP);
  1066. // Skip the rest of the attributes under -gmlt to save space.
  1067. if (SkipSPAttributes)
  1068. return;
  1069. // Add the prototype if we have a prototype and we have a C like
  1070. // language.
  1071. if (SP->isPrototyped() && dwarf::isC((dwarf::SourceLanguage)getLanguage()))
  1072. addFlag(SPDie, dwarf::DW_AT_prototyped);
  1073. if (SP->isObjCDirect())
  1074. addFlag(SPDie, dwarf::DW_AT_APPLE_objc_direct);
  1075. unsigned CC = 0;
  1076. DITypeRefArray Args;
  1077. if (const DISubroutineType *SPTy = SP->getType()) {
  1078. Args = SPTy->getTypeArray();
  1079. CC = SPTy->getCC();
  1080. }
  1081. // Add a DW_AT_calling_convention if this has an explicit convention.
  1082. if (CC && CC != dwarf::DW_CC_normal)
  1083. addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
  1084. // Add a return type. If this is a type like a C/C++ void type we don't add a
  1085. // return type.
  1086. if (Args.size())
  1087. if (auto Ty = Args[0])
  1088. addType(SPDie, Ty);
  1089. unsigned VK = SP->getVirtuality();
  1090. if (VK) {
  1091. addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
  1092. if (SP->getVirtualIndex() != -1u) {
  1093. DIELoc *Block = getDIELoc();
  1094. addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
  1095. addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
  1096. addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
  1097. }
  1098. ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType()));
  1099. }
  1100. if (!SP->isDefinition()) {
  1101. addFlag(SPDie, dwarf::DW_AT_declaration);
  1102. // Add arguments. Do not add arguments for subprogram definition. They will
  1103. // be handled while processing variables.
  1104. constructSubprogramArguments(SPDie, Args);
  1105. }
  1106. addThrownTypes(SPDie, SP->getThrownTypes());
  1107. if (SP->isArtificial())
  1108. addFlag(SPDie, dwarf::DW_AT_artificial);
  1109. if (!SP->isLocalToUnit())
  1110. addFlag(SPDie, dwarf::DW_AT_external);
  1111. if (DD->useAppleExtensionAttributes()) {
  1112. if (SP->isOptimized())
  1113. addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
  1114. if (unsigned isa = Asm->getISAEncoding())
  1115. addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
  1116. }
  1117. if (SP->isLValueReference())
  1118. addFlag(SPDie, dwarf::DW_AT_reference);
  1119. if (SP->isRValueReference())
  1120. addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
  1121. if (SP->isNoReturn())
  1122. addFlag(SPDie, dwarf::DW_AT_noreturn);
  1123. addAccess(SPDie, SP->getFlags());
  1124. if (SP->isExplicit())
  1125. addFlag(SPDie, dwarf::DW_AT_explicit);
  1126. if (SP->isMainSubprogram())
  1127. addFlag(SPDie, dwarf::DW_AT_main_subprogram);
  1128. if (SP->isPure())
  1129. addFlag(SPDie, dwarf::DW_AT_pure);
  1130. if (SP->isElemental())
  1131. addFlag(SPDie, dwarf::DW_AT_elemental);
  1132. if (SP->isRecursive())
  1133. addFlag(SPDie, dwarf::DW_AT_recursive);
  1134. if (!SP->getTargetFuncName().empty())
  1135. addString(SPDie, dwarf::DW_AT_trampoline, SP->getTargetFuncName());
  1136. if (DD->getDwarfVersion() >= 5 && SP->isDeleted())
  1137. addFlag(SPDie, dwarf::DW_AT_deleted);
  1138. }
  1139. void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
  1140. DIE *IndexTy) {
  1141. DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
  1142. addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
  1143. // The LowerBound value defines the lower bounds which is typically zero for
  1144. // C/C++. The Count value is the number of elements. Values are 64 bit. If
  1145. // Count == -1 then the array is unbounded and we do not emit
  1146. // DW_AT_lower_bound and DW_AT_count attributes.
  1147. int64_t DefaultLowerBound = getDefaultLowerBound();
  1148. auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
  1149. DISubrange::BoundType Bound) -> void {
  1150. if (auto *BV = Bound.dyn_cast<DIVariable *>()) {
  1151. if (auto *VarDIE = getDIE(BV))
  1152. addDIEEntry(DW_Subrange, Attr, *VarDIE);
  1153. } else if (auto *BE = Bound.dyn_cast<DIExpression *>()) {
  1154. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1155. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  1156. DwarfExpr.setMemoryLocationKind();
  1157. DwarfExpr.addExpression(BE);
  1158. addBlock(DW_Subrange, Attr, DwarfExpr.finalize());
  1159. } else if (auto *BI = Bound.dyn_cast<ConstantInt *>()) {
  1160. if (Attr == dwarf::DW_AT_count) {
  1161. if (BI->getSExtValue() != -1)
  1162. addUInt(DW_Subrange, Attr, std::nullopt, BI->getSExtValue());
  1163. } else if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
  1164. BI->getSExtValue() != DefaultLowerBound)
  1165. addSInt(DW_Subrange, Attr, dwarf::DW_FORM_sdata, BI->getSExtValue());
  1166. }
  1167. };
  1168. AddBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound());
  1169. AddBoundTypeEntry(dwarf::DW_AT_count, SR->getCount());
  1170. AddBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound());
  1171. AddBoundTypeEntry(dwarf::DW_AT_byte_stride, SR->getStride());
  1172. }
  1173. void DwarfUnit::constructGenericSubrangeDIE(DIE &Buffer,
  1174. const DIGenericSubrange *GSR,
  1175. DIE *IndexTy) {
  1176. DIE &DwGenericSubrange =
  1177. createAndAddDIE(dwarf::DW_TAG_generic_subrange, Buffer);
  1178. addDIEEntry(DwGenericSubrange, dwarf::DW_AT_type, *IndexTy);
  1179. int64_t DefaultLowerBound = getDefaultLowerBound();
  1180. auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
  1181. DIGenericSubrange::BoundType Bound) -> void {
  1182. if (auto *BV = Bound.dyn_cast<DIVariable *>()) {
  1183. if (auto *VarDIE = getDIE(BV))
  1184. addDIEEntry(DwGenericSubrange, Attr, *VarDIE);
  1185. } else if (auto *BE = Bound.dyn_cast<DIExpression *>()) {
  1186. if (BE->isConstant() &&
  1187. DIExpression::SignedOrUnsignedConstant::SignedConstant ==
  1188. *BE->isConstant()) {
  1189. if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
  1190. static_cast<int64_t>(BE->getElement(1)) != DefaultLowerBound)
  1191. addSInt(DwGenericSubrange, Attr, dwarf::DW_FORM_sdata,
  1192. BE->getElement(1));
  1193. } else {
  1194. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1195. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  1196. DwarfExpr.setMemoryLocationKind();
  1197. DwarfExpr.addExpression(BE);
  1198. addBlock(DwGenericSubrange, Attr, DwarfExpr.finalize());
  1199. }
  1200. }
  1201. };
  1202. AddBoundTypeEntry(dwarf::DW_AT_lower_bound, GSR->getLowerBound());
  1203. AddBoundTypeEntry(dwarf::DW_AT_count, GSR->getCount());
  1204. AddBoundTypeEntry(dwarf::DW_AT_upper_bound, GSR->getUpperBound());
  1205. AddBoundTypeEntry(dwarf::DW_AT_byte_stride, GSR->getStride());
  1206. }
  1207. DIE *DwarfUnit::getIndexTyDie() {
  1208. if (IndexTyDie)
  1209. return IndexTyDie;
  1210. // Construct an integer type to use for indexes.
  1211. IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
  1212. StringRef Name = "__ARRAY_SIZE_TYPE__";
  1213. addString(*IndexTyDie, dwarf::DW_AT_name, Name);
  1214. addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, std::nullopt, sizeof(int64_t));
  1215. addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
  1216. dwarf::getArrayIndexTypeEncoding(
  1217. (dwarf::SourceLanguage)getLanguage()));
  1218. DD->addAccelType(*CUNode, Name, *IndexTyDie, /*Flags*/ 0);
  1219. return IndexTyDie;
  1220. }
  1221. /// Returns true if the vector's size differs from the sum of sizes of elements
  1222. /// the user specified. This can occur if the vector has been rounded up to
  1223. /// fit memory alignment constraints.
  1224. static bool hasVectorBeenPadded(const DICompositeType *CTy) {
  1225. assert(CTy && CTy->isVector() && "Composite type is not a vector");
  1226. const uint64_t ActualSize = CTy->getSizeInBits();
  1227. // Obtain the size of each element in the vector.
  1228. DIType *BaseTy = CTy->getBaseType();
  1229. assert(BaseTy && "Unknown vector element type.");
  1230. const uint64_t ElementSize = BaseTy->getSizeInBits();
  1231. // Locate the number of elements in the vector.
  1232. const DINodeArray Elements = CTy->getElements();
  1233. assert(Elements.size() == 1 &&
  1234. Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
  1235. "Invalid vector element array, expected one element of type subrange");
  1236. const auto Subrange = cast<DISubrange>(Elements[0]);
  1237. const auto NumVecElements =
  1238. Subrange->getCount()
  1239. ? Subrange->getCount().get<ConstantInt *>()->getSExtValue()
  1240. : 0;
  1241. // Ensure we found the element count and that the actual size is wide
  1242. // enough to contain the requested size.
  1243. assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
  1244. return ActualSize != (NumVecElements * ElementSize);
  1245. }
  1246. void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
  1247. if (CTy->isVector()) {
  1248. addFlag(Buffer, dwarf::DW_AT_GNU_vector);
  1249. if (hasVectorBeenPadded(CTy))
  1250. addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt,
  1251. CTy->getSizeInBits() / CHAR_BIT);
  1252. }
  1253. if (DIVariable *Var = CTy->getDataLocation()) {
  1254. if (auto *VarDIE = getDIE(Var))
  1255. addDIEEntry(Buffer, dwarf::DW_AT_data_location, *VarDIE);
  1256. } else if (DIExpression *Expr = CTy->getDataLocationExp()) {
  1257. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1258. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  1259. DwarfExpr.setMemoryLocationKind();
  1260. DwarfExpr.addExpression(Expr);
  1261. addBlock(Buffer, dwarf::DW_AT_data_location, DwarfExpr.finalize());
  1262. }
  1263. if (DIVariable *Var = CTy->getAssociated()) {
  1264. if (auto *VarDIE = getDIE(Var))
  1265. addDIEEntry(Buffer, dwarf::DW_AT_associated, *VarDIE);
  1266. } else if (DIExpression *Expr = CTy->getAssociatedExp()) {
  1267. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1268. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  1269. DwarfExpr.setMemoryLocationKind();
  1270. DwarfExpr.addExpression(Expr);
  1271. addBlock(Buffer, dwarf::DW_AT_associated, DwarfExpr.finalize());
  1272. }
  1273. if (DIVariable *Var = CTy->getAllocated()) {
  1274. if (auto *VarDIE = getDIE(Var))
  1275. addDIEEntry(Buffer, dwarf::DW_AT_allocated, *VarDIE);
  1276. } else if (DIExpression *Expr = CTy->getAllocatedExp()) {
  1277. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1278. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  1279. DwarfExpr.setMemoryLocationKind();
  1280. DwarfExpr.addExpression(Expr);
  1281. addBlock(Buffer, dwarf::DW_AT_allocated, DwarfExpr.finalize());
  1282. }
  1283. if (auto *RankConst = CTy->getRankConst()) {
  1284. addSInt(Buffer, dwarf::DW_AT_rank, dwarf::DW_FORM_sdata,
  1285. RankConst->getSExtValue());
  1286. } else if (auto *RankExpr = CTy->getRankExp()) {
  1287. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1288. DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
  1289. DwarfExpr.setMemoryLocationKind();
  1290. DwarfExpr.addExpression(RankExpr);
  1291. addBlock(Buffer, dwarf::DW_AT_rank, DwarfExpr.finalize());
  1292. }
  1293. // Emit the element type.
  1294. addType(Buffer, CTy->getBaseType());
  1295. // Get an anonymous type for index type.
  1296. // FIXME: This type should be passed down from the front end
  1297. // as different languages may have different sizes for indexes.
  1298. DIE *IdxTy = getIndexTyDie();
  1299. // Add subranges to array type.
  1300. DINodeArray Elements = CTy->getElements();
  1301. for (DINode *E : Elements) {
  1302. // FIXME: Should this really be such a loose cast?
  1303. if (auto *Element = dyn_cast_or_null<DINode>(E)) {
  1304. if (Element->getTag() == dwarf::DW_TAG_subrange_type)
  1305. constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
  1306. else if (Element->getTag() == dwarf::DW_TAG_generic_subrange)
  1307. constructGenericSubrangeDIE(Buffer, cast<DIGenericSubrange>(Element),
  1308. IdxTy);
  1309. }
  1310. }
  1311. }
  1312. void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
  1313. const DIType *DTy = CTy->getBaseType();
  1314. bool IsUnsigned = DTy && DD->isUnsignedDIType(DTy);
  1315. if (DTy) {
  1316. if (DD->getDwarfVersion() >= 3)
  1317. addType(Buffer, DTy);
  1318. if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
  1319. addFlag(Buffer, dwarf::DW_AT_enum_class);
  1320. }
  1321. auto *Context = CTy->getScope();
  1322. bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
  1323. isa<DINamespace>(Context) || isa<DICommonBlock>(Context);
  1324. DINodeArray Elements = CTy->getElements();
  1325. // Add enumerators to enumeration type.
  1326. for (const DINode *E : Elements) {
  1327. auto *Enum = dyn_cast_or_null<DIEnumerator>(E);
  1328. if (Enum) {
  1329. DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
  1330. StringRef Name = Enum->getName();
  1331. addString(Enumerator, dwarf::DW_AT_name, Name);
  1332. addConstantValue(Enumerator, Enum->getValue(), IsUnsigned);
  1333. if (IndexEnumerators)
  1334. addGlobalName(Name, Enumerator, Context);
  1335. }
  1336. }
  1337. }
  1338. void DwarfUnit::constructContainingTypeDIEs() {
  1339. for (auto &P : ContainingTypeMap) {
  1340. DIE &SPDie = *P.first;
  1341. const DINode *D = P.second;
  1342. if (!D)
  1343. continue;
  1344. DIE *NDie = getDIE(D);
  1345. if (!NDie)
  1346. continue;
  1347. addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
  1348. }
  1349. }
  1350. DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
  1351. DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
  1352. StringRef Name = DT->getName();
  1353. if (!Name.empty())
  1354. addString(MemberDie, dwarf::DW_AT_name, Name);
  1355. addAnnotation(MemberDie, DT->getAnnotations());
  1356. if (DIType *Resolved = DT->getBaseType())
  1357. addType(MemberDie, Resolved);
  1358. addSourceLine(MemberDie, DT);
  1359. if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
  1360. // For C++, virtual base classes are not at fixed offset. Use following
  1361. // expression to extract appropriate offset from vtable.
  1362. // BaseAddr = ObAddr + *((*ObAddr) - Offset)
  1363. DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
  1364. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
  1365. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
  1366. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
  1367. addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
  1368. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
  1369. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
  1370. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
  1371. addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
  1372. } else {
  1373. uint64_t Size = DT->getSizeInBits();
  1374. uint64_t FieldSize = DD->getBaseTypeSize(DT);
  1375. uint32_t AlignInBytes = DT->getAlignInBytes();
  1376. uint64_t OffsetInBytes;
  1377. bool IsBitfield = DT->isBitField();
  1378. if (IsBitfield) {
  1379. // Handle bitfield, assume bytes are 8 bits.
  1380. if (DD->useDWARF2Bitfields())
  1381. addUInt(MemberDie, dwarf::DW_AT_byte_size, std::nullopt, FieldSize / 8);
  1382. addUInt(MemberDie, dwarf::DW_AT_bit_size, std::nullopt, Size);
  1383. uint64_t Offset = DT->getOffsetInBits();
  1384. // We can't use DT->getAlignInBits() here: AlignInBits for member type
  1385. // is non-zero if and only if alignment was forced (e.g. _Alignas()),
  1386. // which can't be done with bitfields. Thus we use FieldSize here.
  1387. uint32_t AlignInBits = FieldSize;
  1388. uint32_t AlignMask = ~(AlignInBits - 1);
  1389. // The bits from the start of the storage unit to the start of the field.
  1390. uint64_t StartBitOffset = Offset - (Offset & AlignMask);
  1391. // The byte offset of the field's aligned storage unit inside the struct.
  1392. OffsetInBytes = (Offset - StartBitOffset) / 8;
  1393. if (DD->useDWARF2Bitfields()) {
  1394. uint64_t HiMark = (Offset + FieldSize) & AlignMask;
  1395. uint64_t FieldOffset = (HiMark - FieldSize);
  1396. Offset -= FieldOffset;
  1397. // Maybe we need to work from the other end.
  1398. if (Asm->getDataLayout().isLittleEndian())
  1399. Offset = FieldSize - (Offset + Size);
  1400. addUInt(MemberDie, dwarf::DW_AT_bit_offset, std::nullopt, Offset);
  1401. OffsetInBytes = FieldOffset >> 3;
  1402. } else {
  1403. addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, std::nullopt, Offset);
  1404. }
  1405. } else {
  1406. // This is not a bitfield.
  1407. OffsetInBytes = DT->getOffsetInBits() / 8;
  1408. if (AlignInBytes)
  1409. addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  1410. AlignInBytes);
  1411. }
  1412. if (DD->getDwarfVersion() <= 2) {
  1413. DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
  1414. addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
  1415. addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
  1416. addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
  1417. } else if (!IsBitfield || DD->useDWARF2Bitfields()) {
  1418. // In DWARF v3, DW_FORM_data4/8 in DW_AT_data_member_location are
  1419. // interpreted as location-list pointers. Interpreting constants as
  1420. // pointers is not expected, so we use DW_FORM_udata to encode the
  1421. // constants here.
  1422. if (DD->getDwarfVersion() == 3)
  1423. addUInt(MemberDie, dwarf::DW_AT_data_member_location,
  1424. dwarf::DW_FORM_udata, OffsetInBytes);
  1425. else
  1426. addUInt(MemberDie, dwarf::DW_AT_data_member_location, std::nullopt,
  1427. OffsetInBytes);
  1428. }
  1429. }
  1430. addAccess(MemberDie, DT->getFlags());
  1431. if (DT->isVirtual())
  1432. addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
  1433. dwarf::DW_VIRTUALITY_virtual);
  1434. // Objective-C properties.
  1435. if (DINode *PNode = DT->getObjCProperty())
  1436. if (DIE *PDie = getDIE(PNode))
  1437. addAttribute(MemberDie, dwarf::DW_AT_APPLE_property,
  1438. dwarf::DW_FORM_ref4, DIEEntry(*PDie));
  1439. if (DT->isArtificial())
  1440. addFlag(MemberDie, dwarf::DW_AT_artificial);
  1441. return MemberDie;
  1442. }
  1443. DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
  1444. if (!DT)
  1445. return nullptr;
  1446. // Construct the context before querying for the existence of the DIE in case
  1447. // such construction creates the DIE.
  1448. DIE *ContextDIE = getOrCreateContextDIE(DT->getScope());
  1449. assert(dwarf::isType(ContextDIE->getTag()) &&
  1450. "Static member should belong to a type.");
  1451. if (DIE *StaticMemberDIE = getDIE(DT))
  1452. return StaticMemberDIE;
  1453. DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
  1454. const DIType *Ty = DT->getBaseType();
  1455. addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
  1456. addType(StaticMemberDIE, Ty);
  1457. addSourceLine(StaticMemberDIE, DT);
  1458. addFlag(StaticMemberDIE, dwarf::DW_AT_external);
  1459. addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
  1460. // FIXME: We could omit private if the parent is a class_type, and
  1461. // public if the parent is something else.
  1462. addAccess(StaticMemberDIE, DT->getFlags());
  1463. if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
  1464. addConstantValue(StaticMemberDIE, CI, Ty);
  1465. if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
  1466. addConstantFPValue(StaticMemberDIE, CFP);
  1467. if (uint32_t AlignInBytes = DT->getAlignInBytes())
  1468. addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  1469. AlignInBytes);
  1470. return &StaticMemberDIE;
  1471. }
  1472. void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
  1473. // Emit size of content not including length itself
  1474. if (!DD->useSectionsAsReferences())
  1475. EndLabel = Asm->emitDwarfUnitLength(
  1476. isDwoUnit() ? "debug_info_dwo" : "debug_info", "Length of Unit");
  1477. else
  1478. Asm->emitDwarfUnitLength(getHeaderSize() + getUnitDie().getSize(),
  1479. "Length of Unit");
  1480. Asm->OutStreamer->AddComment("DWARF version number");
  1481. unsigned Version = DD->getDwarfVersion();
  1482. Asm->emitInt16(Version);
  1483. // DWARF v5 reorders the address size and adds a unit type.
  1484. if (Version >= 5) {
  1485. Asm->OutStreamer->AddComment("DWARF Unit Type");
  1486. Asm->emitInt8(UT);
  1487. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  1488. Asm->emitInt8(Asm->MAI->getCodePointerSize());
  1489. }
  1490. // We share one abbreviations table across all units so it's always at the
  1491. // start of the section. Use a relocatable offset where needed to ensure
  1492. // linking doesn't invalidate that offset.
  1493. Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
  1494. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1495. if (UseOffsets)
  1496. Asm->emitDwarfLengthOrOffset(0);
  1497. else
  1498. Asm->emitDwarfSymbolReference(
  1499. TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
  1500. if (Version <= 4) {
  1501. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  1502. Asm->emitInt8(Asm->MAI->getCodePointerSize());
  1503. }
  1504. }
  1505. void DwarfTypeUnit::emitHeader(bool UseOffsets) {
  1506. DwarfUnit::emitCommonHeader(UseOffsets,
  1507. DD->useSplitDwarf() ? dwarf::DW_UT_split_type
  1508. : dwarf::DW_UT_type);
  1509. Asm->OutStreamer->AddComment("Type Signature");
  1510. Asm->OutStreamer->emitIntValue(TypeSignature, sizeof(TypeSignature));
  1511. Asm->OutStreamer->AddComment("Type DIE Offset");
  1512. // In a skeleton type unit there is no type DIE so emit a zero offset.
  1513. Asm->emitDwarfLengthOrOffset(Ty ? Ty->getOffset() : 0);
  1514. }
  1515. void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
  1516. const MCSymbol *Hi, const MCSymbol *Lo) {
  1517. addAttribute(Die, Attribute, DD->getDwarfSectionOffsetForm(),
  1518. new (DIEValueAllocator) DIEDelta(Hi, Lo));
  1519. }
  1520. void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
  1521. const MCSymbol *Label, const MCSymbol *Sec) {
  1522. if (Asm->doesDwarfUseRelocationsAcrossSections())
  1523. addLabel(Die, Attribute, DD->getDwarfSectionOffsetForm(), Label);
  1524. else
  1525. addSectionDelta(Die, Attribute, Label, Sec);
  1526. }
  1527. bool DwarfTypeUnit::isDwoUnit() const {
  1528. // Since there are no skeleton type units, all type units are dwo type units
  1529. // when split DWARF is being used.
  1530. return DD->useSplitDwarf();
  1531. }
  1532. void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
  1533. const DIScope *Context) {
  1534. getCU().addGlobalNameForTypeUnit(Name, Context);
  1535. }
  1536. void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
  1537. const DIScope *Context) {
  1538. getCU().addGlobalTypeUnitType(Ty, Context);
  1539. }
  1540. const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
  1541. if (!Asm->doesDwarfUseRelocationsAcrossSections())
  1542. return nullptr;
  1543. if (isDwoUnit())
  1544. return nullptr;
  1545. return getSection()->getBeginSymbol();
  1546. }
  1547. void DwarfUnit::addStringOffsetsStart() {
  1548. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1549. addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
  1550. DU->getStringOffsetsStartSym(),
  1551. TLOF.getDwarfStrOffSection()->getBeginSymbol());
  1552. }
  1553. void DwarfUnit::addRnglistsBase() {
  1554. assert(DD->getDwarfVersion() >= 5 &&
  1555. "DW_AT_rnglists_base requires DWARF version 5 or later");
  1556. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1557. addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
  1558. DU->getRnglistsTableBaseSym(),
  1559. TLOF.getDwarfRnglistsSection()->getBeginSymbol());
  1560. }
  1561. void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
  1562. DD->getAddressPool().resetUsedFlag(true);
  1563. }
  1564. bool DwarfUnit::isCompatibleWithVersion(uint16_t Version) const {
  1565. return !Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= Version;
  1566. }