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/Twine.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
26 class AsmPrinterHandler;
32 class GCMetadataPrinter;
35 class MachineBasicBlock;
36 class MachineFunction;
38 class MachineLocation;
39 class MachineLoopInfo;
41 class MachineConstantPoolValue;
42 class MachineJumpTableInfo;
43 class MachineModuleInfo;
45 class MCCFIInstruction;
51 class MCSubtargetInfo;
56 class TargetLoweringObjectFile;
60 /// This class is intended to be used as a driving class for all asm writers.
61 class AsmPrinter : public MachineFunctionPass {
63 /// Target machine description.
67 /// Target Asm Printer information.
71 /// This is the context for the output file that we are streaming. This owns
72 /// all of the global MC-related objects for the generated translation unit.
73 MCContext &OutContext;
75 /// This is the MCStreamer object for the file we are generating. This
76 /// contains the transient state for the current translation unit that we are
77 /// generating (such as the current section etc).
78 MCStreamer &OutStreamer;
80 /// The current machine function.
81 const MachineFunction *MF;
83 /// This is a pointer to the current MachineModuleInfo.
84 MachineModuleInfo *MMI;
86 /// Name-mangler for global names.
90 /// The symbol for the current function. This is recalculated at the beginning
91 /// of each call to runOnMachineFunction().
93 MCSymbol *CurrentFnSym;
95 /// The symbol used to represent the start of the current function for the
96 /// purpose of calculating its size (e.g. using the .size directive). By
97 /// default, this is equal to CurrentFnSym.
98 MCSymbol *CurrentFnSymForSize;
100 /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of
101 /// its number of uses by other globals.
102 typedef std::pair<const GlobalVariable *, unsigned> GOTEquivUsePair;
103 DenseMap<const MCSymbol *, GOTEquivUsePair> GlobalGOTEquivs;
106 MCSymbol *CurrentFnBegin;
107 MCSymbol *CurrentFnEnd;
109 // The garbage collection metadata printer table.
110 void *GCMetadataPrinters; // Really a DenseMap.
112 /// Emit comments in assembly output if this is true.
117 /// If VerboseAsm is set, a pointer to the loop info for this function.
121 AsmPrinterHandler *Handler;
122 const char *TimerName, *TimerGroupName;
123 HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName,
124 const char *TimerGroupName)
125 : Handler(Handler), TimerName(TimerName),
126 TimerGroupName(TimerGroupName) {}
128 /// A vector of all debug/EH info emitters we should use. This vector
129 /// maintains ownership of the emitters.
130 SmallVector<HandlerInfo, 1> Handlers;
132 /// If the target supports dwarf debug info, this pointer is non-null.
136 explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
139 virtual ~AsmPrinter();
141 DwarfDebug *getDwarfDebug() { return DD; }
142 DwarfDebug *getDwarfDebug() const { return DD; }
144 /// Return true if assembly output should contain comments.
146 bool isVerbose() const { return VerboseAsm; }
148 /// Return a unique ID for the current function.
150 unsigned getFunctionNumber() const;
152 MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
153 MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
155 /// Return information about object file lowering.
156 const TargetLoweringObjectFile &getObjFileLowering() const;
158 /// Return information about data layout.
159 const DataLayout &getDataLayout() const;
161 /// Return information about subtarget.
162 const MCSubtargetInfo &getSubtargetInfo() const;
164 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
166 /// Return the target triple string.
167 StringRef getTargetTriple() const;
169 /// Return the current section we are emitting to.
170 const MCSection *getCurrentSection() const;
172 void getNameWithPrefix(SmallVectorImpl<char> &Name,
173 const GlobalValue *GV) const;
175 MCSymbol *getSymbol(const GlobalValue *GV) const;
177 //===------------------------------------------------------------------===//
178 // MachineFunctionPass Implementation.
179 //===------------------------------------------------------------------===//
181 /// Record analysis usage.
183 void getAnalysisUsage(AnalysisUsage &AU) const override;
185 /// Set up the AsmPrinter when we are working on a new module. If your pass
186 /// overrides this, it must make sure to explicitly call this implementation.
187 bool doInitialization(Module &M) override;
189 /// Shut down the asmprinter. If you override this in your pass, you must make
190 /// sure to call it explicitly.
191 bool doFinalization(Module &M) override;
193 /// Emit the specified function out to the OutStreamer.
194 bool runOnMachineFunction(MachineFunction &MF) override {
195 SetupMachineFunction(MF);
196 EmitFunctionHeader();
201 //===------------------------------------------------------------------===//
202 // Coarse grained IR lowering routines.
203 //===------------------------------------------------------------------===//
205 /// This should be called when a new MachineFunction is being processed from
206 /// runOnMachineFunction.
207 void SetupMachineFunction(MachineFunction &MF);
209 /// This method emits the header for the current function.
210 void EmitFunctionHeader();
212 /// This method emits the body and trailer for a function.
213 void EmitFunctionBody();
215 void emitCFIInstruction(const MachineInstr &MI);
217 void emitFrameAlloc(const MachineInstr &MI);
219 enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug };
220 CFIMoveType needsCFIMoves();
222 bool needsSEHMoves();
224 /// Print to the current output stream assembly representations of the
225 /// constants in the constant pool MCP. This is used to print out constants
226 /// which have been "spilled to memory" by the code generator.
228 virtual void EmitConstantPool();
230 /// Print assembly representations of the jump tables used by the current
231 /// function to the current output stream.
233 void EmitJumpTableInfo();
235 /// Emit the specified global variable to the .s file.
236 virtual void EmitGlobalVariable(const GlobalVariable *GV);
238 /// Check to see if the specified global is a special global used by LLVM. If
239 /// so, emit it and return true, otherwise do nothing and return false.
240 bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
242 /// Emit an alignment directive to the specified power of two boundary. For
243 /// example, if you pass in 3 here, you will get an 8 byte alignment. If a
244 /// global value is specified, and if that global has an explicit alignment
245 /// requested, it will override the alignment request if required for
248 void EmitAlignment(unsigned NumBits, const GlobalObject *GO = nullptr) const;
250 /// Lower the specified LLVM Constant to an MCExpr.
251 const MCExpr *lowerConstant(const Constant *CV);
253 /// \brief Print a general LLVM constant to the .s file.
254 void EmitGlobalConstant(const Constant *CV);
256 /// \brief Unnamed constant global variables solely contaning a pointer to
257 /// another globals variable act like a global variable "proxy", or GOT
258 /// equivalents, i.e., it's only used to hold the address of the latter. One
259 /// optimization is to replace accesses to these proxies by using the GOT
260 /// entry for the final global instead. Hence, we select GOT equivalent
261 /// candidates among all the module global variables, avoid emitting them
262 /// unnecessarily and finally replace references to them by pc relative
263 /// accesses to GOT entries.
264 void computeGlobalGOTEquivs(Module &M);
266 /// \brief Constant expressions using GOT equivalent globals may not be
267 /// eligible for PC relative GOT entry conversion, in such cases we need to
268 /// emit the proxies we previously omitted in EmitGlobalVariable.
269 void emitGlobalGOTEquivs();
271 //===------------------------------------------------------------------===//
273 //===------------------------------------------------------------------===//
275 // Targets can, or in the case of EmitInstruction, must implement these to
278 /// This virtual method can be overridden by targets that want to emit
279 /// something at the start of their file.
280 virtual void EmitStartOfAsmFile(Module &) {}
282 /// This virtual method can be overridden by targets that want to emit
283 /// something at the end of their file.
284 virtual void EmitEndOfAsmFile(Module &) {}
286 /// Targets can override this to emit stuff before the first basic block in
288 virtual void EmitFunctionBodyStart() {}
290 /// Targets can override this to emit stuff after the last basic block in the
292 virtual void EmitFunctionBodyEnd() {}
294 /// Targets can override this to emit stuff at the start of a basic block.
295 /// By default, this method prints the label for the specified
296 /// MachineBasicBlock, an alignment (if present) and a comment describing it
298 virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const;
300 /// Targets can override this to emit stuff at the end of a basic block.
301 virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB) {}
303 /// Targets should implement this to emit instructions.
304 virtual void EmitInstruction(const MachineInstr *) {
305 llvm_unreachable("EmitInstruction not implemented");
308 /// Return the symbol for the specified constant pool entry.
309 virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
311 virtual void EmitFunctionEntryLabel();
313 virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
315 /// Targets can override this to change how global constants that are part of
316 /// a C++ static/global constructor list are emitted.
317 virtual void EmitXXStructor(const Constant *CV) { EmitGlobalConstant(CV); }
319 /// Return true if the basic block has exactly one predecessor and the control
320 /// transfer mechanism between the predecessor and this block is a
323 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
325 /// Targets can override this to customize the output of IMPLICIT_DEF
326 /// instructions in verbose mode.
327 virtual void emitImplicitDef(const MachineInstr *MI) const;
329 //===------------------------------------------------------------------===//
330 // Symbol Lowering Routines.
331 //===------------------------------------------------------------------===//
333 /// Return the MCSymbol corresponding to the assembler temporary label with
334 /// the specified stem and unique ID.
335 MCSymbol *GetTempSymbol(const Twine &Name, unsigned ID) const;
337 /// Return an assembler temporary label with the specified stem.
338 MCSymbol *GetTempSymbol(const Twine &Name) const;
340 MCSymbol *createTempSymbol(const Twine &Name, unsigned ID) const;
342 /// Return the MCSymbol for a private symbol with global value name as its
343 /// base, with the specified suffix.
344 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
345 StringRef Suffix) const;
347 /// Return the MCSymbol for the specified ExternalSymbol.
348 MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
350 /// Return the symbol for the specified jump table entry.
351 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
353 /// Return the symbol for the specified jump table .set
354 /// FIXME: privatize to AsmPrinter.
355 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
357 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
359 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
360 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
362 //===------------------------------------------------------------------===//
363 // Emission Helper Routines.
364 //===------------------------------------------------------------------===//
366 /// This is just convenient handler for printing offsets.
367 void printOffset(int64_t Offset, raw_ostream &OS) const;
369 /// Emit a byte directive and value.
371 void EmitInt8(int Value) const;
373 /// Emit a short directive and value.
375 void EmitInt16(int Value) const;
377 /// Emit a long directive and value.
379 void EmitInt32(int Value) const;
381 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
382 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
383 /// .set if it is available.
384 void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
385 unsigned Size) const;
387 /// Emit something like ".long Label+Offset" where the size in bytes of the
388 /// directive is specified by Size and Label specifies the label. This
389 /// implicitly uses .set if it is available.
390 void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
391 unsigned Size, bool IsSectionRelative = false) const;
393 /// Emit something like ".long Label" where the size in bytes of the directive
394 /// is specified by Size and Label specifies the label.
395 void EmitLabelReference(const MCSymbol *Label, unsigned Size,
396 bool IsSectionRelative = false) const {
397 EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
400 //===------------------------------------------------------------------===//
401 // Dwarf Emission Helper Routines
402 //===------------------------------------------------------------------===//
404 /// Emit the specified signed leb128 value.
405 void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
407 /// Emit the specified unsigned leb128 value.
408 void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
409 unsigned PadTo = 0) const;
411 /// Emit a .byte 42 directive for a DW_CFA_xxx value.
412 void EmitCFAByte(unsigned Val) const;
414 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
415 /// assembly output is enabled, we output comments describing the encoding.
416 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
417 void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
419 /// Return the size of the encoding in bytes.
420 unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
422 /// Emit reference to a ttype global with a specified encoding.
423 void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
425 /// Emit the 4-byte offset of Label from the start of its section. This can
426 /// be done with a special directive if the target supports it (e.g. cygwin)
427 /// or by emitting it as an offset from a label at the start of the section.
429 /// SectionLabel is a temporary label emitted at the start of the section
430 /// that Label lives in.
431 void EmitSectionOffset(const MCSymbol *Label,
432 const MCSymbol *SectionLabel) const;
434 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
435 virtual unsigned getISAEncoding(const Function *) { return 0; }
437 /// EmitDwarfRegOp - Emit a dwarf register operation.
438 virtual void EmitDwarfRegOp(ByteStreamer &BS,
439 const MachineLocation &MLoc) const;
441 //===------------------------------------------------------------------===//
442 // Dwarf Lowering Routines
443 //===------------------------------------------------------------------===//
445 /// \brief Emit frame instruction to describe the layout of the frame.
446 void emitCFIInstruction(const MCCFIInstruction &Inst) const;
448 //===------------------------------------------------------------------===//
449 // Inline Asm Support
450 //===------------------------------------------------------------------===//
452 // These are hooks that targets can override to implement inline asm
453 // support. These should probably be moved out of AsmPrinter someday.
455 /// Print information related to the specified machine instr that is
456 /// independent of the operand, and may be independent of the instr itself.
457 /// This can be useful for portably encoding the comment character or other
458 /// bits of target-specific knowledge into the asmstrings. The syntax used is
459 /// ${:comment}. Targets can override this to add support for their own
461 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
462 const char *Code) const;
464 /// Print the specified operand of MI, an INLINEASM instruction, using the
465 /// specified assembler variant. Targets should override this to format as
466 /// appropriate. This method can return true if the operand is erroneous.
467 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
468 unsigned AsmVariant, const char *ExtraCode,
471 /// Print the specified operand of MI, an INLINEASM instruction, using the
472 /// specified assembler variant as an address. Targets should override this to
473 /// format as appropriate. This method can return true if the operand is
475 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
476 unsigned AsmVariant, const char *ExtraCode,
479 /// Let the target do anything it needs to do before emitting inlineasm.
480 /// \p StartInfo - the subtarget info before parsing inline asm
481 virtual void emitInlineAsmStart() const;
483 /// Let the target do anything it needs to do after emitting inlineasm.
484 /// This callback can be used restore the original mode in case the
485 /// inlineasm contains directives to switch modes.
486 /// \p StartInfo - the original subtarget info before inline asm
487 /// \p EndInfo - the final subtarget info after parsing the inline asm,
488 /// or NULL if the value is unknown.
489 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
490 const MCSubtargetInfo *EndInfo) const;
493 /// Private state for PrintSpecial()
494 // Assign a unique ID to this machine instruction.
495 mutable const MachineInstr *LastMI;
496 mutable unsigned LastFn;
497 mutable unsigned Counter;
498 mutable unsigned SetCounter;
500 /// Emit a blob of inline asm to the output streamer.
502 EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = nullptr,
503 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
505 /// This method formats and emits the specified machine instruction that is an
507 void EmitInlineAsm(const MachineInstr *MI) const;
509 //===------------------------------------------------------------------===//
510 // Internal Implementation Details
511 //===------------------------------------------------------------------===//
513 /// This emits visibility information about symbol, if this is suported by the
515 void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
516 bool IsDefinition = true) const;
518 void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
520 void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
521 const MachineBasicBlock *MBB, unsigned uid) const;
522 void EmitLLVMUsedList(const ConstantArray *InitList);
523 /// Emit llvm.ident metadata in an '.ident' directive.
524 void EmitModuleIdents(Module &M);
525 void EmitXXStructorList(const Constant *List, bool isCtor);
526 GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C);