MCContext.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_MC_MCCONTEXT_H
  14. #define LLVM_MC_MCCONTEXT_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/SetVector.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringMap.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/BinaryFormat/Dwarf.h"
  24. #include "llvm/BinaryFormat/ELF.h"
  25. #include "llvm/BinaryFormat/XCOFF.h"
  26. #include "llvm/MC/MCAsmMacro.h"
  27. #include "llvm/MC/MCDwarf.h"
  28. #include "llvm/MC/MCPseudoProbe.h"
  29. #include "llvm/MC/MCSubtargetInfo.h"
  30. #include "llvm/MC/MCTargetOptions.h"
  31. #include "llvm/MC/SectionKind.h"
  32. #include "llvm/Support/Allocator.h"
  33. #include "llvm/Support/Compiler.h"
  34. #include "llvm/Support/Error.h"
  35. #include "llvm/Support/MD5.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <algorithm>
  38. #include <cassert>
  39. #include <cstddef>
  40. #include <cstdint>
  41. #include <functional>
  42. #include <map>
  43. #include <memory>
  44. #include <string>
  45. #include <utility>
  46. #include <vector>
  47. namespace llvm {
  48. class CodeViewContext;
  49. class MCAsmInfo;
  50. class MCLabel;
  51. class MCObjectFileInfo;
  52. class MCRegisterInfo;
  53. class MCSection;
  54. class MCSectionCOFF;
  55. class MCSectionELF;
  56. class MCSectionGOFF;
  57. class MCSectionMachO;
  58. class MCSectionWasm;
  59. class MCSectionXCOFF;
  60. class MCStreamer;
  61. class MCSymbol;
  62. class MCSymbolELF;
  63. class MCSymbolWasm;
  64. class MCSymbolXCOFF;
  65. class MDNode;
  66. class SMDiagnostic;
  67. class SMLoc;
  68. class SourceMgr;
  69. /// Context object for machine code objects. This class owns all of the
  70. /// sections that it creates.
  71. ///
  72. class MCContext {
  73. public:
  74. using SymbolTable = StringMap<MCSymbol *, BumpPtrAllocator &>;
  75. using DiagHandlerTy =
  76. std::function<void(const SMDiagnostic &, bool, const SourceMgr &,
  77. std::vector<const MDNode *> &)>;
  78. enum Environment { IsMachO, IsELF, IsGOFF, IsCOFF, IsWasm, IsXCOFF };
  79. private:
  80. Environment Env;
  81. /// The name of the Segment where Swift5 Reflection Section data will be
  82. /// outputted
  83. StringRef Swift5ReflectionSegmentName;
  84. /// The triple for this object.
  85. Triple TT;
  86. /// The SourceMgr for this object, if any.
  87. const SourceMgr *SrcMgr;
  88. /// The SourceMgr for inline assembly, if any.
  89. std::unique_ptr<SourceMgr> InlineSrcMgr;
  90. std::vector<const MDNode *> LocInfos;
  91. DiagHandlerTy DiagHandler;
  92. /// The MCAsmInfo for this target.
  93. const MCAsmInfo *MAI;
  94. /// The MCRegisterInfo for this target.
  95. const MCRegisterInfo *MRI;
  96. /// The MCObjectFileInfo for this target.
  97. const MCObjectFileInfo *MOFI;
  98. /// The MCSubtargetInfo for this target.
  99. const MCSubtargetInfo *MSTI;
  100. std::unique_ptr<CodeViewContext> CVContext;
  101. /// Allocator object used for creating machine code objects.
  102. ///
  103. /// We use a bump pointer allocator to avoid the need to track all allocated
  104. /// objects.
  105. BumpPtrAllocator Allocator;
  106. SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
  107. SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
  108. SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
  109. SpecificBumpPtrAllocator<MCSectionGOFF> GOFFAllocator;
  110. SpecificBumpPtrAllocator<MCSectionWasm> WasmAllocator;
  111. SpecificBumpPtrAllocator<MCSectionXCOFF> XCOFFAllocator;
  112. SpecificBumpPtrAllocator<MCInst> MCInstAllocator;
  113. /// Bindings of names to symbols.
  114. SymbolTable Symbols;
  115. /// A mapping from a local label number and an instance count to a symbol.
  116. /// For example, in the assembly
  117. /// 1:
  118. /// 2:
  119. /// 1:
  120. /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
  121. DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
  122. /// Keeps tracks of names that were used both for used declared and
  123. /// artificial symbols. The value is "true" if the name has been used for a
  124. /// non-section symbol (there can be at most one of those, plus an unlimited
  125. /// number of section symbols with the same name).
  126. StringMap<bool, BumpPtrAllocator &> UsedNames;
  127. /// Keeps track of labels that are used in inline assembly.
  128. SymbolTable InlineAsmUsedLabelNames;
  129. /// The next ID to dole out to an unnamed assembler temporary symbol with
  130. /// a given prefix.
  131. StringMap<unsigned> NextID;
  132. /// Instances of directional local labels.
  133. DenseMap<unsigned, MCLabel *> Instances;
  134. /// NextInstance() creates the next instance of the directional local label
  135. /// for the LocalLabelVal and adds it to the map if needed.
  136. unsigned NextInstance(unsigned LocalLabelVal);
  137. /// GetInstance() gets the current instance of the directional local label
  138. /// for the LocalLabelVal and adds it to the map if needed.
  139. unsigned GetInstance(unsigned LocalLabelVal);
  140. /// The file name of the log file from the environment variable
  141. /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
  142. /// directive is used or it is an error.
  143. char *SecureLogFile;
  144. /// The stream that gets written to for the .secure_log_unique directive.
  145. std::unique_ptr<raw_fd_ostream> SecureLog;
  146. /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
  147. /// catch errors if .secure_log_unique appears twice without
  148. /// .secure_log_reset appearing between them.
  149. bool SecureLogUsed = false;
  150. /// The compilation directory to use for DW_AT_comp_dir.
  151. SmallString<128> CompilationDir;
  152. /// Prefix replacement map for source file information.
  153. std::map<const std::string, const std::string> DebugPrefixMap;
  154. /// The main file name if passed in explicitly.
  155. std::string MainFileName;
  156. /// The dwarf file and directory tables from the dwarf .file directive.
  157. /// We now emit a line table for each compile unit. To reduce the prologue
  158. /// size of each line table, the files and directories used by each compile
  159. /// unit are separated.
  160. std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
  161. /// The current dwarf line information from the last dwarf .loc directive.
  162. MCDwarfLoc CurrentDwarfLoc;
  163. bool DwarfLocSeen = false;
  164. /// Generate dwarf debugging info for assembly source files.
  165. bool GenDwarfForAssembly = false;
  166. /// The current dwarf file number when generate dwarf debugging info for
  167. /// assembly source files.
  168. unsigned GenDwarfFileNumber = 0;
  169. /// Sections for generating the .debug_ranges and .debug_aranges sections.
  170. SetVector<MCSection *> SectionsForRanges;
  171. /// The information gathered from labels that will have dwarf label
  172. /// entries when generating dwarf assembly source files.
  173. std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
  174. /// The string to embed in the debug information for the compile unit, if
  175. /// non-empty.
  176. StringRef DwarfDebugFlags;
  177. /// The string to embed in as the dwarf AT_producer for the compile unit, if
  178. /// non-empty.
  179. StringRef DwarfDebugProducer;
  180. /// The maximum version of dwarf that we should emit.
  181. uint16_t DwarfVersion = 4;
  182. /// The format of dwarf that we emit.
  183. dwarf::DwarfFormat DwarfFormat = dwarf::DWARF32;
  184. /// Honor temporary labels, this is useful for debugging semantic
  185. /// differences between temporary and non-temporary labels (primarily on
  186. /// Darwin).
  187. bool AllowTemporaryLabels = true;
  188. bool UseNamesOnTempLabels = false;
  189. /// The Compile Unit ID that we are currently processing.
  190. unsigned DwarfCompileUnitID = 0;
  191. /// A collection of MCPseudoProbe in the current module
  192. MCPseudoProbeTable PseudoProbeTable;
  193. // Sections are differentiated by the quadruple (section_name, group_name,
  194. // unique_id, link_to_symbol_name). Sections sharing the same quadruple are
  195. // combined into one section.
  196. struct ELFSectionKey {
  197. std::string SectionName;
  198. StringRef GroupName;
  199. StringRef LinkedToName;
  200. unsigned UniqueID;
  201. ELFSectionKey(StringRef SectionName, StringRef GroupName,
  202. StringRef LinkedToName, unsigned UniqueID)
  203. : SectionName(SectionName), GroupName(GroupName),
  204. LinkedToName(LinkedToName), UniqueID(UniqueID) {}
  205. bool operator<(const ELFSectionKey &Other) const {
  206. if (SectionName != Other.SectionName)
  207. return SectionName < Other.SectionName;
  208. if (GroupName != Other.GroupName)
  209. return GroupName < Other.GroupName;
  210. if (int O = LinkedToName.compare(Other.LinkedToName))
  211. return O < 0;
  212. return UniqueID < Other.UniqueID;
  213. }
  214. };
  215. struct COFFSectionKey {
  216. std::string SectionName;
  217. StringRef GroupName;
  218. int SelectionKey;
  219. unsigned UniqueID;
  220. COFFSectionKey(StringRef SectionName, StringRef GroupName,
  221. int SelectionKey, unsigned UniqueID)
  222. : SectionName(SectionName), GroupName(GroupName),
  223. SelectionKey(SelectionKey), UniqueID(UniqueID) {}
  224. bool operator<(const COFFSectionKey &Other) const {
  225. if (SectionName != Other.SectionName)
  226. return SectionName < Other.SectionName;
  227. if (GroupName != Other.GroupName)
  228. return GroupName < Other.GroupName;
  229. if (SelectionKey != Other.SelectionKey)
  230. return SelectionKey < Other.SelectionKey;
  231. return UniqueID < Other.UniqueID;
  232. }
  233. };
  234. struct WasmSectionKey {
  235. std::string SectionName;
  236. StringRef GroupName;
  237. unsigned UniqueID;
  238. WasmSectionKey(StringRef SectionName, StringRef GroupName,
  239. unsigned UniqueID)
  240. : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
  241. }
  242. bool operator<(const WasmSectionKey &Other) const {
  243. if (SectionName != Other.SectionName)
  244. return SectionName < Other.SectionName;
  245. if (GroupName != Other.GroupName)
  246. return GroupName < Other.GroupName;
  247. return UniqueID < Other.UniqueID;
  248. }
  249. };
  250. struct XCOFFSectionKey {
  251. // Section name.
  252. std::string SectionName;
  253. // Section property.
  254. // For csect section, it is storage mapping class.
  255. // For debug section, it is section type flags.
  256. union {
  257. XCOFF::StorageMappingClass MappingClass;
  258. XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags;
  259. };
  260. bool IsCsect;
  261. XCOFFSectionKey(StringRef SectionName,
  262. XCOFF::StorageMappingClass MappingClass)
  263. : SectionName(SectionName), MappingClass(MappingClass),
  264. IsCsect(true) {}
  265. XCOFFSectionKey(StringRef SectionName,
  266. XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags)
  267. : SectionName(SectionName), DwarfSubtypeFlags(DwarfSubtypeFlags),
  268. IsCsect(false) {}
  269. bool operator<(const XCOFFSectionKey &Other) const {
  270. if (IsCsect && Other.IsCsect)
  271. return std::tie(SectionName, MappingClass) <
  272. std::tie(Other.SectionName, Other.MappingClass);
  273. if (IsCsect != Other.IsCsect)
  274. return IsCsect;
  275. return std::tie(SectionName, DwarfSubtypeFlags) <
  276. std::tie(Other.SectionName, Other.DwarfSubtypeFlags);
  277. }
  278. };
  279. StringMap<MCSectionMachO *> MachOUniquingMap;
  280. std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
  281. std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
  282. std::map<std::string, MCSectionGOFF *> GOFFUniquingMap;
  283. std::map<WasmSectionKey, MCSectionWasm *> WasmUniquingMap;
  284. std::map<XCOFFSectionKey, MCSectionXCOFF *> XCOFFUniquingMap;
  285. StringMap<bool> RelSecNames;
  286. SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
  287. /// Do automatic reset in destructor
  288. bool AutoReset;
  289. MCTargetOptions const *TargetOptions;
  290. bool HadError = false;
  291. void reportCommon(SMLoc Loc,
  292. std::function<void(SMDiagnostic &, const SourceMgr *)>);
  293. MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
  294. bool CanBeUnnamed);
  295. MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
  296. bool IsTemporary);
  297. MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
  298. unsigned Instance);
  299. MCSectionELF *createELFSectionImpl(StringRef Section, unsigned Type,
  300. unsigned Flags, SectionKind K,
  301. unsigned EntrySize,
  302. const MCSymbolELF *Group, bool IsComdat,
  303. unsigned UniqueID,
  304. const MCSymbolELF *LinkedToSym);
  305. MCSymbolXCOFF *createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
  306. bool IsTemporary);
  307. /// Map of currently defined macros.
  308. StringMap<MCAsmMacro> MacroMap;
  309. struct ELFEntrySizeKey {
  310. std::string SectionName;
  311. unsigned Flags;
  312. unsigned EntrySize;
  313. ELFEntrySizeKey(StringRef SectionName, unsigned Flags, unsigned EntrySize)
  314. : SectionName(SectionName), Flags(Flags), EntrySize(EntrySize) {}
  315. bool operator<(const ELFEntrySizeKey &Other) const {
  316. if (SectionName != Other.SectionName)
  317. return SectionName < Other.SectionName;
  318. if (Flags != Other.Flags)
  319. return Flags < Other.Flags;
  320. return EntrySize < Other.EntrySize;
  321. }
  322. };
  323. // Symbols must be assigned to a section with a compatible entry size and
  324. // flags. This map is used to assign unique IDs to sections to distinguish
  325. // between sections with identical names but incompatible entry sizes and/or
  326. // flags. This can occur when a symbol is explicitly assigned to a section,
  327. // e.g. via __attribute__((section("myname"))).
  328. std::map<ELFEntrySizeKey, unsigned> ELFEntrySizeMap;
  329. // This set is used to record the generic mergeable section names seen.
  330. // These are sections that are created as mergeable e.g. .debug_str. We need
  331. // to avoid assigning non-mergeable symbols to these sections. It is used
  332. // to prevent non-mergeable symbols being explicitly assigned to mergeable
  333. // sections (e.g. via _attribute_((section("myname")))).
  334. DenseSet<StringRef> ELFSeenGenericMergeableSections;
  335. public:
  336. explicit MCContext(const Triple &TheTriple, const MCAsmInfo *MAI,
  337. const MCRegisterInfo *MRI, const MCSubtargetInfo *MSTI,
  338. const SourceMgr *Mgr = nullptr,
  339. MCTargetOptions const *TargetOpts = nullptr,
  340. bool DoAutoReset = true,
  341. StringRef Swift5ReflSegmentName = {});
  342. MCContext(const MCContext &) = delete;
  343. MCContext &operator=(const MCContext &) = delete;
  344. ~MCContext();
  345. Environment getObjectFileType() const { return Env; }
  346. const StringRef &getSwift5ReflectionSegmentName() const {
  347. return Swift5ReflectionSegmentName;
  348. }
  349. const Triple &getTargetTriple() const { return TT; }
  350. const SourceMgr *getSourceManager() const { return SrcMgr; }
  351. void initInlineSourceManager();
  352. SourceMgr *getInlineSourceManager() {
  353. return InlineSrcMgr.get();
  354. }
  355. std::vector<const MDNode *> &getLocInfos() { return LocInfos; }
  356. void setDiagnosticHandler(DiagHandlerTy DiagHandler) {
  357. this->DiagHandler = DiagHandler;
  358. }
  359. void setObjectFileInfo(const MCObjectFileInfo *Mofi) { MOFI = Mofi; }
  360. const MCAsmInfo *getAsmInfo() const { return MAI; }
  361. const MCRegisterInfo *getRegisterInfo() const { return MRI; }
  362. const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
  363. const MCSubtargetInfo *getSubtargetInfo() const { return MSTI; }
  364. CodeViewContext &getCVContext();
  365. void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
  366. void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
  367. /// \name Module Lifetime Management
  368. /// @{
  369. /// reset - return object to right after construction state to prepare
  370. /// to process a new module
  371. void reset();
  372. /// @}
  373. /// \name McInst Management
  374. /// Create and return a new MC instruction.
  375. MCInst *createMCInst();
  376. /// \name Symbol Management
  377. /// @{
  378. /// Create and return a new linker temporary symbol with a unique but
  379. /// unspecified name.
  380. MCSymbol *createLinkerPrivateTempSymbol();
  381. /// Create a temporary symbol with a unique name. The name will be omitted
  382. /// in the symbol table if UseNamesOnTempLabels is false (default except
  383. /// MCAsmStreamer). The overload without Name uses an unspecified name.
  384. MCSymbol *createTempSymbol();
  385. MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix = true);
  386. /// Create a temporary symbol with a unique name whose name cannot be
  387. /// omitted in the symbol table. This is rarely used.
  388. MCSymbol *createNamedTempSymbol();
  389. MCSymbol *createNamedTempSymbol(const Twine &Name);
  390. /// Create the definition of a directional local symbol for numbered label
  391. /// (used for "1:" definitions).
  392. MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
  393. /// Create and return a directional local symbol for numbered label (used
  394. /// for "1b" or 1f" references).
  395. MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
  396. /// Lookup the symbol inside with the specified \p Name. If it exists,
  397. /// return it. If not, create a forward reference and return it.
  398. ///
  399. /// \param Name - The symbol name, which must be unique across all symbols.
  400. MCSymbol *getOrCreateSymbol(const Twine &Name);
  401. /// Gets a symbol that will be defined to the final stack offset of a local
  402. /// variable after codegen.
  403. ///
  404. /// \param Idx - The index of a local variable passed to \@llvm.localescape.
  405. MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
  406. MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
  407. MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
  408. /// Get the symbol for \p Name, or null.
  409. MCSymbol *lookupSymbol(const Twine &Name) const;
  410. /// Set value for a symbol.
  411. void setSymbolValue(MCStreamer &Streamer, StringRef Sym, uint64_t Val);
  412. /// getSymbols - Get a reference for the symbol table for clients that
  413. /// want to, for example, iterate over all symbols. 'const' because we
  414. /// still want any modifications to the table itself to use the MCContext
  415. /// APIs.
  416. const SymbolTable &getSymbols() const { return Symbols; }
  417. /// isInlineAsmLabel - Return true if the name is a label referenced in
  418. /// inline assembly.
  419. MCSymbol *getInlineAsmLabel(StringRef Name) const {
  420. return InlineAsmUsedLabelNames.lookup(Name);
  421. }
  422. /// registerInlineAsmLabel - Records that the name is a label referenced in
  423. /// inline assembly.
  424. void registerInlineAsmLabel(MCSymbol *Sym);
  425. /// @}
  426. /// \name Section Management
  427. /// @{
  428. enum : unsigned {
  429. /// Pass this value as the UniqueID during section creation to get the
  430. /// generic section with the given name and characteristics. The usual
  431. /// sections such as .text use this ID.
  432. GenericSectionID = ~0U
  433. };
  434. /// Return the MCSection for the specified mach-o section. This requires
  435. /// the operands to be valid.
  436. MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
  437. unsigned TypeAndAttributes,
  438. unsigned Reserved2, SectionKind K,
  439. const char *BeginSymName = nullptr);
  440. MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
  441. unsigned TypeAndAttributes, SectionKind K,
  442. const char *BeginSymName = nullptr) {
  443. return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
  444. BeginSymName);
  445. }
  446. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  447. unsigned Flags) {
  448. return getELFSection(Section, Type, Flags, 0, "", false);
  449. }
  450. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  451. unsigned Flags, unsigned EntrySize) {
  452. return getELFSection(Section, Type, Flags, EntrySize, "", false,
  453. MCSection::NonUniqueID, nullptr);
  454. }
  455. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  456. unsigned Flags, unsigned EntrySize,
  457. const Twine &Group, bool IsComdat) {
  458. return getELFSection(Section, Type, Flags, EntrySize, Group, IsComdat,
  459. MCSection::NonUniqueID, nullptr);
  460. }
  461. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  462. unsigned Flags, unsigned EntrySize,
  463. const Twine &Group, bool IsComdat,
  464. unsigned UniqueID,
  465. const MCSymbolELF *LinkedToSym);
  466. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  467. unsigned Flags, unsigned EntrySize,
  468. const MCSymbolELF *Group, bool IsComdat,
  469. unsigned UniqueID,
  470. const MCSymbolELF *LinkedToSym);
  471. /// Get a section with the provided group identifier. This section is
  472. /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
  473. /// describes the type of the section and \p Flags are used to further
  474. /// configure this named section.
  475. MCSectionELF *getELFNamedSection(const Twine &Prefix, const Twine &Suffix,
  476. unsigned Type, unsigned Flags,
  477. unsigned EntrySize = 0);
  478. MCSectionELF *createELFRelSection(const Twine &Name, unsigned Type,
  479. unsigned Flags, unsigned EntrySize,
  480. const MCSymbolELF *Group,
  481. const MCSectionELF *RelInfoSection);
  482. void renameELFSection(MCSectionELF *Section, StringRef Name);
  483. MCSectionELF *createELFGroupSection(const MCSymbolELF *Group,
  484. bool IsComdat);
  485. void recordELFMergeableSectionInfo(StringRef SectionName, unsigned Flags,
  486. unsigned UniqueID, unsigned EntrySize);
  487. bool isELFImplicitMergeableSectionNamePrefix(StringRef Name);
  488. bool isELFGenericMergeableSection(StringRef Name);
  489. /// Return the unique ID of the section with the given name, flags and entry
  490. /// size, if it exists.
  491. Optional<unsigned> getELFUniqueIDForEntsize(StringRef SectionName,
  492. unsigned Flags,
  493. unsigned EntrySize);
  494. MCSectionGOFF *getGOFFSection(StringRef Section, SectionKind Kind);
  495. MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
  496. SectionKind Kind, StringRef COMDATSymName,
  497. int Selection,
  498. unsigned UniqueID = GenericSectionID,
  499. const char *BeginSymName = nullptr);
  500. MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
  501. SectionKind Kind,
  502. const char *BeginSymName = nullptr);
  503. /// Gets or creates a section equivalent to Sec that is associated with the
  504. /// section containing KeySym. For example, to create a debug info section
  505. /// associated with an inline function, pass the normal debug info section
  506. /// as Sec and the function symbol as KeySym.
  507. MCSectionCOFF *
  508. getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
  509. unsigned UniqueID = GenericSectionID);
  510. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  511. unsigned Flags = 0) {
  512. return getWasmSection(Section, K, Flags, nullptr);
  513. }
  514. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  515. unsigned Flags, const char *BeginSymName) {
  516. return getWasmSection(Section, K, Flags, "", ~0, BeginSymName);
  517. }
  518. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  519. unsigned Flags, const Twine &Group,
  520. unsigned UniqueID) {
  521. return getWasmSection(Section, K, Flags, Group, UniqueID, nullptr);
  522. }
  523. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  524. unsigned Flags, const Twine &Group,
  525. unsigned UniqueID, const char *BeginSymName);
  526. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  527. unsigned Flags, const MCSymbolWasm *Group,
  528. unsigned UniqueID, const char *BeginSymName);
  529. MCSectionXCOFF *getXCOFFSection(
  530. StringRef Section, SectionKind K,
  531. Optional<XCOFF::CsectProperties> CsectProp = None,
  532. bool MultiSymbolsAllowed = false, const char *BeginSymName = nullptr,
  533. Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSubtypeFlags = None);
  534. // Create and save a copy of STI and return a reference to the copy.
  535. MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
  536. /// @}
  537. /// \name Dwarf Management
  538. /// @{
  539. /// Get the compilation directory for DW_AT_comp_dir
  540. /// The compilation directory should be set with \c setCompilationDir before
  541. /// calling this function. If it is unset, an empty string will be returned.
  542. StringRef getCompilationDir() const { return CompilationDir; }
  543. /// Set the compilation directory for DW_AT_comp_dir
  544. void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
  545. /// Add an entry to the debug prefix map.
  546. void addDebugPrefixMapEntry(const std::string &From, const std::string &To);
  547. // Remaps all debug directory paths in-place as per the debug prefix map.
  548. void RemapDebugPaths();
  549. /// Get the main file name for use in error messages and debug
  550. /// info. This can be set to ensure we've got the correct file name
  551. /// after preprocessing or for -save-temps.
  552. const std::string &getMainFileName() const { return MainFileName; }
  553. /// Set the main file name and override the default.
  554. void setMainFileName(StringRef S) { MainFileName = std::string(S); }
  555. /// Creates an entry in the dwarf file and directory tables.
  556. Expected<unsigned> getDwarfFile(StringRef Directory, StringRef FileName,
  557. unsigned FileNumber,
  558. Optional<MD5::MD5Result> Checksum,
  559. Optional<StringRef> Source, unsigned CUID);
  560. bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
  561. const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
  562. return MCDwarfLineTablesCUMap;
  563. }
  564. MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
  565. return MCDwarfLineTablesCUMap[CUID];
  566. }
  567. const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
  568. auto I = MCDwarfLineTablesCUMap.find(CUID);
  569. assert(I != MCDwarfLineTablesCUMap.end());
  570. return I->second;
  571. }
  572. const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
  573. return getMCDwarfLineTable(CUID).getMCDwarfFiles();
  574. }
  575. const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
  576. return getMCDwarfLineTable(CUID).getMCDwarfDirs();
  577. }
  578. unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
  579. void setDwarfCompileUnitID(unsigned CUIndex) {
  580. DwarfCompileUnitID = CUIndex;
  581. }
  582. /// Specifies the "root" file and directory of the compilation unit.
  583. /// These are "file 0" and "directory 0" in DWARF v5.
  584. void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir,
  585. StringRef Filename,
  586. Optional<MD5::MD5Result> Checksum,
  587. Optional<StringRef> Source) {
  588. getMCDwarfLineTable(CUID).setRootFile(CompilationDir, Filename, Checksum,
  589. Source);
  590. }
  591. /// Reports whether MD5 checksum usage is consistent (all-or-none).
  592. bool isDwarfMD5UsageConsistent(unsigned CUID) const {
  593. return getMCDwarfLineTable(CUID).isMD5UsageConsistent();
  594. }
  595. /// Saves the information from the currently parsed dwarf .loc directive
  596. /// and sets DwarfLocSeen. When the next instruction is assembled an entry
  597. /// in the line number table with this information and the address of the
  598. /// instruction will be created.
  599. void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
  600. unsigned Flags, unsigned Isa,
  601. unsigned Discriminator) {
  602. CurrentDwarfLoc.setFileNum(FileNum);
  603. CurrentDwarfLoc.setLine(Line);
  604. CurrentDwarfLoc.setColumn(Column);
  605. CurrentDwarfLoc.setFlags(Flags);
  606. CurrentDwarfLoc.setIsa(Isa);
  607. CurrentDwarfLoc.setDiscriminator(Discriminator);
  608. DwarfLocSeen = true;
  609. }
  610. void clearDwarfLocSeen() { DwarfLocSeen = false; }
  611. bool getDwarfLocSeen() { return DwarfLocSeen; }
  612. const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
  613. bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
  614. void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
  615. unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
  616. void setGenDwarfFileNumber(unsigned FileNumber) {
  617. GenDwarfFileNumber = FileNumber;
  618. }
  619. /// Specifies information about the "root file" for assembler clients
  620. /// (e.g., llvm-mc). Assumes compilation dir etc. have been set up.
  621. void setGenDwarfRootFile(StringRef FileName, StringRef Buffer);
  622. const SetVector<MCSection *> &getGenDwarfSectionSyms() {
  623. return SectionsForRanges;
  624. }
  625. bool addGenDwarfSection(MCSection *Sec) {
  626. return SectionsForRanges.insert(Sec);
  627. }
  628. void finalizeDwarfSections(MCStreamer &MCOS);
  629. const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
  630. return MCGenDwarfLabelEntries;
  631. }
  632. void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
  633. MCGenDwarfLabelEntries.push_back(E);
  634. }
  635. void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
  636. StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
  637. void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
  638. StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
  639. void setDwarfFormat(dwarf::DwarfFormat f) { DwarfFormat = f; }
  640. dwarf::DwarfFormat getDwarfFormat() const { return DwarfFormat; }
  641. void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
  642. uint16_t getDwarfVersion() const { return DwarfVersion; }
  643. /// @}
  644. char *getSecureLogFile() { return SecureLogFile; }
  645. raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
  646. void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
  647. SecureLog = std::move(Value);
  648. }
  649. bool getSecureLogUsed() { return SecureLogUsed; }
  650. void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
  651. void *allocate(unsigned Size, unsigned Align = 8) {
  652. return Allocator.Allocate(Size, Align);
  653. }
  654. void deallocate(void *Ptr) {}
  655. bool hadError() { return HadError; }
  656. void diagnose(const SMDiagnostic &SMD);
  657. void reportError(SMLoc L, const Twine &Msg);
  658. void reportWarning(SMLoc L, const Twine &Msg);
  659. const MCAsmMacro *lookupMacro(StringRef Name) {
  660. StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
  661. return (I == MacroMap.end()) ? nullptr : &I->getValue();
  662. }
  663. void defineMacro(StringRef Name, MCAsmMacro Macro) {
  664. MacroMap.insert(std::make_pair(Name, std::move(Macro)));
  665. }
  666. void undefineMacro(StringRef Name) { MacroMap.erase(Name); }
  667. MCPseudoProbeTable &getMCPseudoProbeTable() { return PseudoProbeTable; }
  668. };
  669. } // end namespace llvm
  670. // operator new and delete aren't allowed inside namespaces.
  671. // The throw specifications are mandated by the standard.
  672. /// Placement new for using the MCContext's allocator.
  673. ///
  674. /// This placement form of operator new uses the MCContext's allocator for
  675. /// obtaining memory. It is a non-throwing new, which means that it returns
  676. /// null on error. (If that is what the allocator does. The current does, so if
  677. /// this ever changes, this operator will have to be changed, too.)
  678. /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
  679. /// \code
  680. /// // Default alignment (8)
  681. /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
  682. /// // Specific alignment
  683. /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
  684. /// \endcode
  685. /// Please note that you cannot use delete on the pointer; it must be
  686. /// deallocated using an explicit destructor call followed by
  687. /// \c Context.Deallocate(Ptr).
  688. ///
  689. /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
  690. /// \param C The MCContext that provides the allocator.
  691. /// \param Alignment The alignment of the allocated memory (if the underlying
  692. /// allocator supports it).
  693. /// \return The allocated memory. Could be NULL.
  694. inline void *operator new(size_t Bytes, llvm::MCContext &C,
  695. size_t Alignment = 8) noexcept {
  696. return C.allocate(Bytes, Alignment);
  697. }
  698. /// Placement delete companion to the new above.
  699. ///
  700. /// This operator is just a companion to the new above. There is no way of
  701. /// invoking it directly; see the new operator for more details. This operator
  702. /// is called implicitly by the compiler if a placement new expression using
  703. /// the MCContext throws in the object constructor.
  704. inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept {
  705. C.deallocate(Ptr);
  706. }
  707. /// This placement form of operator new[] uses the MCContext's allocator for
  708. /// obtaining memory. It is a non-throwing new[], which means that it returns
  709. /// null on error.
  710. /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
  711. /// \code
  712. /// // Default alignment (8)
  713. /// char *data = new (Context) char[10];
  714. /// // Specific alignment
  715. /// char *data = new (Context, 4) char[10];
  716. /// \endcode
  717. /// Please note that you cannot use delete on the pointer; it must be
  718. /// deallocated using an explicit destructor call followed by
  719. /// \c Context.Deallocate(Ptr).
  720. ///
  721. /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
  722. /// \param C The MCContext that provides the allocator.
  723. /// \param Alignment The alignment of the allocated memory (if the underlying
  724. /// allocator supports it).
  725. /// \return The allocated memory. Could be NULL.
  726. inline void *operator new[](size_t Bytes, llvm::MCContext &C,
  727. size_t Alignment = 8) noexcept {
  728. return C.allocate(Bytes, Alignment);
  729. }
  730. /// Placement delete[] companion to the new[] above.
  731. ///
  732. /// This operator is just a companion to the new[] above. There is no way of
  733. /// invoking it directly; see the new[] operator for more details. This operator
  734. /// is called implicitly by the compiler if a placement new[] expression using
  735. /// the MCContext throws in the object constructor.
  736. inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept {
  737. C.deallocate(Ptr);
  738. }
  739. #endif // LLVM_MC_MCCONTEXT_H
  740. #ifdef __GNUC__
  741. #pragma GCC diagnostic pop
  742. #endif