DwarfUnit.cpp 67 KB

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