DwarfUnit.cpp 61 KB

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