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;
34 class GCMetadataPrinter;
37 class MachineBasicBlock;
38 class MachineFunction;
40 class MachineLocation;
41 class MachineLoopInfo;
43 class MachineConstantPoolValue;
44 class MachineJumpTableInfo;
45 class MachineModuleInfo;
47 class MCCFIInstruction;
53 class MCSubtargetInfo;
58 class TargetLoweringObjectFile;
62 /// This class is intended to be used as a driving class for all asm writers.
63 class AsmPrinter : public MachineFunctionPass {
65 /// Target machine description.
69 /// Target Asm Printer information.
73 /// This is the context for the output file that we are streaming. This owns
74 /// all of the global MC-related objects for the generated translation unit.
75 MCContext &OutContext;
77 /// This is the MCStreamer object for the file we are generating. This
78 /// contains the transient state for the current translation unit that we are
79 /// generating (such as the current section etc).
80 MCStreamer &OutStreamer;
82 /// The current machine function.
83 const MachineFunction *MF;
85 /// This is a pointer to the current MachineModuleInfo.
86 MachineModuleInfo *MMI;
88 /// Name-mangler for global names.
92 /// The symbol for the current function. This is recalculated at the beginning
93 /// of each call to runOnMachineFunction().
95 MCSymbol *CurrentFnSym;
97 /// The symbol used to represent the start of the current function for the
98 /// purpose of calculating its size (e.g. using the .size directive). By
99 /// default, this is equal to CurrentFnSym.
100 MCSymbol *CurrentFnSymForSize;
102 /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of
103 /// its number of uses by other globals.
104 typedef std::pair<const GlobalVariable *, unsigned> GOTEquivUsePair;
105 DenseMap<const MCSymbol *, GOTEquivUsePair> GlobalGOTEquivs;
108 MCSymbol *CurrentFnBegin;
109 MCSymbol *CurrentFnEnd;
111 // The garbage collection metadata printer table.
112 void *GCMetadataPrinters; // Really a DenseMap.
114 /// Emit comments in assembly output if this is true.
119 /// If VerboseAsm is set, a pointer to the loop info for this function.
123 AsmPrinterHandler *Handler;
124 const char *TimerName, *TimerGroupName;
125 HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName,
126 const char *TimerGroupName)
127 : Handler(Handler), TimerName(TimerName),
128 TimerGroupName(TimerGroupName) {}
130 /// A vector of all debug/EH info emitters we should use. This vector
131 /// maintains ownership of the emitters.
132 SmallVector<HandlerInfo, 1> Handlers;
134 /// If the target supports dwarf debug info, this pointer is non-null.
138 explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
141 virtual ~AsmPrinter();
143 DwarfDebug *getDwarfDebug() { return DD; }
144 DwarfDebug *getDwarfDebug() const { return DD; }
146 /// Return true if assembly output should contain comments.
148 bool isVerbose() const { return VerboseAsm; }
150 /// Return a unique ID for the current function.
152 unsigned getFunctionNumber() const;
154 MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
155 MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
157 /// Return information about object file lowering.
158 const TargetLoweringObjectFile &getObjFileLowering() const;
160 /// Return information about data layout.
161 const DataLayout &getDataLayout() const;
163 /// Return information about subtarget.
164 const MCSubtargetInfo &getSubtargetInfo() const;
166 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
168 /// Return the target triple string.
169 StringRef getTargetTriple() const;
171 /// Return the current section we are emitting to.
172 const MCSection *getCurrentSection() const;
174 void getNameWithPrefix(SmallVectorImpl<char> &Name,
175 const GlobalValue *GV) const;
177 MCSymbol *getSymbol(const GlobalValue *GV) const;
179 //===------------------------------------------------------------------===//
180 // MachineFunctionPass Implementation.
181 //===------------------------------------------------------------------===//
183 /// Record analysis usage.
185 void getAnalysisUsage(AnalysisUsage &AU) const override;
187 /// Set up the AsmPrinter when we are working on a new module. If your pass
188 /// overrides this, it must make sure to explicitly call this implementation.
189 bool doInitialization(Module &M) override;
191 /// Shut down the asmprinter. If you override this in your pass, you must make
192 /// sure to call it explicitly.
193 bool doFinalization(Module &M) override;
195 /// Emit the specified function out to the OutStreamer.
196 bool runOnMachineFunction(MachineFunction &MF) override {
197 SetupMachineFunction(MF);
198 EmitFunctionHeader();
203 //===------------------------------------------------------------------===//
204 // Coarse grained IR lowering routines.
205 //===------------------------------------------------------------------===//
207 /// This should be called when a new MachineFunction is being processed from
208 /// runOnMachineFunction.
209 void SetupMachineFunction(MachineFunction &MF);
211 /// This method emits the header for the current function.
212 void EmitFunctionHeader();
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 /// Return the MCSymbol corresponding to the assembler temporary label with
336 /// the specified stem and unique ID.
337 MCSymbol *GetTempSymbol(const Twine &Name, unsigned ID) const;
339 /// Return an assembler temporary label with the specified stem.
340 MCSymbol *GetTempSymbol(const Twine &Name) const;
342 MCSymbol *createTempSymbol(const Twine &Name, unsigned ID) const;
344 /// Return the MCSymbol for a private symbol with global value name as its
345 /// base, with the specified suffix.
346 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
347 StringRef Suffix) const;
349 /// Return the MCSymbol for the specified ExternalSymbol.
350 MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
352 /// Return the symbol for the specified jump table entry.
353 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
355 /// Return the symbol for the specified jump table .set
356 /// FIXME: privatize to AsmPrinter.
357 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
359 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
361 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
362 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
364 //===------------------------------------------------------------------===//
365 // Emission Helper Routines.
366 //===------------------------------------------------------------------===//
368 /// This is just convenient handler for printing offsets.
369 void printOffset(int64_t Offset, raw_ostream &OS) const;
371 /// Emit a byte directive and value.
373 void EmitInt8(int Value) const;
375 /// Emit a short directive and value.
377 void EmitInt16(int Value) const;
379 /// Emit a long directive and value.
381 void EmitInt32(int Value) const;
383 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
384 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
385 /// .set if it is available.
386 void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
387 unsigned Size) const;
389 /// Emit something like ".long Label+Offset" where the size in bytes of the
390 /// directive is specified by Size and Label specifies the label. This
391 /// implicitly uses .set if it is available.
392 void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
393 unsigned Size, bool IsSectionRelative = false) const;
395 /// Emit something like ".long Label" where the size in bytes of the directive
396 /// is specified by Size and Label specifies the label.
397 void EmitLabelReference(const MCSymbol *Label, unsigned Size,
398 bool IsSectionRelative = false) const {
399 EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
402 //===------------------------------------------------------------------===//
403 // Dwarf Emission Helper Routines
404 //===------------------------------------------------------------------===//
406 /// Emit the specified signed leb128 value.
407 void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
409 /// Emit the specified unsigned leb128 value.
410 void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
411 unsigned PadTo = 0) const;
413 /// Emit a .byte 42 directive for a DW_CFA_xxx value.
414 void EmitCFAByte(unsigned Val) const;
416 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
417 /// assembly output is enabled, we output comments describing the encoding.
418 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
419 void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
421 /// Return the size of the encoding in bytes.
422 unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
424 /// Emit reference to a ttype global with a specified encoding.
425 void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
427 /// Emit the 4-byte offset of Label from the start of its section. This can
428 /// be done with a special directive if the target supports it (e.g. cygwin)
429 /// or by emitting it as an offset from a label at the start of the section.
430 void emitSectionOffset(const MCSymbol *Label) const;
432 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
433 virtual unsigned getISAEncoding(const Function *) { return 0; }
435 /// EmitDwarfRegOp - Emit a dwarf register operation.
436 virtual void EmitDwarfRegOp(ByteStreamer &BS,
437 const MachineLocation &MLoc) const;
439 //===------------------------------------------------------------------===//
440 // Dwarf Lowering Routines
441 //===------------------------------------------------------------------===//
443 /// \brief Emit frame instruction to describe the layout of the frame.
444 void emitCFIInstruction(const MCCFIInstruction &Inst) const;
446 /// \brief Emit Dwarf abbreviation table.
447 void emitDwarfAbbrevs(const std::vector<DIEAbbrev *>& Abbrevs) const;
449 /// \brief Recursively emit Dwarf DIE tree.
450 void emitDwarfDIE(const DIE &Die) const;
452 //===------------------------------------------------------------------===//
453 // Inline Asm Support
454 //===------------------------------------------------------------------===//
456 // These are hooks that targets can override to implement inline asm
457 // support. These should probably be moved out of AsmPrinter someday.
459 /// Print information related to the specified machine instr that is
460 /// independent of the operand, and may be independent of the instr itself.
461 /// This can be useful for portably encoding the comment character or other
462 /// bits of target-specific knowledge into the asmstrings. The syntax used is
463 /// ${:comment}. Targets can override this to add support for their own
465 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
466 const char *Code) const;
468 /// Print the specified operand of MI, an INLINEASM instruction, using the
469 /// specified assembler variant. Targets should override this to format as
470 /// appropriate. This method can return true if the operand is erroneous.
471 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
472 unsigned AsmVariant, const char *ExtraCode,
475 /// Print the specified operand of MI, an INLINEASM instruction, using the
476 /// specified assembler variant as an address. Targets should override this to
477 /// format as appropriate. This method can return true if the operand is
479 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
480 unsigned AsmVariant, const char *ExtraCode,
483 /// Let the target do anything it needs to do before emitting inlineasm.
484 /// \p StartInfo - the subtarget info before parsing inline asm
485 virtual void emitInlineAsmStart() const;
487 /// Let the target do anything it needs to do after emitting inlineasm.
488 /// This callback can be used restore the original mode in case the
489 /// inlineasm contains directives to switch modes.
490 /// \p StartInfo - the original subtarget info before inline asm
491 /// \p EndInfo - the final subtarget info after parsing the inline asm,
492 /// or NULL if the value is unknown.
493 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
494 const MCSubtargetInfo *EndInfo) const;
497 /// Private state for PrintSpecial()
498 // Assign a unique ID to this machine instruction.
499 mutable const MachineInstr *LastMI;
500 mutable unsigned LastFn;
501 mutable unsigned Counter;
502 mutable unsigned SetCounter;
504 /// Emit a blob of inline asm to the output streamer.
506 EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = nullptr,
507 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
509 /// This method formats and emits the specified machine instruction that is an
511 void EmitInlineAsm(const MachineInstr *MI) const;
513 //===------------------------------------------------------------------===//
514 // Internal Implementation Details
515 //===------------------------------------------------------------------===//
517 /// This emits visibility information about symbol, if this is suported by the
519 void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
520 bool IsDefinition = true) const;
522 void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
524 void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
525 const MachineBasicBlock *MBB, unsigned uid) const;
526 void EmitLLVMUsedList(const ConstantArray *InitList);
527 /// Emit llvm.ident metadata in an '.ident' directive.
528 void EmitModuleIdents(Module &M);
529 void EmitXXStructorList(const Constant *List, bool isCtor);
530 GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C);