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;
101 // The garbage collection metadata printer table.
102 void *GCMetadataPrinters; // Really a DenseMap.
104 /// Emit comments in assembly output if this is true.
109 /// If VerboseAsm is set, a pointer to the loop info for this function.
113 AsmPrinterHandler *Handler;
114 const char *TimerName, *TimerGroupName;
115 HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName,
116 const char *TimerGroupName)
117 : Handler(Handler), TimerName(TimerName),
118 TimerGroupName(TimerGroupName) {}
120 /// A vector of all debug/EH info emitters we should use. This vector
121 /// maintains ownership of the emitters.
122 SmallVector<HandlerInfo, 1> Handlers;
124 /// If the target supports dwarf debug info, this pointer is non-null.
128 explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
131 virtual ~AsmPrinter();
133 DwarfDebug *getDwarfDebug() { return DD; }
134 DwarfDebug *getDwarfDebug() const { return DD; }
136 /// Return true if assembly output should contain comments.
138 bool isVerbose() const { return VerboseAsm; }
140 /// Return a unique ID for the current function.
142 unsigned getFunctionNumber() const;
144 /// Return information about object file lowering.
145 const TargetLoweringObjectFile &getObjFileLowering() const;
147 /// Return information about data layout.
148 const DataLayout &getDataLayout() const;
150 /// Return information about subtarget.
151 const MCSubtargetInfo &getSubtargetInfo() const;
153 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
155 /// Return the target triple string.
156 StringRef getTargetTriple() const;
158 /// Return the current section we are emitting to.
159 const MCSection *getCurrentSection() const;
161 void getNameWithPrefix(SmallVectorImpl<char> &Name,
162 const GlobalValue *GV) const;
164 MCSymbol *getSymbol(const GlobalValue *GV) const;
166 //===------------------------------------------------------------------===//
167 // MachineFunctionPass Implementation.
168 //===------------------------------------------------------------------===//
170 /// Record analysis usage.
172 void getAnalysisUsage(AnalysisUsage &AU) const override;
174 /// Set up the AsmPrinter when we are working on a new module. If your pass
175 /// overrides this, it must make sure to explicitly call this implementation.
176 bool doInitialization(Module &M) override;
178 /// Shut down the asmprinter. If you override this in your pass, you must make
179 /// sure to call it explicitly.
180 bool doFinalization(Module &M) override;
182 /// Emit the specified function out to the OutStreamer.
183 bool runOnMachineFunction(MachineFunction &MF) override {
184 SetupMachineFunction(MF);
185 EmitFunctionHeader();
190 //===------------------------------------------------------------------===//
191 // Coarse grained IR lowering routines.
192 //===------------------------------------------------------------------===//
194 /// This should be called when a new MachineFunction is being processed from
195 /// runOnMachineFunction.
196 void SetupMachineFunction(MachineFunction &MF);
198 /// This method emits the header for the current function.
199 void EmitFunctionHeader();
201 /// This method emits the body and trailer for a function.
202 void EmitFunctionBody();
204 void emitCFIInstruction(const MachineInstr &MI);
206 void emitFrameAlloc(const MachineInstr &MI);
208 enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug };
209 CFIMoveType needsCFIMoves();
211 bool needsSEHMoves();
213 /// Print to the current output stream assembly representations of the
214 /// constants in the constant pool MCP. This is used to print out constants
215 /// which have been "spilled to memory" by the code generator.
217 virtual void EmitConstantPool();
219 /// Print assembly representations of the jump tables used by the current
220 /// function to the current output stream.
222 void EmitJumpTableInfo();
224 /// Emit the specified global variable to the .s file.
225 virtual void EmitGlobalVariable(const GlobalVariable *GV);
227 /// Check to see if the specified global is a special global used by LLVM. If
228 /// so, emit it and return true, otherwise do nothing and return false.
229 bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
231 /// Emit an alignment directive to the specified power of two boundary. For
232 /// example, if you pass in 3 here, you will get an 8 byte alignment. If a
233 /// global value is specified, and if that global has an explicit alignment
234 /// requested, it will override the alignment request if required for
237 void EmitAlignment(unsigned NumBits, const GlobalObject *GO = nullptr) const;
239 /// Lower the specified LLVM Constant to an MCExpr.
240 const MCExpr *lowerConstant(const Constant *CV);
242 /// \brief Print a general LLVM constant to the .s file.
243 void EmitGlobalConstant(const Constant *CV);
245 //===------------------------------------------------------------------===//
247 //===------------------------------------------------------------------===//
249 // Targets can, or in the case of EmitInstruction, must implement these to
252 /// This virtual method can be overridden by targets that want to emit
253 /// something at the start of their file.
254 virtual void EmitStartOfAsmFile(Module &) {}
256 /// This virtual method can be overridden by targets that want to emit
257 /// something at the end of their file.
258 virtual void EmitEndOfAsmFile(Module &) {}
260 /// Targets can override this to emit stuff before the first basic block in
262 virtual void EmitFunctionBodyStart() {}
264 /// Targets can override this to emit stuff after the last basic block in the
266 virtual void EmitFunctionBodyEnd() {}
268 /// Targets can override this to emit stuff at the start of a basic block.
269 /// By default, this method prints the label for the specified
270 /// MachineBasicBlock, an alignment (if present) and a comment describing it
272 virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const;
274 /// Targets can override this to emit stuff at the end of a basic block.
275 virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB) {}
277 /// Targets should implement this to emit instructions.
278 virtual void EmitInstruction(const MachineInstr *) {
279 llvm_unreachable("EmitInstruction not implemented");
282 /// Return the symbol for the specified constant pool entry.
283 virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
285 virtual void EmitFunctionEntryLabel();
287 virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
289 /// Targets can override this to change how global constants that are part of
290 /// a C++ static/global constructor list are emitted.
291 virtual void EmitXXStructor(const Constant *CV) { EmitGlobalConstant(CV); }
293 /// Return true if the basic block has exactly one predecessor and the control
294 /// transfer mechanism between the predecessor and this block is a
297 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
299 /// Targets can override this to customize the output of IMPLICIT_DEF
300 /// instructions in verbose mode.
301 virtual void emitImplicitDef(const MachineInstr *MI) const;
303 //===------------------------------------------------------------------===//
304 // Symbol Lowering Routines.
305 //===------------------------------------------------------------------===//
307 /// Return the MCSymbol corresponding to the assembler temporary label with
308 /// the specified stem and unique ID.
309 MCSymbol *GetTempSymbol(const Twine &Name, unsigned ID) const;
311 /// Return an assembler temporary label with the specified stem.
312 MCSymbol *GetTempSymbol(const Twine &Name) const;
314 /// Return the MCSymbol for a private symbol with global value name as its
315 /// base, with the specified suffix.
316 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
317 StringRef Suffix) const;
319 /// Return the MCSymbol for the specified ExternalSymbol.
320 MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
322 /// Return the symbol for the specified jump table entry.
323 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
325 /// Return the symbol for the specified jump table .set
326 /// FIXME: privatize to AsmPrinter.
327 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
329 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
331 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
332 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
334 //===------------------------------------------------------------------===//
335 // Emission Helper Routines.
336 //===------------------------------------------------------------------===//
338 /// This is just convenient handler for printing offsets.
339 void printOffset(int64_t Offset, raw_ostream &OS) const;
341 /// Emit a byte directive and value.
343 void EmitInt8(int Value) const;
345 /// Emit a short directive and value.
347 void EmitInt16(int Value) const;
349 /// Emit a long directive and value.
351 void EmitInt32(int Value) const;
353 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
354 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
355 /// .set if it is available.
356 void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
357 unsigned Size) const;
359 /// Emit something like ".long Label+Offset" where the size in bytes of the
360 /// directive is specified by Size and Label specifies the label. This
361 /// implicitly uses .set if it is available.
362 void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
363 unsigned Size, bool IsSectionRelative = false) const;
365 /// Emit something like ".long Label" where the size in bytes of the directive
366 /// is specified by Size and Label specifies the label.
367 void EmitLabelReference(const MCSymbol *Label, unsigned Size,
368 bool IsSectionRelative = false) const {
369 EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
372 //===------------------------------------------------------------------===//
373 // Dwarf Emission Helper Routines
374 //===------------------------------------------------------------------===//
376 /// Emit the specified signed leb128 value.
377 void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
379 /// Emit the specified unsigned leb128 value.
380 void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
381 unsigned PadTo = 0) const;
383 /// Emit a .byte 42 directive for a DW_CFA_xxx value.
384 void EmitCFAByte(unsigned Val) const;
386 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
387 /// assembly output is enabled, we output comments describing the encoding.
388 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
389 void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
391 /// Return the size of the encoding in bytes.
392 unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
394 /// Emit reference to a ttype global with a specified encoding.
395 void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
397 /// Emit the 4-byte offset of Label from the start of its section. This can
398 /// be done with a special directive if the target supports it (e.g. cygwin)
399 /// or by emitting it as an offset from a label at the start of the section.
401 /// SectionLabel is a temporary label emitted at the start of the section
402 /// that Label lives in.
403 void EmitSectionOffset(const MCSymbol *Label,
404 const MCSymbol *SectionLabel) const;
406 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
407 virtual unsigned getISAEncoding(const Function *) { return 0; }
409 /// Emit a dwarf register operation for describing
410 /// - a small value occupying only part of a register or
411 /// - a register representing only part of a value.
412 void EmitDwarfOpPiece(ByteStreamer &Streamer, unsigned SizeInBits,
413 unsigned OffsetInBits = 0) const;
416 /// \brief Emit a partial DWARF register operation.
417 /// \param MLoc the register
418 /// \param PieceSize size and
419 /// \param PieceOffset offset of the piece in bits, if this is one
420 /// piece of an aggregate value.
422 /// If size and offset is zero an operation for the entire
423 /// register is emitted: Some targets do not provide a DWARF
424 /// register number for every register. If this is the case, this
425 /// function will attempt to emit a DWARF register by emitting a
426 /// piece of a super-register or by piecing together multiple
427 /// subregisters that alias the register.
428 void EmitDwarfRegOpPiece(ByteStreamer &BS, const MachineLocation &MLoc,
429 unsigned PieceSize = 0,
430 unsigned PieceOffset = 0) const;
432 /// EmitDwarfRegOp - Emit a dwarf register operation.
433 virtual void EmitDwarfRegOp(ByteStreamer &BS,
434 const MachineLocation &MLoc) const;
436 //===------------------------------------------------------------------===//
437 // Dwarf Lowering Routines
438 //===------------------------------------------------------------------===//
440 /// \brief Emit frame instruction to describe the layout of the frame.
441 void emitCFIInstruction(const MCCFIInstruction &Inst) const;
443 //===------------------------------------------------------------------===//
444 // Inline Asm Support
445 //===------------------------------------------------------------------===//
447 // These are hooks that targets can override to implement inline asm
448 // support. These should probably be moved out of AsmPrinter someday.
450 /// Print information related to the specified machine instr that is
451 /// independent of the operand, and may be independent of the instr itself.
452 /// This can be useful for portably encoding the comment character or other
453 /// bits of target-specific knowledge into the asmstrings. The syntax used is
454 /// ${:comment}. Targets can override this to add support for their own
456 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
457 const char *Code) const;
459 /// Print the specified operand of MI, an INLINEASM instruction, using the
460 /// specified assembler variant. Targets should override this to format as
461 /// appropriate. This method can return true if the operand is erroneous.
462 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
463 unsigned AsmVariant, const char *ExtraCode,
466 /// Print the specified operand of MI, an INLINEASM instruction, using the
467 /// specified assembler variant as an address. Targets should override this to
468 /// format as appropriate. This method can return true if the operand is
470 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
471 unsigned AsmVariant, const char *ExtraCode,
474 /// Let the target do anything it needs to do before emitting inlineasm.
475 /// \p StartInfo - the subtarget info before parsing inline asm
476 virtual void emitInlineAsmStart() const;
478 /// Let the target do anything it needs to do after emitting inlineasm.
479 /// This callback can be used restore the original mode in case the
480 /// inlineasm contains directives to switch modes.
481 /// \p StartInfo - the original subtarget info before inline asm
482 /// \p EndInfo - the final subtarget info after parsing the inline asm,
483 /// or NULL if the value is unknown.
484 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
485 const MCSubtargetInfo *EndInfo) const;
488 /// Private state for PrintSpecial()
489 // Assign a unique ID to this machine instruction.
490 mutable const MachineInstr *LastMI;
491 mutable unsigned LastFn;
492 mutable unsigned Counter;
493 mutable unsigned SetCounter;
495 /// Emit a blob of inline asm to the output streamer.
497 EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = nullptr,
498 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
500 /// This method formats and emits the specified machine instruction that is an
502 void EmitInlineAsm(const MachineInstr *MI) const;
504 //===------------------------------------------------------------------===//
505 // Internal Implementation Details
506 //===------------------------------------------------------------------===//
508 /// This emits visibility information about symbol, if this is suported by the
510 void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
511 bool IsDefinition = true) const;
513 void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
515 void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
516 const MachineBasicBlock *MBB, unsigned uid) const;
517 void EmitLLVMUsedList(const ConstantArray *InitList);
518 /// Emit llvm.ident metadata in an '.ident' directive.
519 void EmitModuleIdents(Module &M);
520 void EmitXXStructorList(const Constant *List, bool isCtor);
521 GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C);