Move emitDIE and emitAbbrevs to AsmPrinter. NFC.
[oota-llvm.git] / include / llvm / CodeGen / AsmPrinter.h
1 //===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // all asm writers.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_ASMPRINTER_H
17 #define LLVM_CODEGEN_ASMPRINTER_H
18
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"
24
25 namespace llvm {
26 class AsmPrinterHandler;
27 class BlockAddress;
28 class ByteStreamer;
29 class GCStrategy;
30 class Constant;
31 class ConstantArray;
32 class DIE;
33 class DIEAbbrev;
34 class GCMetadataPrinter;
35 class GlobalValue;
36 class GlobalVariable;
37 class MachineBasicBlock;
38 class MachineFunction;
39 class MachineInstr;
40 class MachineLocation;
41 class MachineLoopInfo;
42 class MachineLoop;
43 class MachineConstantPoolValue;
44 class MachineJumpTableInfo;
45 class MachineModuleInfo;
46 class MCAsmInfo;
47 class MCCFIInstruction;
48 class MCContext;
49 class MCExpr;
50 class MCInst;
51 class MCSection;
52 class MCStreamer;
53 class MCSubtargetInfo;
54 class MCSymbol;
55 class MDNode;
56 class DwarfDebug;
57 class Mangler;
58 class TargetLoweringObjectFile;
59 class DataLayout;
60 class TargetMachine;
61
62 /// This class is intended to be used as a driving class for all asm writers.
63 class AsmPrinter : public MachineFunctionPass {
64 public:
65   /// Target machine description.
66   ///
67   TargetMachine &TM;
68
69   /// Target Asm Printer information.
70   ///
71   const MCAsmInfo *MAI;
72
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;
76
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;
81
82   /// The current machine function.
83   const MachineFunction *MF;
84
85   /// This is a pointer to the current MachineModuleInfo.
86   MachineModuleInfo *MMI;
87
88   /// Name-mangler for global names.
89   ///
90   Mangler *Mang;
91
92   /// The symbol for the current function. This is recalculated at the beginning
93   /// of each call to runOnMachineFunction().
94   ///
95   MCSymbol *CurrentFnSym;
96
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;
101
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;
106
107 private:
108   MCSymbol *CurrentFnBegin;
109   MCSymbol *CurrentFnEnd;
110
111   // The garbage collection metadata printer table.
112   void *GCMetadataPrinters; // Really a DenseMap.
113
114   /// Emit comments in assembly output if this is true.
115   ///
116   bool VerboseAsm;
117   static char ID;
118
119   /// If VerboseAsm is set, a pointer to the loop info for this function.
120   MachineLoopInfo *LI;
121
122   struct HandlerInfo {
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) {}
129   };
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;
133
134   /// If the target supports dwarf debug info, this pointer is non-null.
135   DwarfDebug *DD;
136
137 protected:
138   explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
139
140 public:
141   virtual ~AsmPrinter();
142
143   DwarfDebug *getDwarfDebug() { return DD; }
144   DwarfDebug *getDwarfDebug() const { return DD; }
145
146   /// Return true if assembly output should contain comments.
147   ///
148   bool isVerbose() const { return VerboseAsm; }
149
150   /// Return a unique ID for the current function.
151   ///
152   unsigned getFunctionNumber() const;
153
154   MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
155   MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
156
157   /// Return information about object file lowering.
158   const TargetLoweringObjectFile &getObjFileLowering() const;
159
160   /// Return information about data layout.
161   const DataLayout &getDataLayout() const;
162
163   /// Return information about subtarget.
164   const MCSubtargetInfo &getSubtargetInfo() const;
165
166   void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
167
168   /// Return the target triple string.
169   StringRef getTargetTriple() const;
170
171   /// Return the current section we are emitting to.
172   const MCSection *getCurrentSection() const;
173
174   void getNameWithPrefix(SmallVectorImpl<char> &Name,
175                          const GlobalValue *GV) const;
176
177   MCSymbol *getSymbol(const GlobalValue *GV) const;
178
179   //===------------------------------------------------------------------===//
180   // MachineFunctionPass Implementation.
181   //===------------------------------------------------------------------===//
182
183   /// Record analysis usage.
184   ///
185   void getAnalysisUsage(AnalysisUsage &AU) const override;
186
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;
190
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;
194
195   /// Emit the specified function out to the OutStreamer.
196   bool runOnMachineFunction(MachineFunction &MF) override {
197     SetupMachineFunction(MF);
198     EmitFunctionHeader();
199     EmitFunctionBody();
200     return false;
201   }
202
203   //===------------------------------------------------------------------===//
204   // Coarse grained IR lowering routines.
205   //===------------------------------------------------------------------===//
206
207   /// This should be called when a new MachineFunction is being processed from
208   /// runOnMachineFunction.
209   void SetupMachineFunction(MachineFunction &MF);
210
211   /// This method emits the header for the current function.
212   void EmitFunctionHeader();
213
214   /// This method emits the body and trailer for a function.
215   void EmitFunctionBody();
216
217   void emitCFIInstruction(const MachineInstr &MI);
218
219   void emitFrameAlloc(const MachineInstr &MI);
220
221   enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug };
222   CFIMoveType needsCFIMoves();
223
224   bool needsSEHMoves();
225
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.
229   ///
230   virtual void EmitConstantPool();
231
232   /// Print assembly representations of the jump tables used by the current
233   /// function to the current output stream.
234   ///
235   void EmitJumpTableInfo();
236
237   /// Emit the specified global variable to the .s file.
238   virtual void EmitGlobalVariable(const GlobalVariable *GV);
239
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);
243
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
248   /// correctness.
249   ///
250   void EmitAlignment(unsigned NumBits, const GlobalObject *GO = nullptr) const;
251
252   /// Lower the specified LLVM Constant to an MCExpr.
253   const MCExpr *lowerConstant(const Constant *CV);
254
255   /// \brief Print a general LLVM constant to the .s file.
256   void EmitGlobalConstant(const Constant *CV);
257
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);
267
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();
272
273   //===------------------------------------------------------------------===//
274   // Overridable Hooks
275   //===------------------------------------------------------------------===//
276
277   // Targets can, or in the case of EmitInstruction, must implement these to
278   // customize output.
279
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 &) {}
283
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 &) {}
287
288   /// Targets can override this to emit stuff before the first basic block in
289   /// the function.
290   virtual void EmitFunctionBodyStart() {}
291
292   /// Targets can override this to emit stuff after the last basic block in the
293   /// function.
294   virtual void EmitFunctionBodyEnd() {}
295
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
299   /// if appropriate.
300   virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const;
301
302   /// Targets can override this to emit stuff at the end of a basic block.
303   virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB) {}
304
305   /// Targets should implement this to emit instructions.
306   virtual void EmitInstruction(const MachineInstr *) {
307     llvm_unreachable("EmitInstruction not implemented");
308   }
309
310   /// Return the symbol for the specified constant pool entry.
311   virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
312
313   virtual void EmitFunctionEntryLabel();
314
315   virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
316
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); }
320
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
323   /// fall-through.
324   virtual bool
325   isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
326
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;
330
331   //===------------------------------------------------------------------===//
332   // Symbol Lowering Routines.
333   //===------------------------------------------------------------------===//
334 public:
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;
338
339   /// Return an assembler temporary label with the specified stem.
340   MCSymbol *GetTempSymbol(const Twine &Name) const;
341
342   MCSymbol *createTempSymbol(const Twine &Name, unsigned ID) const;
343
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;
348
349   /// Return the MCSymbol for the specified ExternalSymbol.
350   MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
351
352   /// Return the symbol for the specified jump table entry.
353   MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
354
355   /// Return the symbol for the specified jump table .set
356   /// FIXME: privatize to AsmPrinter.
357   MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
358
359   /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
360   /// basic block.
361   MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
362   MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
363
364   //===------------------------------------------------------------------===//
365   // Emission Helper Routines.
366   //===------------------------------------------------------------------===//
367 public:
368   /// This is just convenient handler for printing offsets.
369   void printOffset(int64_t Offset, raw_ostream &OS) const;
370
371   /// Emit a byte directive and value.
372   ///
373   void EmitInt8(int Value) const;
374
375   /// Emit a short directive and value.
376   ///
377   void EmitInt16(int Value) const;
378
379   /// Emit a long directive and value.
380   ///
381   void EmitInt32(int Value) const;
382
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;
388
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;
394
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);
400   }
401
402   //===------------------------------------------------------------------===//
403   // Dwarf Emission Helper Routines
404   //===------------------------------------------------------------------===//
405
406   /// Emit the specified signed leb128 value.
407   void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
408
409   /// Emit the specified unsigned leb128 value.
410   void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
411                    unsigned PadTo = 0) const;
412
413   /// Emit a .byte 42 directive for a DW_CFA_xxx value.
414   void EmitCFAByte(unsigned Val) const;
415
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;
420
421   /// Return the size of the encoding in bytes.
422   unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
423
424   /// Emit reference to a ttype global with a specified encoding.
425   void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
426
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   ///
431   /// SectionLabel is a temporary label emitted at the start of the section
432   /// that Label lives in.
433   void EmitSectionOffset(const MCSymbol *Label,
434                          const MCSymbol *SectionLabel) const;
435
436   /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
437   virtual unsigned getISAEncoding(const Function *) { return 0; }
438
439   /// EmitDwarfRegOp - Emit a dwarf register operation.
440   virtual void EmitDwarfRegOp(ByteStreamer &BS,
441                               const MachineLocation &MLoc) const;
442
443   //===------------------------------------------------------------------===//
444   // Dwarf Lowering Routines
445   //===------------------------------------------------------------------===//
446
447   /// \brief Emit frame instruction to describe the layout of the frame.
448   void emitCFIInstruction(const MCCFIInstruction &Inst) const;
449
450   /// \brief Emit Dwarf abbreviation table.
451   void emitDwarfAbbrevs(const std::vector<DIEAbbrev *>& Abbrevs) const;
452
453   /// \brief Recursively emit Dwarf DIE tree.
454   void emitDwarfDIE(const DIE &Die) const;
455
456   //===------------------------------------------------------------------===//
457   // Inline Asm Support
458   //===------------------------------------------------------------------===//
459 public:
460   // These are hooks that targets can override to implement inline asm
461   // support.  These should probably be moved out of AsmPrinter someday.
462
463   /// Print information related to the specified machine instr that is
464   /// independent of the operand, and may be independent of the instr itself.
465   /// This can be useful for portably encoding the comment character or other
466   /// bits of target-specific knowledge into the asmstrings.  The syntax used is
467   /// ${:comment}.  Targets can override this to add support for their own
468   /// strange codes.
469   virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
470                             const char *Code) const;
471
472   /// Print the specified operand of MI, an INLINEASM instruction, using the
473   /// specified assembler variant.  Targets should override this to format as
474   /// appropriate.  This method can return true if the operand is erroneous.
475   virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
476                                unsigned AsmVariant, const char *ExtraCode,
477                                raw_ostream &OS);
478
479   /// Print the specified operand of MI, an INLINEASM instruction, using the
480   /// specified assembler variant as an address. Targets should override this to
481   /// format as appropriate.  This method can return true if the operand is
482   /// erroneous.
483   virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
484                                      unsigned AsmVariant, const char *ExtraCode,
485                                      raw_ostream &OS);
486
487   /// Let the target do anything it needs to do before emitting inlineasm.
488   /// \p StartInfo - the subtarget info before parsing inline asm
489   virtual void emitInlineAsmStart() const;
490
491   /// Let the target do anything it needs to do after emitting inlineasm.
492   /// This callback can be used restore the original mode in case the
493   /// inlineasm contains directives to switch modes.
494   /// \p StartInfo - the original subtarget info before inline asm
495   /// \p EndInfo   - the final subtarget info after parsing the inline asm,
496   ///                or NULL if the value is unknown.
497   virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
498                                 const MCSubtargetInfo *EndInfo) const;
499
500 private:
501   /// Private state for PrintSpecial()
502   // Assign a unique ID to this machine instruction.
503   mutable const MachineInstr *LastMI;
504   mutable unsigned LastFn;
505   mutable unsigned Counter;
506   mutable unsigned SetCounter;
507
508   /// Emit a blob of inline asm to the output streamer.
509   void
510   EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = nullptr,
511                 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
512
513   /// This method formats and emits the specified machine instruction that is an
514   /// inline asm.
515   void EmitInlineAsm(const MachineInstr *MI) const;
516
517   //===------------------------------------------------------------------===//
518   // Internal Implementation Details
519   //===------------------------------------------------------------------===//
520
521   /// This emits visibility information about symbol, if this is suported by the
522   /// target.
523   void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
524                       bool IsDefinition = true) const;
525
526   void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
527
528   void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
529                           const MachineBasicBlock *MBB, unsigned uid) const;
530   void EmitLLVMUsedList(const ConstantArray *InitList);
531   /// Emit llvm.ident metadata in an '.ident' directive.
532   void EmitModuleIdents(Module &M);
533   void EmitXXStructorList(const Constant *List, bool isCtor);
534   GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C);
535 };
536 }
537
538 #endif