1 //===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a class to be used as the base class for target specific
11 // asm writers. This class primarily handles common functionality used by
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_ASMPRINTER_H
17 #define LLVM_CODEGEN_ASMPRINTER_H
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/Support/DataTypes.h"
24 #include "llvm/Support/ErrorHandling.h"
27 class AsmPrinterHandler;
35 class GCMetadataPrinter;
38 class MachineBasicBlock;
39 class MachineFunction;
41 class MachineLocation;
42 class MachineLoopInfo;
44 class MachineConstantPoolValue;
45 class MachineJumpTableInfo;
46 class MachineModuleInfo;
48 class MCCFIInstruction;
54 class MCSubtargetInfo;
56 class MCTargetOptions;
60 class TargetLoweringObjectFile;
64 /// This class is intended to be used as a driving class for all asm writers.
65 class AsmPrinter : public MachineFunctionPass {
67 /// Target machine description.
71 /// Target Asm Printer information.
75 /// This is the context for the output file that we are streaming. This owns
76 /// all of the global MC-related objects for the generated translation unit.
77 MCContext &OutContext;
79 /// This is the MCStreamer object for the file we are generating. This
80 /// contains the transient state for the current translation unit that we are
81 /// generating (such as the current section etc).
82 std::unique_ptr<MCStreamer> OutStreamer;
84 /// The current machine function.
85 const MachineFunction *MF;
87 /// This is a pointer to the current MachineModuleInfo.
88 MachineModuleInfo *MMI;
90 /// Name-mangler for global names.
94 /// The symbol for the current function. This is recalculated at the beginning
95 /// of each call to runOnMachineFunction().
97 MCSymbol *CurrentFnSym;
99 /// The symbol used to represent the start of the current function for the
100 /// purpose of calculating its size (e.g. using the .size directive). By
101 /// default, this is equal to CurrentFnSym.
102 MCSymbol *CurrentFnSymForSize;
104 /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of
105 /// its number of uses by other globals.
106 typedef std::pair<const GlobalVariable *, unsigned> GOTEquivUsePair;
107 MapVector<const MCSymbol *, GOTEquivUsePair> GlobalGOTEquivs;
110 MCSymbol *CurrentFnBegin;
111 MCSymbol *CurrentFnEnd;
112 MCSymbol *CurExceptionSym;
114 // The garbage collection metadata printer table.
115 void *GCMetadataPrinters; // Really a DenseMap.
117 /// Emit comments in assembly output if this is true.
122 /// If VerboseAsm is set, a pointer to the loop info for this function.
126 AsmPrinterHandler *Handler;
127 const char *TimerName, *TimerGroupName;
128 HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName,
129 const char *TimerGroupName)
130 : Handler(Handler), TimerName(TimerName),
131 TimerGroupName(TimerGroupName) {}
133 /// A vector of all debug/EH info emitters we should use. This vector
134 /// maintains ownership of the emitters.
135 SmallVector<HandlerInfo, 1> Handlers;
137 /// If the target supports dwarf debug info, this pointer is non-null.
141 explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
144 ~AsmPrinter() override;
146 DwarfDebug *getDwarfDebug() { return DD; }
147 DwarfDebug *getDwarfDebug() const { return DD; }
149 /// Return true if assembly output should contain comments.
151 bool isVerbose() const { return VerboseAsm; }
153 /// Return a unique ID for the current function.
155 unsigned getFunctionNumber() const;
157 MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
158 MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
159 MCSymbol *getCurExceptionSym();
161 /// Return information about object file lowering.
162 const TargetLoweringObjectFile &getObjFileLowering() const;
164 /// Return information about data layout.
165 const DataLayout &getDataLayout() const;
167 /// Return information about subtarget.
168 const MCSubtargetInfo &getSubtargetInfo() const;
170 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
172 /// Return the target triple string.
173 StringRef getTargetTriple() const;
175 /// Return the current section we are emitting to.
176 const MCSection *getCurrentSection() const;
178 void getNameWithPrefix(SmallVectorImpl<char> &Name,
179 const GlobalValue *GV) const;
181 MCSymbol *getSymbol(const GlobalValue *GV) const;
183 //===------------------------------------------------------------------===//
184 // MachineFunctionPass Implementation.
185 //===------------------------------------------------------------------===//
187 /// Record analysis usage.
189 void getAnalysisUsage(AnalysisUsage &AU) const override;
191 /// Set up the AsmPrinter when we are working on a new module. If your pass
192 /// overrides this, it must make sure to explicitly call this implementation.
193 bool doInitialization(Module &M) override;
195 /// Shut down the asmprinter. If you override this in your pass, you must make
196 /// sure to call it explicitly.
197 bool doFinalization(Module &M) override;
199 /// Emit the specified function out to the OutStreamer.
200 bool runOnMachineFunction(MachineFunction &MF) override {
201 SetupMachineFunction(MF);
206 //===------------------------------------------------------------------===//
207 // Coarse grained IR lowering routines.
208 //===------------------------------------------------------------------===//
210 /// This should be called when a new MachineFunction is being processed from
211 /// runOnMachineFunction.
212 void SetupMachineFunction(MachineFunction &MF);
214 /// This method emits the body and trailer for a function.
215 void EmitFunctionBody();
217 void emitCFIInstruction(const MachineInstr &MI);
219 void emitFrameAlloc(const MachineInstr &MI);
221 enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug };
222 CFIMoveType needsCFIMoves();
224 bool needsSEHMoves();
226 /// Print to the current output stream assembly representations of the
227 /// constants in the constant pool MCP. This is used to print out constants
228 /// which have been "spilled to memory" by the code generator.
230 virtual void EmitConstantPool();
232 /// Print assembly representations of the jump tables used by the current
233 /// function to the current output stream.
235 void EmitJumpTableInfo();
237 /// Emit the specified global variable to the .s file.
238 virtual void EmitGlobalVariable(const GlobalVariable *GV);
240 /// Check to see if the specified global is a special global used by LLVM. If
241 /// so, emit it and return true, otherwise do nothing and return false.
242 bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
244 /// Emit an alignment directive to the specified power of two boundary. For
245 /// example, if you pass in 3 here, you will get an 8 byte alignment. If a
246 /// global value is specified, and if that global has an explicit alignment
247 /// requested, it will override the alignment request if required for
250 void EmitAlignment(unsigned NumBits, const GlobalObject *GO = nullptr) const;
252 /// Lower the specified LLVM Constant to an MCExpr.
253 const MCExpr *lowerConstant(const Constant *CV);
255 /// \brief Print a general LLVM constant to the .s file.
256 void EmitGlobalConstant(const Constant *CV);
258 /// \brief Unnamed constant global variables solely contaning a pointer to
259 /// another globals variable act like a global variable "proxy", or GOT
260 /// equivalents, i.e., it's only used to hold the address of the latter. One
261 /// optimization is to replace accesses to these proxies by using the GOT
262 /// entry for the final global instead. Hence, we select GOT equivalent
263 /// candidates among all the module global variables, avoid emitting them
264 /// unnecessarily and finally replace references to them by pc relative
265 /// accesses to GOT entries.
266 void computeGlobalGOTEquivs(Module &M);
268 /// \brief Constant expressions using GOT equivalent globals may not be
269 /// eligible for PC relative GOT entry conversion, in such cases we need to
270 /// emit the proxies we previously omitted in EmitGlobalVariable.
271 void emitGlobalGOTEquivs();
273 //===------------------------------------------------------------------===//
275 //===------------------------------------------------------------------===//
277 // Targets can, or in the case of EmitInstruction, must implement these to
280 /// This virtual method can be overridden by targets that want to emit
281 /// something at the start of their file.
282 virtual void EmitStartOfAsmFile(Module &) {}
284 /// This virtual method can be overridden by targets that want to emit
285 /// something at the end of their file.
286 virtual void EmitEndOfAsmFile(Module &) {}
288 /// Targets can override this to emit stuff before the first basic block in
290 virtual void EmitFunctionBodyStart() {}
292 /// Targets can override this to emit stuff after the last basic block in the
294 virtual void EmitFunctionBodyEnd() {}
296 /// Targets can override this to emit stuff at the start of a basic block.
297 /// By default, this method prints the label for the specified
298 /// MachineBasicBlock, an alignment (if present) and a comment describing it
300 virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const;
302 /// Targets can override this to emit stuff at the end of a basic block.
303 virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB) {}
305 /// Targets should implement this to emit instructions.
306 virtual void EmitInstruction(const MachineInstr *) {
307 llvm_unreachable("EmitInstruction not implemented");
310 /// Return the symbol for the specified constant pool entry.
311 virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
313 virtual void EmitFunctionEntryLabel();
315 virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
317 /// Targets can override this to change how global constants that are part of
318 /// a C++ static/global constructor list are emitted.
319 virtual void EmitXXStructor(const Constant *CV) { EmitGlobalConstant(CV); }
321 /// Return true if the basic block has exactly one predecessor and the control
322 /// transfer mechanism between the predecessor and this block is a
325 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
327 /// Targets can override this to customize the output of IMPLICIT_DEF
328 /// instructions in verbose mode.
329 virtual void emitImplicitDef(const MachineInstr *MI) const;
331 //===------------------------------------------------------------------===//
332 // Symbol Lowering Routines.
333 //===------------------------------------------------------------------===//
335 MCSymbol *createTempSymbol(const Twine &Name) const;
337 /// Return the MCSymbol for a private symbol with global value name as its
338 /// base, with the specified suffix.
339 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
340 StringRef Suffix) const;
342 /// Return the MCSymbol for the specified ExternalSymbol.
343 MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
345 /// Return the symbol for the specified jump table entry.
346 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
348 /// Return the symbol for the specified jump table .set
349 /// FIXME: privatize to AsmPrinter.
350 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
352 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
354 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
355 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
357 //===------------------------------------------------------------------===//
358 // Emission Helper Routines.
359 //===------------------------------------------------------------------===//
361 /// This is just convenient handler for printing offsets.
362 void printOffset(int64_t Offset, raw_ostream &OS) const;
364 /// Emit a byte directive and value.
366 void EmitInt8(int Value) const;
368 /// Emit a short directive and value.
370 void EmitInt16(int Value) const;
372 /// Emit a long directive and value.
374 void EmitInt32(int Value) const;
376 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
377 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
378 /// .set if it is available.
379 void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
380 unsigned Size) const;
382 /// Emit something like ".long Label+Offset" where the size in bytes of the
383 /// directive is specified by Size and Label specifies the label. This
384 /// implicitly uses .set if it is available.
385 void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
386 unsigned Size, bool IsSectionRelative = false) const;
388 /// Emit something like ".long Label" where the size in bytes of the directive
389 /// is specified by Size and Label specifies the label.
390 void EmitLabelReference(const MCSymbol *Label, unsigned Size,
391 bool IsSectionRelative = false) const {
392 EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
395 //===------------------------------------------------------------------===//
396 // Dwarf Emission Helper Routines
397 //===------------------------------------------------------------------===//
399 /// Emit the specified signed leb128 value.
400 void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
402 /// Emit the specified unsigned leb128 value.
403 void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
404 unsigned PadTo = 0) const;
406 /// Emit a .byte 42 directive for a DW_CFA_xxx value.
407 void EmitCFAByte(unsigned Val) const;
409 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
410 /// assembly output is enabled, we output comments describing the encoding.
411 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
412 void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
414 /// Return the size of the encoding in bytes.
415 unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
417 /// Emit reference to a ttype global with a specified encoding.
418 void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
420 /// Emit the 4-byte offset of Label from the start of its section. This can
421 /// be done with a special directive if the target supports it (e.g. cygwin)
422 /// or by emitting it as an offset from a label at the start of the section.
423 void emitSectionOffset(const MCSymbol *Label) const;
425 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
426 virtual unsigned getISAEncoding() { return 0; }
428 /// EmitDwarfRegOp - Emit a dwarf register operation.
429 virtual void EmitDwarfRegOp(ByteStreamer &BS,
430 const MachineLocation &MLoc) const;
432 //===------------------------------------------------------------------===//
433 // Dwarf Lowering Routines
434 //===------------------------------------------------------------------===//
436 /// \brief Emit frame instruction to describe the layout of the frame.
437 void emitCFIInstruction(const MCCFIInstruction &Inst) const;
439 /// \brief Emit Dwarf abbreviation table.
440 void emitDwarfAbbrevs(const std::vector<DIEAbbrev *>& Abbrevs) const;
442 /// \brief Recursively emit Dwarf DIE tree.
443 void emitDwarfDIE(const DIE &Die) const;
445 //===------------------------------------------------------------------===//
446 // Inline Asm Support
447 //===------------------------------------------------------------------===//
449 // These are hooks that targets can override to implement inline asm
450 // support. These should probably be moved out of AsmPrinter someday.
452 /// Print information related to the specified machine instr that is
453 /// independent of the operand, and may be independent of the instr itself.
454 /// This can be useful for portably encoding the comment character or other
455 /// bits of target-specific knowledge into the asmstrings. The syntax used is
456 /// ${:comment}. Targets can override this to add support for their own
458 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
459 const char *Code) const;
461 /// Print the specified operand of MI, an INLINEASM instruction, using the
462 /// specified assembler variant. Targets should override this to format as
463 /// appropriate. This method can return true if the operand is erroneous.
464 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
465 unsigned AsmVariant, const char *ExtraCode,
468 /// Print the specified operand of MI, an INLINEASM instruction, using the
469 /// specified assembler variant as an address. Targets should override this to
470 /// format as appropriate. This method can return true if the operand is
472 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
473 unsigned AsmVariant, const char *ExtraCode,
476 /// Let the target do anything it needs to do before emitting inlineasm.
477 /// \p StartInfo - the subtarget info before parsing inline asm
478 virtual void emitInlineAsmStart() const;
480 /// Let the target do anything it needs to do after emitting inlineasm.
481 /// This callback can be used restore the original mode in case the
482 /// inlineasm contains directives to switch modes.
483 /// \p StartInfo - the original subtarget info before inline asm
484 /// \p EndInfo - the final subtarget info after parsing the inline asm,
485 /// or NULL if the value is unknown.
486 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
487 const MCSubtargetInfo *EndInfo) const;
490 /// Private state for PrintSpecial()
491 // Assign a unique ID to this machine instruction.
492 mutable const MachineInstr *LastMI;
493 mutable unsigned LastFn;
494 mutable unsigned Counter;
496 /// This method emits the header for the current function.
497 void EmitFunctionHeader();
499 /// Emit a blob of inline asm to the output streamer.
501 EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
502 const MCTargetOptions &MCOptions,
503 const MDNode *LocMDNode = nullptr,
504 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
506 /// This method formats and emits the specified machine instruction that is an
508 void EmitInlineAsm(const MachineInstr *MI) const;
510 //===------------------------------------------------------------------===//
511 // Internal Implementation Details
512 //===------------------------------------------------------------------===//
514 /// This emits visibility information about symbol, if this is suported by the
516 void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
517 bool IsDefinition = true) const;
519 void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
521 void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
522 const MachineBasicBlock *MBB, unsigned uid) const;
523 void EmitLLVMUsedList(const ConstantArray *InitList);
524 /// Emit llvm.ident metadata in an '.ident' directive.
525 void EmitModuleIdents(Module &M);
526 void EmitXXStructorList(const Constant *List, bool isCtor);
527 GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C);