DwarfDebug.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. //===- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework --------*- C++ -*-===//
  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 writing dwarf debug info into asm files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
  13. #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
  14. #include "AddressPool.h"
  15. #include "DebugLocStream.h"
  16. #include "DebugLocEntry.h"
  17. #include "DwarfFile.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/ADT/MapVector.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringMap.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/BinaryFormat/Dwarf.h"
  29. #include "llvm/CodeGen/AccelTable.h"
  30. #include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
  31. #include "llvm/CodeGen/DebugHandlerBase.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/DebugLoc.h"
  35. #include "llvm/IR/Metadata.h"
  36. #include "llvm/MC/MCDwarf.h"
  37. #include "llvm/Support/Allocator.h"
  38. #include "llvm/Target/TargetOptions.h"
  39. #include <cassert>
  40. #include <cstdint>
  41. #include <limits>
  42. #include <memory>
  43. #include <utility>
  44. #include <vector>
  45. namespace llvm {
  46. class AsmPrinter;
  47. class ByteStreamer;
  48. class DIE;
  49. class DwarfCompileUnit;
  50. class DwarfExpression;
  51. class DwarfTypeUnit;
  52. class DwarfUnit;
  53. class LexicalScope;
  54. class MachineFunction;
  55. class MCSection;
  56. class MCSymbol;
  57. class Module;
  58. //===----------------------------------------------------------------------===//
  59. /// This class is defined as the common parent of DbgVariable and DbgLabel
  60. /// such that it could levarage polymorphism to extract common code for
  61. /// DbgVariable and DbgLabel.
  62. class DbgEntity {
  63. public:
  64. enum DbgEntityKind {
  65. DbgVariableKind,
  66. DbgLabelKind
  67. };
  68. private:
  69. const DINode *Entity;
  70. const DILocation *InlinedAt;
  71. DIE *TheDIE = nullptr;
  72. const DbgEntityKind SubclassID;
  73. public:
  74. DbgEntity(const DINode *N, const DILocation *IA, DbgEntityKind ID)
  75. : Entity(N), InlinedAt(IA), SubclassID(ID) {}
  76. virtual ~DbgEntity() {}
  77. /// Accessors.
  78. /// @{
  79. const DINode *getEntity() const { return Entity; }
  80. const DILocation *getInlinedAt() const { return InlinedAt; }
  81. DIE *getDIE() const { return TheDIE; }
  82. DbgEntityKind getDbgEntityID() const { return SubclassID; }
  83. /// @}
  84. void setDIE(DIE &D) { TheDIE = &D; }
  85. static bool classof(const DbgEntity *N) {
  86. switch (N->getDbgEntityID()) {
  87. case DbgVariableKind:
  88. case DbgLabelKind:
  89. return true;
  90. }
  91. llvm_unreachable("Invalid DbgEntityKind");
  92. }
  93. };
  94. //===----------------------------------------------------------------------===//
  95. /// This class is used to track local variable information.
  96. ///
  97. /// Variables can be created from allocas, in which case they're generated from
  98. /// the MMI table. Such variables can have multiple expressions and frame
  99. /// indices.
  100. ///
  101. /// Variables can be created from \c DBG_VALUE instructions. Those whose
  102. /// location changes over time use \a DebugLocListIndex, while those with a
  103. /// single location use \a ValueLoc and (optionally) a single entry of \a Expr.
  104. ///
  105. /// Variables that have been optimized out use none of these fields.
  106. class DbgVariable : public DbgEntity {
  107. /// Index of the entry list in DebugLocs.
  108. unsigned DebugLocListIndex = ~0u;
  109. /// DW_OP_LLVM_tag_offset value from DebugLocs.
  110. Optional<uint8_t> DebugLocListTagOffset;
  111. /// Single value location description.
  112. std::unique_ptr<DbgValueLoc> ValueLoc = nullptr;
  113. struct FrameIndexExpr {
  114. int FI;
  115. const DIExpression *Expr;
  116. };
  117. mutable SmallVector<FrameIndexExpr, 1>
  118. FrameIndexExprs; /// Frame index + expression.
  119. public:
  120. /// Construct a DbgVariable.
  121. ///
  122. /// Creates a variable without any DW_AT_location. Call \a initializeMMI()
  123. /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
  124. DbgVariable(const DILocalVariable *V, const DILocation *IA)
  125. : DbgEntity(V, IA, DbgVariableKind) {}
  126. /// Initialize from the MMI table.
  127. void initializeMMI(const DIExpression *E, int FI) {
  128. assert(FrameIndexExprs.empty() && "Already initialized?");
  129. assert(!ValueLoc.get() && "Already initialized?");
  130. assert((!E || E->isValid()) && "Expected valid expression");
  131. assert(FI != std::numeric_limits<int>::max() && "Expected valid index");
  132. FrameIndexExprs.push_back({FI, E});
  133. }
  134. // Initialize variable's location.
  135. void initializeDbgValue(DbgValueLoc Value) {
  136. assert(FrameIndexExprs.empty() && "Already initialized?");
  137. assert(!ValueLoc && "Already initialized?");
  138. assert(!Value.getExpression()->isFragment() && "Fragments not supported.");
  139. ValueLoc = std::make_unique<DbgValueLoc>(Value);
  140. if (auto *E = ValueLoc->getExpression())
  141. if (E->getNumElements())
  142. FrameIndexExprs.push_back({0, E});
  143. }
  144. /// Initialize from a DBG_VALUE instruction.
  145. void initializeDbgValue(const MachineInstr *DbgValue);
  146. // Accessors.
  147. const DILocalVariable *getVariable() const {
  148. return cast<DILocalVariable>(getEntity());
  149. }
  150. const DIExpression *getSingleExpression() const {
  151. assert(ValueLoc.get() && FrameIndexExprs.size() <= 1);
  152. return FrameIndexExprs.size() ? FrameIndexExprs[0].Expr : nullptr;
  153. }
  154. void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
  155. unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
  156. void setDebugLocListTagOffset(uint8_t O) { DebugLocListTagOffset = O; }
  157. Optional<uint8_t> getDebugLocListTagOffset() const { return DebugLocListTagOffset; }
  158. StringRef getName() const { return getVariable()->getName(); }
  159. const DbgValueLoc *getValueLoc() const { return ValueLoc.get(); }
  160. /// Get the FI entries, sorted by fragment offset.
  161. ArrayRef<FrameIndexExpr> getFrameIndexExprs() const;
  162. bool hasFrameIndexExprs() const { return !FrameIndexExprs.empty(); }
  163. void addMMIEntry(const DbgVariable &V);
  164. // Translate tag to proper Dwarf tag.
  165. dwarf::Tag getTag() const {
  166. // FIXME: Why don't we just infer this tag and store it all along?
  167. if (getVariable()->isParameter())
  168. return dwarf::DW_TAG_formal_parameter;
  169. return dwarf::DW_TAG_variable;
  170. }
  171. /// Return true if DbgVariable is artificial.
  172. bool isArtificial() const {
  173. if (getVariable()->isArtificial())
  174. return true;
  175. if (getType()->isArtificial())
  176. return true;
  177. return false;
  178. }
  179. bool isObjectPointer() const {
  180. if (getVariable()->isObjectPointer())
  181. return true;
  182. if (getType()->isObjectPointer())
  183. return true;
  184. return false;
  185. }
  186. bool hasComplexAddress() const {
  187. assert(ValueLoc.get() && "Expected DBG_VALUE, not MMI variable");
  188. assert((FrameIndexExprs.empty() ||
  189. (FrameIndexExprs.size() == 1 &&
  190. FrameIndexExprs[0].Expr->getNumElements())) &&
  191. "Invalid Expr for DBG_VALUE");
  192. return !FrameIndexExprs.empty();
  193. }
  194. const DIType *getType() const;
  195. static bool classof(const DbgEntity *N) {
  196. return N->getDbgEntityID() == DbgVariableKind;
  197. }
  198. };
  199. //===----------------------------------------------------------------------===//
  200. /// This class is used to track label information.
  201. ///
  202. /// Labels are collected from \c DBG_LABEL instructions.
  203. class DbgLabel : public DbgEntity {
  204. const MCSymbol *Sym; /// Symbol before DBG_LABEL instruction.
  205. public:
  206. /// We need MCSymbol information to generate DW_AT_low_pc.
  207. DbgLabel(const DILabel *L, const DILocation *IA, const MCSymbol *Sym = nullptr)
  208. : DbgEntity(L, IA, DbgLabelKind), Sym(Sym) {}
  209. /// Accessors.
  210. /// @{
  211. const DILabel *getLabel() const { return cast<DILabel>(getEntity()); }
  212. const MCSymbol *getSymbol() const { return Sym; }
  213. StringRef getName() const { return getLabel()->getName(); }
  214. /// @}
  215. /// Translate tag to proper Dwarf tag.
  216. dwarf::Tag getTag() const {
  217. return dwarf::DW_TAG_label;
  218. }
  219. static bool classof(const DbgEntity *N) {
  220. return N->getDbgEntityID() == DbgLabelKind;
  221. }
  222. };
  223. /// Used for tracking debug info about call site parameters.
  224. class DbgCallSiteParam {
  225. private:
  226. unsigned Register; ///< Parameter register at the callee entry point.
  227. DbgValueLoc Value; ///< Corresponding location for the parameter value at
  228. ///< the call site.
  229. public:
  230. DbgCallSiteParam(unsigned Reg, DbgValueLoc Val)
  231. : Register(Reg), Value(Val) {
  232. assert(Reg && "Parameter register cannot be undef");
  233. }
  234. unsigned getRegister() const { return Register; }
  235. DbgValueLoc getValue() const { return Value; }
  236. };
  237. /// Collection used for storing debug call site parameters.
  238. using ParamSet = SmallVector<DbgCallSiteParam, 4>;
  239. /// Helper used to pair up a symbol and its DWARF compile unit.
  240. struct SymbolCU {
  241. SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
  242. const MCSymbol *Sym;
  243. DwarfCompileUnit *CU;
  244. };
  245. /// The kind of accelerator tables we should emit.
  246. enum class AccelTableKind {
  247. Default, ///< Platform default.
  248. None, ///< None.
  249. Apple, ///< .apple_names, .apple_namespaces, .apple_types, .apple_objc.
  250. Dwarf, ///< DWARF v5 .debug_names.
  251. };
  252. /// Collects and handles dwarf debug information.
  253. class DwarfDebug : public DebugHandlerBase {
  254. /// All DIEValues are allocated through this allocator.
  255. BumpPtrAllocator DIEValueAllocator;
  256. /// Maps MDNode with its corresponding DwarfCompileUnit.
  257. MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
  258. /// Maps a CU DIE with its corresponding DwarfCompileUnit.
  259. DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
  260. /// List of all labels used in aranges generation.
  261. std::vector<SymbolCU> ArangeLabels;
  262. /// Size of each symbol emitted (for those symbols that have a specific size).
  263. DenseMap<const MCSymbol *, uint64_t> SymSize;
  264. /// Collection of abstract variables/labels.
  265. SmallVector<std::unique_ptr<DbgEntity>, 64> ConcreteEntities;
  266. /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
  267. /// can refer to them in spite of insertions into this list.
  268. DebugLocStream DebugLocs;
  269. /// This is a collection of subprogram MDNodes that are processed to
  270. /// create DIEs.
  271. SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
  272. SmallPtrSet<const DISubprogram *, 16>>
  273. ProcessedSPNodes;
  274. /// If nonnull, stores the current machine function we're processing.
  275. const MachineFunction *CurFn = nullptr;
  276. /// If nonnull, stores the CU in which the previous subprogram was contained.
  277. const DwarfCompileUnit *PrevCU = nullptr;
  278. /// As an optimization, there is no need to emit an entry in the directory
  279. /// table for the same directory as DW_AT_comp_dir.
  280. StringRef CompilationDir;
  281. /// Holder for the file specific debug information.
  282. DwarfFile InfoHolder;
  283. /// Holders for the various debug information flags that we might need to
  284. /// have exposed. See accessor functions below for description.
  285. /// Map from MDNodes for user-defined types to their type signatures. Also
  286. /// used to keep track of which types we have emitted type units for.
  287. DenseMap<const MDNode *, uint64_t> TypeSignatures;
  288. DenseMap<const MCSection *, const MCSymbol *> SectionLabels;
  289. SmallVector<
  290. std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
  291. TypeUnitsUnderConstruction;
  292. /// Whether to use the GNU TLS opcode (instead of the standard opcode).
  293. bool UseGNUTLSOpcode;
  294. /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
  295. bool UseDWARF2Bitfields;
  296. /// Whether to emit all linkage names, or just abstract subprograms.
  297. bool UseAllLinkageNames;
  298. /// Use inlined strings.
  299. bool UseInlineStrings = false;
  300. /// Allow emission of .debug_ranges section.
  301. bool UseRangesSection = true;
  302. /// True if the sections itself must be used as references and don't create
  303. /// temp symbols inside DWARF sections.
  304. bool UseSectionsAsReferences = false;
  305. ///Allow emission of the .debug_loc section.
  306. bool UseLocSection = true;
  307. /// Generate DWARF v4 type units.
  308. bool GenerateTypeUnits;
  309. /// Emit a .debug_macro section instead of .debug_macinfo.
  310. bool UseDebugMacroSection;
  311. /// Avoid using DW_OP_convert due to consumer incompatibilities.
  312. bool EnableOpConvert;
  313. public:
  314. enum class MinimizeAddrInV5 {
  315. Default,
  316. Disabled,
  317. Ranges,
  318. Expressions,
  319. Form,
  320. };
  321. private:
  322. /// Force the use of DW_AT_ranges even for single-entry range lists.
  323. MinimizeAddrInV5 MinimizeAddr = MinimizeAddrInV5::Disabled;
  324. /// DWARF5 Experimental Options
  325. /// @{
  326. AccelTableKind TheAccelTableKind;
  327. bool HasAppleExtensionAttributes;
  328. bool HasSplitDwarf;
  329. /// Whether to generate the DWARF v5 string offsets table.
  330. /// It consists of a series of contributions, each preceded by a header.
  331. /// The pre-DWARF v5 string offsets table for split dwarf is, in contrast,
  332. /// a monolithic sequence of string offsets.
  333. bool UseSegmentedStringOffsetsTable;
  334. /// Enable production of call site parameters needed to print the debug entry
  335. /// values. Useful for testing purposes when a debugger does not support the
  336. /// feature yet.
  337. bool EmitDebugEntryValues;
  338. /// Separated Dwarf Variables
  339. /// In general these will all be for bits that are left in the
  340. /// original object file, rather than things that are meant
  341. /// to be in the .dwo sections.
  342. /// Holder for the skeleton information.
  343. DwarfFile SkeletonHolder;
  344. /// Store file names for type units under fission in a line table
  345. /// header that will be emitted into debug_line.dwo.
  346. // FIXME: replace this with a map from comp_dir to table so that we
  347. // can emit multiple tables during LTO each of which uses directory
  348. // 0, referencing the comp_dir of all the type units that use it.
  349. MCDwarfDwoLineTable SplitTypeUnitFileTable;
  350. /// @}
  351. /// True iff there are multiple CUs in this module.
  352. bool SingleCU;
  353. bool IsDarwin;
  354. /// Map for tracking Fortran deferred CHARACTER lengths.
  355. DenseMap<const DIStringType *, unsigned> StringTypeLocMap;
  356. AddressPool AddrPool;
  357. /// Accelerator tables.
  358. AccelTable<DWARF5AccelTableData> AccelDebugNames;
  359. AccelTable<AppleAccelTableOffsetData> AccelNames;
  360. AccelTable<AppleAccelTableOffsetData> AccelObjC;
  361. AccelTable<AppleAccelTableOffsetData> AccelNamespace;
  362. AccelTable<AppleAccelTableTypeData> AccelTypes;
  363. /// Identify a debugger for "tuning" the debug info.
  364. ///
  365. /// The "tuning" should be used to set defaults for individual feature flags
  366. /// in DwarfDebug; if a given feature has a more specific command-line option,
  367. /// that option should take precedence over the tuning.
  368. DebuggerKind DebuggerTuning = DebuggerKind::Default;
  369. MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
  370. const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
  371. return InfoHolder.getUnits();
  372. }
  373. using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
  374. void ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
  375. const DINode *Node,
  376. const MDNode *Scope);
  377. void ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
  378. const DINode *Node,
  379. const MDNode *Scope);
  380. DbgEntity *createConcreteEntity(DwarfCompileUnit &TheCU,
  381. LexicalScope &Scope,
  382. const DINode *Node,
  383. const DILocation *Location,
  384. const MCSymbol *Sym = nullptr);
  385. /// Construct a DIE for this abstract scope.
  386. void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
  387. /// Construct DIEs for call site entries describing the calls in \p MF.
  388. void constructCallSiteEntryDIEs(const DISubprogram &SP, DwarfCompileUnit &CU,
  389. DIE &ScopeDIE, const MachineFunction &MF);
  390. template <typename DataT>
  391. void addAccelNameImpl(const DICompileUnit &CU, AccelTable<DataT> &AppleAccel,
  392. StringRef Name, const DIE &Die);
  393. void finishEntityDefinitions();
  394. void finishSubprogramDefinitions();
  395. /// Finish off debug information after all functions have been
  396. /// processed.
  397. void finalizeModuleInfo();
  398. /// Emit the debug info section.
  399. void emitDebugInfo();
  400. /// Emit the abbreviation section.
  401. void emitAbbreviations();
  402. /// Emit the string offsets table header.
  403. void emitStringOffsetsTableHeader();
  404. /// Emit a specified accelerator table.
  405. template <typename AccelTableT>
  406. void emitAccel(AccelTableT &Accel, MCSection *Section, StringRef TableName);
  407. /// Emit DWARF v5 accelerator table.
  408. void emitAccelDebugNames();
  409. /// Emit visible names into a hashed accelerator table section.
  410. void emitAccelNames();
  411. /// Emit objective C classes and categories into a hashed
  412. /// accelerator table section.
  413. void emitAccelObjC();
  414. /// Emit namespace dies into a hashed accelerator table.
  415. void emitAccelNamespaces();
  416. /// Emit type dies into a hashed accelerator table.
  417. void emitAccelTypes();
  418. /// Emit visible names and types into debug pubnames and pubtypes sections.
  419. void emitDebugPubSections();
  420. void emitDebugPubSection(bool GnuStyle, StringRef Name,
  421. DwarfCompileUnit *TheU,
  422. const StringMap<const DIE *> &Globals);
  423. /// Emit null-terminated strings into a debug str section.
  424. void emitDebugStr();
  425. /// Emit variable locations into a debug loc section.
  426. void emitDebugLoc();
  427. /// Emit variable locations into a debug loc dwo section.
  428. void emitDebugLocDWO();
  429. void emitDebugLocImpl(MCSection *Sec);
  430. /// Emit address ranges into a debug aranges section.
  431. void emitDebugARanges();
  432. /// Emit address ranges into a debug ranges section.
  433. void emitDebugRanges();
  434. void emitDebugRangesDWO();
  435. void emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section);
  436. /// Emit macros into a debug macinfo section.
  437. void emitDebugMacinfo();
  438. /// Emit macros into a debug macinfo.dwo section.
  439. void emitDebugMacinfoDWO();
  440. void emitDebugMacinfoImpl(MCSection *Section);
  441. void emitMacro(DIMacro &M);
  442. void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
  443. void emitMacroFileImpl(DIMacroFile &F, DwarfCompileUnit &U,
  444. unsigned StartFile, unsigned EndFile,
  445. StringRef (*MacroFormToString)(unsigned Form));
  446. void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
  447. /// DWARF 5 Experimental Split Dwarf Emitters
  448. /// Initialize common features of skeleton units.
  449. void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
  450. std::unique_ptr<DwarfCompileUnit> NewU);
  451. /// Construct the split debug info compile unit for the debug info section.
  452. /// In DWARF v5, the skeleton unit DIE may have the following attributes:
  453. /// DW_AT_addr_base, DW_AT_comp_dir, DW_AT_dwo_name, DW_AT_high_pc,
  454. /// DW_AT_low_pc, DW_AT_ranges, DW_AT_stmt_list, and DW_AT_str_offsets_base.
  455. /// Prior to DWARF v5 it may also have DW_AT_GNU_dwo_id. DW_AT_GNU_dwo_name
  456. /// is used instead of DW_AT_dwo_name, Dw_AT_GNU_addr_base instead of
  457. /// DW_AT_addr_base, and DW_AT_GNU_ranges_base instead of DW_AT_rnglists_base.
  458. DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
  459. /// Emit the debug info dwo section.
  460. void emitDebugInfoDWO();
  461. /// Emit the debug abbrev dwo section.
  462. void emitDebugAbbrevDWO();
  463. /// Emit the debug line dwo section.
  464. void emitDebugLineDWO();
  465. /// Emit the dwo stringoffsets table header.
  466. void emitStringOffsetsTableHeaderDWO();
  467. /// Emit the debug str dwo section.
  468. void emitDebugStrDWO();
  469. /// Emit DWO addresses.
  470. void emitDebugAddr();
  471. /// Flags to let the linker know we have emitted new style pubnames. Only
  472. /// emit it here if we don't have a skeleton CU for split dwarf.
  473. void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
  474. /// Create new DwarfCompileUnit for the given metadata node with tag
  475. /// DW_TAG_compile_unit.
  476. DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
  477. void finishUnitAttributes(const DICompileUnit *DIUnit,
  478. DwarfCompileUnit &NewCU);
  479. /// Construct imported_module or imported_declaration DIE.
  480. void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
  481. const DIImportedEntity *N);
  482. /// Register a source line with debug info. Returns the unique
  483. /// label that was emitted and which provides correspondence to the
  484. /// source line list.
  485. void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
  486. unsigned Flags);
  487. /// Populate LexicalScope entries with variables' info.
  488. void collectEntityInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
  489. DenseSet<InlinedEntity> &ProcessedVars);
  490. /// Build the location list for all DBG_VALUEs in the
  491. /// function that describe the same variable. If the resulting
  492. /// list has only one entry that is valid for entire variable's
  493. /// scope return true.
  494. bool buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
  495. const DbgValueHistoryMap::Entries &Entries);
  496. /// Collect variable information from the side table maintained by MF.
  497. void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
  498. DenseSet<InlinedEntity> &P);
  499. /// Emit the reference to the section.
  500. void emitSectionReference(const DwarfCompileUnit &CU);
  501. protected:
  502. /// Gather pre-function debug information.
  503. void beginFunctionImpl(const MachineFunction *MF) override;
  504. /// Gather and emit post-function debug information.
  505. void endFunctionImpl(const MachineFunction *MF) override;
  506. /// Get Dwarf compile unit ID for line table.
  507. unsigned getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU);
  508. void skippedNonDebugFunction() override;
  509. public:
  510. //===--------------------------------------------------------------------===//
  511. // Main entry points.
  512. //
  513. DwarfDebug(AsmPrinter *A);
  514. ~DwarfDebug() override;
  515. /// Emit all Dwarf sections that should come prior to the
  516. /// content.
  517. void beginModule(Module *M) override;
  518. /// Emit all Dwarf sections that should come after the content.
  519. void endModule() override;
  520. /// Emits inital debug location directive.
  521. DebugLoc emitInitialLocDirective(const MachineFunction &MF, unsigned CUID);
  522. /// Process beginning of an instruction.
  523. void beginInstruction(const MachineInstr *MI) override;
  524. /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
  525. static uint64_t makeTypeSignature(StringRef Identifier);
  526. /// Add a DIE to the set of types that we're going to pull into
  527. /// type units.
  528. void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
  529. DIE &Die, const DICompositeType *CTy);
  530. class NonTypeUnitContext {
  531. DwarfDebug *DD;
  532. decltype(DwarfDebug::TypeUnitsUnderConstruction) TypeUnitsUnderConstruction;
  533. bool AddrPoolUsed;
  534. friend class DwarfDebug;
  535. NonTypeUnitContext(DwarfDebug *DD);
  536. public:
  537. NonTypeUnitContext(NonTypeUnitContext&&) = default;
  538. ~NonTypeUnitContext();
  539. };
  540. NonTypeUnitContext enterNonTypeUnitContext();
  541. /// Add a label so that arange data can be generated for it.
  542. void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
  543. /// For symbols that have a size designated (e.g. common symbols),
  544. /// this tracks that size.
  545. void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
  546. SymSize[Sym] = Size;
  547. }
  548. /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
  549. /// If not, we still might emit certain cases.
  550. bool useAllLinkageNames() const { return UseAllLinkageNames; }
  551. /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
  552. /// standard DW_OP_form_tls_address opcode
  553. bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
  554. /// Returns whether to use the DWARF2 format for bitfields instyead of the
  555. /// DWARF4 format.
  556. bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
  557. /// Returns whether to use inline strings.
  558. bool useInlineStrings() const { return UseInlineStrings; }
  559. /// Returns whether ranges section should be emitted.
  560. bool useRangesSection() const { return UseRangesSection; }
  561. /// Returns whether range encodings should be used for single entry range
  562. /// lists.
  563. bool alwaysUseRanges() const {
  564. return MinimizeAddr == MinimizeAddrInV5::Ranges;
  565. }
  566. // Returns whether novel exprloc addrx+offset encodings should be used to
  567. // reduce debug_addr size.
  568. bool useAddrOffsetExpressions() const {
  569. return MinimizeAddr == MinimizeAddrInV5::Expressions;
  570. }
  571. // Returns whether addrx+offset LLVM extension form should be used to reduce
  572. // debug_addr size.
  573. bool useAddrOffsetForm() const {
  574. return MinimizeAddr == MinimizeAddrInV5::Form;
  575. }
  576. /// Returns whether to use sections as labels rather than temp symbols.
  577. bool useSectionsAsReferences() const {
  578. return UseSectionsAsReferences;
  579. }
  580. /// Returns whether .debug_loc section should be emitted.
  581. bool useLocSection() const { return UseLocSection; }
  582. /// Returns whether to generate DWARF v4 type units.
  583. bool generateTypeUnits() const { return GenerateTypeUnits; }
  584. // Experimental DWARF5 features.
  585. /// Returns what kind (if any) of accelerator tables to emit.
  586. AccelTableKind getAccelTableKind() const { return TheAccelTableKind; }
  587. bool useAppleExtensionAttributes() const {
  588. return HasAppleExtensionAttributes;
  589. }
  590. /// Returns whether or not to change the current debug info for the
  591. /// split dwarf proposal support.
  592. bool useSplitDwarf() const { return HasSplitDwarf; }
  593. /// Returns whether to generate a string offsets table with (possibly shared)
  594. /// contributions from each CU and type unit. This implies the use of
  595. /// DW_FORM_strx* indirect references with DWARF v5 and beyond. Note that
  596. /// DW_FORM_GNU_str_index is also an indirect reference, but it is used with
  597. /// a pre-DWARF v5 implementation of split DWARF sections, which uses a
  598. /// monolithic string offsets table.
  599. bool useSegmentedStringOffsetsTable() const {
  600. return UseSegmentedStringOffsetsTable;
  601. }
  602. bool emitDebugEntryValues() const {
  603. return EmitDebugEntryValues;
  604. }
  605. bool useOpConvert() const {
  606. return EnableOpConvert;
  607. }
  608. bool shareAcrossDWOCUs() const;
  609. /// Returns the Dwarf Version.
  610. uint16_t getDwarfVersion() const;
  611. /// Returns a suitable DWARF form to represent a section offset, i.e.
  612. /// * DW_FORM_sec_offset for DWARF version >= 4;
  613. /// * DW_FORM_data8 for 64-bit DWARFv3;
  614. /// * DW_FORM_data4 for 32-bit DWARFv3 and DWARFv2.
  615. dwarf::Form getDwarfSectionOffsetForm() const;
  616. /// Returns the previous CU that was being updated
  617. const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
  618. void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
  619. /// Terminate the line table by adding the last range label.
  620. void terminateLineTable(const DwarfCompileUnit *CU);
  621. /// Returns the entries for the .debug_loc section.
  622. const DebugLocStream &getDebugLocs() const { return DebugLocs; }
  623. /// Emit an entry for the debug loc section. This can be used to
  624. /// handle an entry that's going to be emitted into the debug loc section.
  625. void emitDebugLocEntry(ByteStreamer &Streamer,
  626. const DebugLocStream::Entry &Entry,
  627. const DwarfCompileUnit *CU);
  628. /// Emit the location for a debug loc entry, including the size header.
  629. void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
  630. const DwarfCompileUnit *CU);
  631. void addSubprogramNames(const DICompileUnit &CU, const DISubprogram *SP,
  632. DIE &Die);
  633. AddressPool &getAddressPool() { return AddrPool; }
  634. void addAccelName(const DICompileUnit &CU, StringRef Name, const DIE &Die);
  635. void addAccelObjC(const DICompileUnit &CU, StringRef Name, const DIE &Die);
  636. void addAccelNamespace(const DICompileUnit &CU, StringRef Name,
  637. const DIE &Die);
  638. void addAccelType(const DICompileUnit &CU, StringRef Name, const DIE &Die,
  639. char Flags);
  640. const MachineFunction *getCurrentFunction() const { return CurFn; }
  641. /// A helper function to check whether the DIE for a given Scope is
  642. /// going to be null.
  643. bool isLexicalScopeDIENull(LexicalScope *Scope);
  644. /// Find the matching DwarfCompileUnit for the given CU DIE.
  645. DwarfCompileUnit *lookupCU(const DIE *Die) { return CUDieMap.lookup(Die); }
  646. const DwarfCompileUnit *lookupCU(const DIE *Die) const {
  647. return CUDieMap.lookup(Die);
  648. }
  649. unsigned getStringTypeLoc(const DIStringType *ST) const {
  650. return StringTypeLocMap.lookup(ST);
  651. }
  652. void addStringTypeLoc(const DIStringType *ST, unsigned Loc) {
  653. assert(ST);
  654. if (Loc)
  655. StringTypeLocMap[ST] = Loc;
  656. }
  657. /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
  658. ///
  659. /// Returns whether we are "tuning" for a given debugger.
  660. /// @{
  661. bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
  662. bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
  663. bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
  664. bool tuneForDBX() const { return DebuggerTuning == DebuggerKind::DBX; }
  665. /// @}
  666. const MCSymbol *getSectionLabel(const MCSection *S);
  667. void insertSectionLabel(const MCSymbol *S);
  668. static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
  669. const DbgValueLoc &Value,
  670. DwarfExpression &DwarfExpr);
  671. /// If the \p File has an MD5 checksum, return it as an MD5Result
  672. /// allocated in the MCContext.
  673. Optional<MD5::MD5Result> getMD5AsBytes(const DIFile *File) const;
  674. };
  675. } // end namespace llvm
  676. #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H