AsmPrinter.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework ---------*- 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. //
  14. // This file contains a class to be used as the base class for target specific
  15. // asm writers. This class primarily handles common functionality used by
  16. // all asm writers.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_CODEGEN_ASMPRINTER_H
  20. #define LLVM_CODEGEN_ASMPRINTER_H
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/DenseSet.h"
  23. #include "llvm/ADT/MapVector.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/BinaryFormat/Dwarf.h"
  26. #include "llvm/CodeGen/AsmPrinterHandler.h"
  27. #include "llvm/CodeGen/DwarfStringPoolEntry.h"
  28. #include "llvm/CodeGen/MachineFunctionPass.h"
  29. #include "llvm/CodeGen/StackMaps.h"
  30. #include "llvm/IR/InlineAsm.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include <cstdint>
  33. #include <memory>
  34. #include <utility>
  35. #include <vector>
  36. namespace llvm {
  37. class AddrLabelMap;
  38. class BasicBlock;
  39. class BlockAddress;
  40. class Constant;
  41. class ConstantArray;
  42. class DataLayout;
  43. class DIE;
  44. class DIEAbbrev;
  45. class DwarfDebug;
  46. class GCMetadataPrinter;
  47. class GCStrategy;
  48. class GlobalAlias;
  49. class GlobalObject;
  50. class GlobalValue;
  51. class GlobalVariable;
  52. class MachineBasicBlock;
  53. class MachineConstantPoolValue;
  54. class MachineDominatorTree;
  55. class MachineFunction;
  56. class MachineInstr;
  57. class MachineJumpTableInfo;
  58. class MachineLoopInfo;
  59. class MachineModuleInfo;
  60. class MachineOptimizationRemarkEmitter;
  61. class MCAsmInfo;
  62. class MCCFIInstruction;
  63. class MCContext;
  64. class MCExpr;
  65. class MCInst;
  66. class MCSection;
  67. class MCStreamer;
  68. class MCSubtargetInfo;
  69. class MCSymbol;
  70. class MCTargetOptions;
  71. class MDNode;
  72. class Module;
  73. class PseudoProbeHandler;
  74. class raw_ostream;
  75. class StringRef;
  76. class TargetLoweringObjectFile;
  77. class TargetMachine;
  78. class Twine;
  79. namespace remarks {
  80. class RemarkStreamer;
  81. }
  82. /// This class is intended to be used as a driving class for all asm writers.
  83. class AsmPrinter : public MachineFunctionPass {
  84. public:
  85. /// Target machine description.
  86. TargetMachine &TM;
  87. /// Target Asm Printer information.
  88. const MCAsmInfo *MAI;
  89. /// This is the context for the output file that we are streaming. This owns
  90. /// all of the global MC-related objects for the generated translation unit.
  91. MCContext &OutContext;
  92. /// This is the MCStreamer object for the file we are generating. This
  93. /// contains the transient state for the current translation unit that we are
  94. /// generating (such as the current section etc).
  95. std::unique_ptr<MCStreamer> OutStreamer;
  96. /// The current machine function.
  97. MachineFunction *MF = nullptr;
  98. /// This is a pointer to the current MachineModuleInfo.
  99. MachineModuleInfo *MMI = nullptr;
  100. /// This is a pointer to the current MachineDominatorTree.
  101. MachineDominatorTree *MDT = nullptr;
  102. /// This is a pointer to the current MachineLoopInfo.
  103. MachineLoopInfo *MLI = nullptr;
  104. /// Optimization remark emitter.
  105. MachineOptimizationRemarkEmitter *ORE;
  106. /// The symbol for the entry in __patchable_function_entires.
  107. MCSymbol *CurrentPatchableFunctionEntrySym = nullptr;
  108. /// The symbol for the current function. This is recalculated at the beginning
  109. /// of each call to runOnMachineFunction().
  110. MCSymbol *CurrentFnSym = nullptr;
  111. /// The symbol for the current function descriptor on AIX. This is created
  112. /// at the beginning of each call to SetupMachineFunction().
  113. MCSymbol *CurrentFnDescSym = nullptr;
  114. /// The symbol used to represent the start of the current function for the
  115. /// purpose of calculating its size (e.g. using the .size directive). By
  116. /// default, this is equal to CurrentFnSym.
  117. MCSymbol *CurrentFnSymForSize = nullptr;
  118. /// Map a basic block section ID to the begin and end symbols of that section
  119. /// which determine the section's range.
  120. struct MBBSectionRange {
  121. MCSymbol *BeginLabel, *EndLabel;
  122. };
  123. MapVector<unsigned, MBBSectionRange> MBBSectionRanges;
  124. /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of
  125. /// its number of uses by other globals.
  126. using GOTEquivUsePair = std::pair<const GlobalVariable *, unsigned>;
  127. MapVector<const MCSymbol *, GOTEquivUsePair> GlobalGOTEquivs;
  128. /// struct HandlerInfo and Handlers permit users or target extended
  129. /// AsmPrinter to add their own handlers.
  130. struct HandlerInfo {
  131. std::unique_ptr<AsmPrinterHandler> Handler;
  132. StringRef TimerName;
  133. StringRef TimerDescription;
  134. StringRef TimerGroupName;
  135. StringRef TimerGroupDescription;
  136. HandlerInfo(std::unique_ptr<AsmPrinterHandler> Handler, StringRef TimerName,
  137. StringRef TimerDescription, StringRef TimerGroupName,
  138. StringRef TimerGroupDescription)
  139. : Handler(std::move(Handler)), TimerName(TimerName),
  140. TimerDescription(TimerDescription), TimerGroupName(TimerGroupName),
  141. TimerGroupDescription(TimerGroupDescription) {}
  142. };
  143. // Flags representing which CFI section is required for a function/module.
  144. enum class CFISection : unsigned {
  145. None = 0, ///< Do not emit either .eh_frame or .debug_frame
  146. EH = 1, ///< Emit .eh_frame
  147. Debug = 2 ///< Emit .debug_frame
  148. };
  149. private:
  150. MCSymbol *CurrentFnEnd = nullptr;
  151. /// Map a basic block section ID to the exception symbol associated with that
  152. /// section. Map entries are assigned and looked up via
  153. /// AsmPrinter::getMBBExceptionSym.
  154. DenseMap<unsigned, MCSymbol *> MBBSectionExceptionSyms;
  155. // The symbol used to represent the start of the current BB section of the
  156. // function. This is used to calculate the size of the BB section.
  157. MCSymbol *CurrentSectionBeginSym = nullptr;
  158. /// This map keeps track of which symbol is being used for the specified basic
  159. /// block's address of label.
  160. std::unique_ptr<AddrLabelMap> AddrLabelSymbols;
  161. /// The garbage collection metadata printer table.
  162. DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>> GCMetadataPrinters;
  163. /// Emit comments in assembly output if this is true.
  164. bool VerboseAsm;
  165. /// Output stream for the stack usage file (i.e., .su file).
  166. std::unique_ptr<raw_fd_ostream> StackUsageStream;
  167. /// List of symbols to be inserted into PC sections.
  168. DenseMap<const MDNode *, SmallVector<const MCSymbol *>> PCSectionsSymbols;
  169. static char ID;
  170. protected:
  171. MCSymbol *CurrentFnBegin = nullptr;
  172. /// For dso_local functions, the current $local alias for the function.
  173. MCSymbol *CurrentFnBeginLocal = nullptr;
  174. /// A vector of all debug/EH info emitters we should use. This vector
  175. /// maintains ownership of the emitters.
  176. std::vector<HandlerInfo> Handlers;
  177. size_t NumUserHandlers = 0;
  178. StackMaps SM;
  179. private:
  180. /// If generated on the fly this own the instance.
  181. std::unique_ptr<MachineDominatorTree> OwnedMDT;
  182. /// If generated on the fly this own the instance.
  183. std::unique_ptr<MachineLoopInfo> OwnedMLI;
  184. /// If the target supports dwarf debug info, this pointer is non-null.
  185. DwarfDebug *DD = nullptr;
  186. /// A handler that supports pseudo probe emission with embedded inline
  187. /// context.
  188. PseudoProbeHandler *PP = nullptr;
  189. /// CFISection type the module needs i.e. either .eh_frame or .debug_frame.
  190. CFISection ModuleCFISection = CFISection::None;
  191. /// True if the module contains split-stack functions. This is used to
  192. /// emit .note.GNU-split-stack section as required by the linker for
  193. /// special handling split-stack function calling no-split-stack function.
  194. bool HasSplitStack = false;
  195. /// True if the module contains no-split-stack functions. This is used to emit
  196. /// .note.GNU-no-split-stack section when it also contains functions without a
  197. /// split stack prologue.
  198. bool HasNoSplitStack = false;
  199. protected:
  200. explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
  201. public:
  202. ~AsmPrinter() override;
  203. DwarfDebug *getDwarfDebug() { return DD; }
  204. DwarfDebug *getDwarfDebug() const { return DD; }
  205. uint16_t getDwarfVersion() const;
  206. void setDwarfVersion(uint16_t Version);
  207. bool isDwarf64() const;
  208. /// Returns 4 for DWARF32 and 8 for DWARF64.
  209. unsigned int getDwarfOffsetByteSize() const;
  210. /// Returns 4 for DWARF32 and 12 for DWARF64.
  211. unsigned int getUnitLengthFieldByteSize() const;
  212. /// Returns information about the byte size of DW_FORM values.
  213. dwarf::FormParams getDwarfFormParams() const;
  214. bool isPositionIndependent() const;
  215. /// Return true if assembly output should contain comments.
  216. bool isVerbose() const { return VerboseAsm; }
  217. /// Return a unique ID for the current function.
  218. unsigned getFunctionNumber() const;
  219. /// Return symbol for the function pseudo stack if the stack frame is not a
  220. /// register based.
  221. virtual const MCSymbol *getFunctionFrameSymbol() const { return nullptr; }
  222. MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
  223. MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
  224. // Return the exception symbol associated with the MBB section containing a
  225. // given basic block.
  226. MCSymbol *getMBBExceptionSym(const MachineBasicBlock &MBB);
  227. /// Return the symbol to be used for the specified basic block when its
  228. /// address is taken. This cannot be its normal LBB label because the block
  229. /// may be accessed outside its containing function.
  230. MCSymbol *getAddrLabelSymbol(const BasicBlock *BB) {
  231. return getAddrLabelSymbolToEmit(BB).front();
  232. }
  233. /// Return the symbol to be used for the specified basic block when its
  234. /// address is taken. If other blocks were RAUW'd to this one, we may have
  235. /// to emit them as well, return the whole set.
  236. ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(const BasicBlock *BB);
  237. /// If the specified function has had any references to address-taken blocks
  238. /// generated, but the block got deleted, return the symbol now so we can
  239. /// emit it. This prevents emitting a reference to a symbol that has no
  240. /// definition.
  241. void takeDeletedSymbolsForFunction(const Function *F,
  242. std::vector<MCSymbol *> &Result);
  243. /// Return information about object file lowering.
  244. const TargetLoweringObjectFile &getObjFileLowering() const;
  245. /// Return information about data layout.
  246. const DataLayout &getDataLayout() const;
  247. /// Return the pointer size from the TargetMachine
  248. unsigned getPointerSize() const;
  249. /// Return information about subtarget.
  250. const MCSubtargetInfo &getSubtargetInfo() const;
  251. void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
  252. /// Emits inital debug location directive.
  253. void emitInitialRawDwarfLocDirective(const MachineFunction &MF);
  254. /// Return the current section we are emitting to.
  255. const MCSection *getCurrentSection() const;
  256. void getNameWithPrefix(SmallVectorImpl<char> &Name,
  257. const GlobalValue *GV) const;
  258. MCSymbol *getSymbol(const GlobalValue *GV) const;
  259. /// Similar to getSymbol() but preferred for references. On ELF, this uses a
  260. /// local symbol if a reference to GV is guaranteed to be resolved to the
  261. /// definition in the same module.
  262. MCSymbol *getSymbolPreferLocal(const GlobalValue &GV) const;
  263. bool doesDwarfUseRelocationsAcrossSections() const {
  264. return DwarfUsesRelocationsAcrossSections;
  265. }
  266. void setDwarfUsesRelocationsAcrossSections(bool Enable) {
  267. DwarfUsesRelocationsAcrossSections = Enable;
  268. }
  269. //===------------------------------------------------------------------===//
  270. // XRay instrumentation implementation.
  271. //===------------------------------------------------------------------===//
  272. public:
  273. // This describes the kind of sled we're storing in the XRay table.
  274. enum class SledKind : uint8_t {
  275. FUNCTION_ENTER = 0,
  276. FUNCTION_EXIT = 1,
  277. TAIL_CALL = 2,
  278. LOG_ARGS_ENTER = 3,
  279. CUSTOM_EVENT = 4,
  280. TYPED_EVENT = 5,
  281. };
  282. // The table will contain these structs that point to the sled, the function
  283. // containing the sled, and what kind of sled (and whether they should always
  284. // be instrumented). We also use a version identifier that the runtime can use
  285. // to decide what to do with the sled, depending on the version of the sled.
  286. struct XRayFunctionEntry {
  287. const MCSymbol *Sled;
  288. const MCSymbol *Function;
  289. SledKind Kind;
  290. bool AlwaysInstrument;
  291. const class Function *Fn;
  292. uint8_t Version;
  293. void emit(int, MCStreamer *) const;
  294. };
  295. // All the sleds to be emitted.
  296. SmallVector<XRayFunctionEntry, 4> Sleds;
  297. // Helper function to record a given XRay sled.
  298. void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind,
  299. uint8_t Version = 0);
  300. /// Emit a table with all XRay instrumentation points.
  301. void emitXRayTable();
  302. void emitPatchableFunctionEntries();
  303. //===------------------------------------------------------------------===//
  304. // MachineFunctionPass Implementation.
  305. //===------------------------------------------------------------------===//
  306. /// Record analysis usage.
  307. void getAnalysisUsage(AnalysisUsage &AU) const override;
  308. /// Set up the AsmPrinter when we are working on a new module. If your pass
  309. /// overrides this, it must make sure to explicitly call this implementation.
  310. bool doInitialization(Module &M) override;
  311. /// Shut down the asmprinter. If you override this in your pass, you must make
  312. /// sure to call it explicitly.
  313. bool doFinalization(Module &M) override;
  314. /// Emit the specified function out to the OutStreamer.
  315. bool runOnMachineFunction(MachineFunction &MF) override {
  316. SetupMachineFunction(MF);
  317. emitFunctionBody();
  318. return false;
  319. }
  320. //===------------------------------------------------------------------===//
  321. // Coarse grained IR lowering routines.
  322. //===------------------------------------------------------------------===//
  323. /// This should be called when a new MachineFunction is being processed from
  324. /// runOnMachineFunction.
  325. virtual void SetupMachineFunction(MachineFunction &MF);
  326. /// This method emits the body and trailer for a function.
  327. void emitFunctionBody();
  328. void emitCFIInstruction(const MachineInstr &MI);
  329. void emitFrameAlloc(const MachineInstr &MI);
  330. void emitStackSizeSection(const MachineFunction &MF);
  331. void emitStackUsage(const MachineFunction &MF);
  332. void emitBBAddrMapSection(const MachineFunction &MF);
  333. void emitKCFITrapEntry(const MachineFunction &MF, const MCSymbol *Symbol);
  334. virtual void emitKCFITypeId(const MachineFunction &MF);
  335. void emitPseudoProbe(const MachineInstr &MI);
  336. void emitRemarksSection(remarks::RemarkStreamer &RS);
  337. /// Emits a label as reference for PC sections.
  338. void emitPCSectionsLabel(const MachineFunction &MF, const MDNode &MD);
  339. /// Emits the PC sections collected from instructions.
  340. void emitPCSections(const MachineFunction &MF);
  341. /// Get the CFISection type for a function.
  342. CFISection getFunctionCFISectionType(const Function &F) const;
  343. /// Get the CFISection type for a function.
  344. CFISection getFunctionCFISectionType(const MachineFunction &MF) const;
  345. /// Get the CFISection type for the module.
  346. CFISection getModuleCFISectionType() const { return ModuleCFISection; }
  347. bool needsSEHMoves();
  348. /// Since emitting CFI unwind information is entangled with supporting the
  349. /// exceptions, this returns true for platforms which use CFI unwind
  350. /// information for debugging purpose when
  351. /// `MCAsmInfo::ExceptionsType == ExceptionHandling::None`.
  352. bool needsCFIForDebug() const;
  353. /// Print to the current output stream assembly representations of the
  354. /// constants in the constant pool MCP. This is used to print out constants
  355. /// which have been "spilled to memory" by the code generator.
  356. virtual void emitConstantPool();
  357. /// Print assembly representations of the jump tables used by the current
  358. /// function to the current output stream.
  359. virtual void emitJumpTableInfo();
  360. /// Emit the specified global variable to the .s file.
  361. virtual void emitGlobalVariable(const GlobalVariable *GV);
  362. /// Check to see if the specified global is a special global used by LLVM. If
  363. /// so, emit it and return true, otherwise do nothing and return false.
  364. bool emitSpecialLLVMGlobal(const GlobalVariable *GV);
  365. /// `llvm.global_ctors` and `llvm.global_dtors` are arrays of Structor
  366. /// structs.
  367. ///
  368. /// Priority - init priority
  369. /// Func - global initialization or global clean-up function
  370. /// ComdatKey - associated data
  371. struct Structor {
  372. int Priority = 0;
  373. Constant *Func = nullptr;
  374. GlobalValue *ComdatKey = nullptr;
  375. Structor() = default;
  376. };
  377. /// This method gathers an array of Structors and then sorts them out by
  378. /// Priority.
  379. /// @param List The initializer of `llvm.global_ctors` or `llvm.global_dtors`
  380. /// array.
  381. /// @param[out] Structors Sorted Structor structs by Priority.
  382. void preprocessXXStructorList(const DataLayout &DL, const Constant *List,
  383. SmallVector<Structor, 8> &Structors);
  384. /// This method emits `llvm.global_ctors` or `llvm.global_dtors` list.
  385. virtual void emitXXStructorList(const DataLayout &DL, const Constant *List,
  386. bool IsCtor);
  387. /// Emit an alignment directive to the specified power of two boundary. If a
  388. /// global value is specified, and if that global has an explicit alignment
  389. /// requested, it will override the alignment request if required for
  390. /// correctness.
  391. void emitAlignment(Align Alignment, const GlobalObject *GV = nullptr,
  392. unsigned MaxBytesToEmit = 0) const;
  393. /// Lower the specified LLVM Constant to an MCExpr.
  394. virtual const MCExpr *lowerConstant(const Constant *CV);
  395. /// Print a general LLVM constant to the .s file.
  396. /// On AIX, when an alias refers to a sub-element of a global variable, the
  397. /// label of that alias needs to be emitted before the corresponding element.
  398. using AliasMapTy = DenseMap<uint64_t, SmallVector<const GlobalAlias *, 1>>;
  399. void emitGlobalConstant(const DataLayout &DL, const Constant *CV,
  400. AliasMapTy *AliasList = nullptr);
  401. /// Unnamed constant global variables solely contaning a pointer to
  402. /// another globals variable act like a global variable "proxy", or GOT
  403. /// equivalents, i.e., it's only used to hold the address of the latter. One
  404. /// optimization is to replace accesses to these proxies by using the GOT
  405. /// entry for the final global instead. Hence, we select GOT equivalent
  406. /// candidates among all the module global variables, avoid emitting them
  407. /// unnecessarily and finally replace references to them by pc relative
  408. /// accesses to GOT entries.
  409. void computeGlobalGOTEquivs(Module &M);
  410. /// Constant expressions using GOT equivalent globals may not be
  411. /// eligible for PC relative GOT entry conversion, in such cases we need to
  412. /// emit the proxies we previously omitted in EmitGlobalVariable.
  413. void emitGlobalGOTEquivs();
  414. /// Emit the stack maps.
  415. void emitStackMaps();
  416. //===------------------------------------------------------------------===//
  417. // Overridable Hooks
  418. //===------------------------------------------------------------------===//
  419. void addAsmPrinterHandler(HandlerInfo Handler) {
  420. Handlers.insert(Handlers.begin(), std::move(Handler));
  421. NumUserHandlers++;
  422. }
  423. // Targets can, or in the case of EmitInstruction, must implement these to
  424. // customize output.
  425. /// This virtual method can be overridden by targets that want to emit
  426. /// something at the start of their file.
  427. virtual void emitStartOfAsmFile(Module &) {}
  428. /// This virtual method can be overridden by targets that want to emit
  429. /// something at the end of their file.
  430. virtual void emitEndOfAsmFile(Module &) {}
  431. /// Targets can override this to emit stuff before the first basic block in
  432. /// the function.
  433. virtual void emitFunctionBodyStart() {}
  434. /// Targets can override this to emit stuff after the last basic block in the
  435. /// function.
  436. virtual void emitFunctionBodyEnd() {}
  437. /// Targets can override this to emit stuff at the start of a basic block.
  438. /// By default, this method prints the label for the specified
  439. /// MachineBasicBlock, an alignment (if present) and a comment describing it
  440. /// if appropriate.
  441. virtual void emitBasicBlockStart(const MachineBasicBlock &MBB);
  442. /// Targets can override this to emit stuff at the end of a basic block.
  443. virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB);
  444. /// Targets should implement this to emit instructions.
  445. virtual void emitInstruction(const MachineInstr *) {
  446. llvm_unreachable("EmitInstruction not implemented");
  447. }
  448. /// Return the symbol for the specified constant pool entry.
  449. virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
  450. virtual void emitFunctionEntryLabel();
  451. virtual void emitFunctionDescriptor() {
  452. llvm_unreachable("Function descriptor is target-specific.");
  453. }
  454. virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
  455. /// Targets can override this to change how global constants that are part of
  456. /// a C++ static/global constructor list are emitted.
  457. virtual void emitXXStructor(const DataLayout &DL, const Constant *CV) {
  458. emitGlobalConstant(DL, CV);
  459. }
  460. /// Return true if the basic block has exactly one predecessor and the control
  461. /// transfer mechanism between the predecessor and this block is a
  462. /// fall-through.
  463. virtual bool
  464. isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
  465. /// Targets can override this to customize the output of IMPLICIT_DEF
  466. /// instructions in verbose mode.
  467. virtual void emitImplicitDef(const MachineInstr *MI) const;
  468. /// Emit N NOP instructions.
  469. void emitNops(unsigned N);
  470. //===------------------------------------------------------------------===//
  471. // Symbol Lowering Routines.
  472. //===------------------------------------------------------------------===//
  473. MCSymbol *createTempSymbol(const Twine &Name) const;
  474. /// Return the MCSymbol for a private symbol with global value name as its
  475. /// base, with the specified suffix.
  476. MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
  477. StringRef Suffix) const;
  478. /// Return the MCSymbol for the specified ExternalSymbol.
  479. MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
  480. /// Return the symbol for the specified jump table entry.
  481. MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
  482. /// Return the symbol for the specified jump table .set
  483. /// FIXME: privatize to AsmPrinter.
  484. MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
  485. /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
  486. /// basic block.
  487. MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
  488. MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
  489. //===------------------------------------------------------------------===//
  490. // Emission Helper Routines.
  491. //===------------------------------------------------------------------===//
  492. /// This is just convenient handler for printing offsets.
  493. void printOffset(int64_t Offset, raw_ostream &OS) const;
  494. /// Emit a byte directive and value.
  495. void emitInt8(int Value) const;
  496. /// Emit a short directive and value.
  497. void emitInt16(int Value) const;
  498. /// Emit a long directive and value.
  499. void emitInt32(int Value) const;
  500. /// Emit a long long directive and value.
  501. void emitInt64(uint64_t Value) const;
  502. /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
  503. /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
  504. /// .set if it is available.
  505. void emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
  506. unsigned Size) const;
  507. /// Emit something like ".uleb128 Hi-Lo".
  508. void emitLabelDifferenceAsULEB128(const MCSymbol *Hi,
  509. const MCSymbol *Lo) const;
  510. /// Emit something like ".long Label+Offset" where the size in bytes of the
  511. /// directive is specified by Size and Label specifies the label. This
  512. /// implicitly uses .set if it is available.
  513. void emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
  514. unsigned Size, bool IsSectionRelative = false) const;
  515. /// Emit something like ".long Label" where the size in bytes of the directive
  516. /// is specified by Size and Label specifies the label.
  517. void emitLabelReference(const MCSymbol *Label, unsigned Size,
  518. bool IsSectionRelative = false) const {
  519. emitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
  520. }
  521. //===------------------------------------------------------------------===//
  522. // Dwarf Emission Helper Routines
  523. //===------------------------------------------------------------------===//
  524. /// Emit the specified signed leb128 value.
  525. void emitSLEB128(int64_t Value, const char *Desc = nullptr) const;
  526. /// Emit the specified unsigned leb128 value.
  527. void emitULEB128(uint64_t Value, const char *Desc = nullptr,
  528. unsigned PadTo = 0) const;
  529. /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
  530. /// assembly output is enabled, we output comments describing the encoding.
  531. /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
  532. void emitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
  533. /// Return the size of the encoding in bytes.
  534. unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
  535. /// Emit reference to a ttype global with a specified encoding.
  536. virtual void emitTTypeReference(const GlobalValue *GV, unsigned Encoding);
  537. /// Emit a reference to a symbol for use in dwarf. Different object formats
  538. /// represent this in different ways. Some use a relocation others encode
  539. /// the label offset in its section.
  540. void emitDwarfSymbolReference(const MCSymbol *Label,
  541. bool ForceOffset = false) const;
  542. /// Emit the 4- or 8-byte offset of a string from the start of its section.
  543. ///
  544. /// When possible, emit a DwarfStringPool section offset without any
  545. /// relocations, and without using the symbol. Otherwise, defers to \a
  546. /// emitDwarfSymbolReference().
  547. ///
  548. /// The length of the emitted value depends on the DWARF format.
  549. void emitDwarfStringOffset(DwarfStringPoolEntry S) const;
  550. /// Emit the 4-or 8-byte offset of a string from the start of its section.
  551. void emitDwarfStringOffset(DwarfStringPoolEntryRef S) const {
  552. emitDwarfStringOffset(S.getEntry());
  553. }
  554. /// Emit something like ".long Label + Offset" or ".quad Label + Offset"
  555. /// depending on the DWARF format.
  556. void emitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const;
  557. /// Emit 32- or 64-bit value depending on the DWARF format.
  558. void emitDwarfLengthOrOffset(uint64_t Value) const;
  559. /// Emit a unit length field. The actual format, DWARF32 or DWARF64, is chosen
  560. /// according to the settings.
  561. void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) const;
  562. /// Emit a unit length field. The actual format, DWARF32 or DWARF64, is chosen
  563. /// according to the settings.
  564. /// Return the end symbol generated inside, the caller needs to emit it.
  565. MCSymbol *emitDwarfUnitLength(const Twine &Prefix,
  566. const Twine &Comment) const;
  567. /// Emit reference to a call site with a specified encoding
  568. void emitCallSiteOffset(const MCSymbol *Hi, const MCSymbol *Lo,
  569. unsigned Encoding) const;
  570. /// Emit an integer value corresponding to the call site encoding
  571. void emitCallSiteValue(uint64_t Value, unsigned Encoding) const;
  572. /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
  573. virtual unsigned getISAEncoding() { return 0; }
  574. /// Emit the directive and value for debug thread local expression
  575. ///
  576. /// \p Value - The value to emit.
  577. /// \p Size - The size of the integer (in bytes) to emit.
  578. virtual void emitDebugValue(const MCExpr *Value, unsigned Size) const;
  579. //===------------------------------------------------------------------===//
  580. // Dwarf Lowering Routines
  581. //===------------------------------------------------------------------===//
  582. /// Emit frame instruction to describe the layout of the frame.
  583. void emitCFIInstruction(const MCCFIInstruction &Inst) const;
  584. /// Emit Dwarf abbreviation table.
  585. template <typename T> void emitDwarfAbbrevs(const T &Abbrevs) const {
  586. // For each abbreviation.
  587. for (const auto &Abbrev : Abbrevs)
  588. emitDwarfAbbrev(*Abbrev);
  589. // Mark end of abbreviations.
  590. emitULEB128(0, "EOM(3)");
  591. }
  592. void emitDwarfAbbrev(const DIEAbbrev &Abbrev) const;
  593. /// Recursively emit Dwarf DIE tree.
  594. void emitDwarfDIE(const DIE &Die) const;
  595. //===------------------------------------------------------------------===//
  596. // Inline Asm Support
  597. //===------------------------------------------------------------------===//
  598. // These are hooks that targets can override to implement inline asm
  599. // support. These should probably be moved out of AsmPrinter someday.
  600. /// Print information related to the specified machine instr that is
  601. /// independent of the operand, and may be independent of the instr itself.
  602. /// This can be useful for portably encoding the comment character or other
  603. /// bits of target-specific knowledge into the asmstrings. The syntax used is
  604. /// ${:comment}. Targets can override this to add support for their own
  605. /// strange codes.
  606. virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
  607. StringRef Code) const;
  608. /// Print the MachineOperand as a symbol. Targets with complex handling of
  609. /// symbol references should override the base implementation.
  610. virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS);
  611. /// Print the specified operand of MI, an INLINEASM instruction, using the
  612. /// specified assembler variant. Targets should override this to format as
  613. /// appropriate. This method can return true if the operand is erroneous.
  614. virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
  615. const char *ExtraCode, raw_ostream &OS);
  616. /// Print the specified operand of MI, an INLINEASM instruction, using the
  617. /// specified assembler variant as an address. Targets should override this to
  618. /// format as appropriate. This method can return true if the operand is
  619. /// erroneous.
  620. virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
  621. const char *ExtraCode, raw_ostream &OS);
  622. /// Let the target do anything it needs to do before emitting inlineasm.
  623. /// \p StartInfo - the subtarget info before parsing inline asm
  624. virtual void emitInlineAsmStart() const;
  625. /// Let the target do anything it needs to do after emitting inlineasm.
  626. /// This callback can be used restore the original mode in case the
  627. /// inlineasm contains directives to switch modes.
  628. /// \p StartInfo - the original subtarget info before inline asm
  629. /// \p EndInfo - the final subtarget info after parsing the inline asm,
  630. /// or NULL if the value is unknown.
  631. virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
  632. const MCSubtargetInfo *EndInfo) const;
  633. /// This emits visibility information about symbol, if this is supported by
  634. /// the target.
  635. void emitVisibility(MCSymbol *Sym, unsigned Visibility,
  636. bool IsDefinition = true) const;
  637. /// This emits linkage information about \p GVSym based on \p GV, if this is
  638. /// supported by the target.
  639. virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
  640. /// Return the alignment for the specified \p GV.
  641. static Align getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
  642. Align InAlign = Align(1));
  643. private:
  644. /// Private state for PrintSpecial()
  645. // Assign a unique ID to this machine instruction.
  646. mutable const MachineInstr *LastMI = nullptr;
  647. mutable unsigned LastFn = 0;
  648. mutable unsigned Counter = ~0U;
  649. bool DwarfUsesRelocationsAcrossSections = false;
  650. /// This method emits the header for the current function.
  651. virtual void emitFunctionHeader();
  652. /// This method emits a comment next to header for the current function.
  653. virtual void emitFunctionHeaderComment();
  654. /// Emit a blob of inline asm to the output streamer.
  655. void
  656. emitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
  657. const MCTargetOptions &MCOptions,
  658. const MDNode *LocMDNode = nullptr,
  659. InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
  660. /// This method formats and emits the specified machine instruction that is an
  661. /// inline asm.
  662. void emitInlineAsm(const MachineInstr *MI) const;
  663. /// Add inline assembly info to the diagnostics machinery, so we can
  664. /// emit file and position info. Returns SrcMgr memory buffer position.
  665. unsigned addInlineAsmDiagBuffer(StringRef AsmStr,
  666. const MDNode *LocMDNode) const;
  667. //===------------------------------------------------------------------===//
  668. // Internal Implementation Details
  669. //===------------------------------------------------------------------===//
  670. void emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
  671. const MachineBasicBlock *MBB, unsigned uid) const;
  672. void emitLLVMUsedList(const ConstantArray *InitList);
  673. /// Emit llvm.ident metadata in an '.ident' directive.
  674. void emitModuleIdents(Module &M);
  675. /// Emit bytes for llvm.commandline metadata.
  676. void emitModuleCommandLines(Module &M);
  677. GCMetadataPrinter *getOrCreateGCPrinter(GCStrategy &S);
  678. void emitGlobalAlias(Module &M, const GlobalAlias &GA);
  679. void emitGlobalIFunc(Module &M, const GlobalIFunc &GI);
  680. /// This method decides whether the specified basic block requires a label.
  681. bool shouldEmitLabelForBasicBlock(const MachineBasicBlock &MBB) const;
  682. protected:
  683. virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const {
  684. return false;
  685. }
  686. };
  687. } // end namespace llvm
  688. #endif // LLVM_CODEGEN_ASMPRINTER_H
  689. #ifdef __GNUC__
  690. #pragma GCC diagnostic pop
  691. #endif