Stop resetting SanitizeAddress in TargetMachine::resetTargetOptions. 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/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"
25
26 namespace llvm {
27 class AsmPrinterHandler;
28 class BlockAddress;
29 class ByteStreamer;
30 class GCStrategy;
31 class Constant;
32 class ConstantArray;
33 class DIE;
34 class DIEAbbrev;
35 class GCMetadataPrinter;
36 class GlobalValue;
37 class GlobalVariable;
38 class MachineBasicBlock;
39 class MachineFunction;
40 class MachineInstr;
41 class MachineLocation;
42 class MachineLoopInfo;
43 class MachineLoop;
44 class MachineConstantPoolValue;
45 class MachineJumpTableInfo;
46 class MachineModuleInfo;
47 class MCAsmInfo;
48 class MCCFIInstruction;
49 class MCContext;
50 class MCExpr;
51 class MCInst;
52 class MCSection;
53 class MCStreamer;
54 class MCSubtargetInfo;
55 class MCSymbol;
56 class MCTargetOptions;
57 class MDNode;
58 class DwarfDebug;
59 class Mangler;
60 class TargetLoweringObjectFile;
61 class DataLayout;
62 class TargetMachine;
63
64 /// This class is intended to be used as a driving class for all asm writers.
65 class AsmPrinter : public MachineFunctionPass {
66 public:
67   /// Target machine description.
68   ///
69   TargetMachine &TM;
70
71   /// Target Asm Printer information.
72   ///
73   const MCAsmInfo *MAI;
74
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;
78
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;
83
84   /// The current machine function.
85   const MachineFunction *MF;
86
87   /// This is a pointer to the current MachineModuleInfo.
88   MachineModuleInfo *MMI;
89
90   /// Name-mangler for global names.
91   ///
92   Mangler *Mang;
93
94   /// The symbol for the current function. This is recalculated at the beginning
95   /// of each call to runOnMachineFunction().
96   ///
97   MCSymbol *CurrentFnSym;
98
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;
103
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;
108
109 private:
110   MCSymbol *CurrentFnBegin;
111   MCSymbol *CurrentFnEnd;
112   MCSymbol *CurExceptionSym;
113
114   // The garbage collection metadata printer table.
115   void *GCMetadataPrinters; // Really a DenseMap.
116
117   /// Emit comments in assembly output if this is true.
118   ///
119   bool VerboseAsm;
120   static char ID;
121
122   /// If VerboseAsm is set, a pointer to the loop info for this function.
123   MachineLoopInfo *LI;
124
125   struct HandlerInfo {
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) {}
132   };
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;
136
137   /// If the target supports dwarf debug info, this pointer is non-null.
138   DwarfDebug *DD;
139
140 protected:
141   explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
142
143 public:
144   ~AsmPrinter() override;
145
146   DwarfDebug *getDwarfDebug() { return DD; }
147   DwarfDebug *getDwarfDebug() const { return DD; }
148
149   /// Return true if assembly output should contain comments.
150   ///
151   bool isVerbose() const { return VerboseAsm; }
152
153   /// Return a unique ID for the current function.
154   ///
155   unsigned getFunctionNumber() const;
156
157   MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
158   MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
159   MCSymbol *getCurExceptionSym();
160
161   /// Return information about object file lowering.
162   const TargetLoweringObjectFile &getObjFileLowering() const;
163
164   /// Return information about data layout.
165   const DataLayout &getDataLayout() const;
166
167   /// Return information about subtarget.
168   const MCSubtargetInfo &getSubtargetInfo() const;
169
170   void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
171
172   /// Return the target triple string.
173   StringRef getTargetTriple() const;
174
175   /// Return the current section we are emitting to.
176   const MCSection *getCurrentSection() const;
177
178   void getNameWithPrefix(SmallVectorImpl<char> &Name,
179                          const GlobalValue *GV) const;
180
181   MCSymbol *getSymbol(const GlobalValue *GV) const;
182
183   //===------------------------------------------------------------------===//
184   // MachineFunctionPass Implementation.
185   //===------------------------------------------------------------------===//
186
187   /// Record analysis usage.
188   ///
189   void getAnalysisUsage(AnalysisUsage &AU) const override;
190
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;
194
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;
198
199   /// Emit the specified function out to the OutStreamer.
200   bool runOnMachineFunction(MachineFunction &MF) override {
201     SetupMachineFunction(MF);
202     EmitFunctionBody();
203     return false;
204   }
205
206   //===------------------------------------------------------------------===//
207   // Coarse grained IR lowering routines.
208   //===------------------------------------------------------------------===//
209
210   /// This should be called when a new MachineFunction is being processed from
211   /// runOnMachineFunction.
212   void SetupMachineFunction(MachineFunction &MF);
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   MCSymbol *createTempSymbol(const Twine &Name) const;
336
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;
341
342   /// Return the MCSymbol for the specified ExternalSymbol.
343   MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
344
345   /// Return the symbol for the specified jump table entry.
346   MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
347
348   /// Return the symbol for the specified jump table .set
349   /// FIXME: privatize to AsmPrinter.
350   MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
351
352   /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
353   /// basic block.
354   MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
355   MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
356
357   //===------------------------------------------------------------------===//
358   // Emission Helper Routines.
359   //===------------------------------------------------------------------===//
360 public:
361   /// This is just convenient handler for printing offsets.
362   void printOffset(int64_t Offset, raw_ostream &OS) const;
363
364   /// Emit a byte directive and value.
365   ///
366   void EmitInt8(int Value) const;
367
368   /// Emit a short directive and value.
369   ///
370   void EmitInt16(int Value) const;
371
372   /// Emit a long directive and value.
373   ///
374   void EmitInt32(int Value) const;
375
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;
381
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;
387
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);
393   }
394
395   //===------------------------------------------------------------------===//
396   // Dwarf Emission Helper Routines
397   //===------------------------------------------------------------------===//
398
399   /// Emit the specified signed leb128 value.
400   void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
401
402   /// Emit the specified unsigned leb128 value.
403   void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
404                    unsigned PadTo = 0) const;
405
406   /// Emit a .byte 42 directive for a DW_CFA_xxx value.
407   void EmitCFAByte(unsigned Val) const;
408
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;
413
414   /// Return the size of the encoding in bytes.
415   unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
416
417   /// Emit reference to a ttype global with a specified encoding.
418   void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
419
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;
424
425   /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
426   virtual unsigned getISAEncoding() { return 0; }
427
428   /// EmitDwarfRegOp - Emit a dwarf register operation.
429   virtual void EmitDwarfRegOp(ByteStreamer &BS,
430                               const MachineLocation &MLoc) const;
431
432   //===------------------------------------------------------------------===//
433   // Dwarf Lowering Routines
434   //===------------------------------------------------------------------===//
435
436   /// \brief Emit frame instruction to describe the layout of the frame.
437   void emitCFIInstruction(const MCCFIInstruction &Inst) const;
438
439   /// \brief Emit Dwarf abbreviation table.
440   void emitDwarfAbbrevs(const std::vector<DIEAbbrev *>& Abbrevs) const;
441
442   /// \brief Recursively emit Dwarf DIE tree.
443   void emitDwarfDIE(const DIE &Die) const;
444
445   //===------------------------------------------------------------------===//
446   // Inline Asm Support
447   //===------------------------------------------------------------------===//
448 public:
449   // These are hooks that targets can override to implement inline asm
450   // support.  These should probably be moved out of AsmPrinter someday.
451
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
457   /// strange codes.
458   virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
459                             const char *Code) const;
460
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,
466                                raw_ostream &OS);
467
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
471   /// erroneous.
472   virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
473                                      unsigned AsmVariant, const char *ExtraCode,
474                                      raw_ostream &OS);
475
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;
479
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;
488
489 private:
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;
495
496   /// This method emits the header for the current function.
497   void EmitFunctionHeader();
498
499   /// Emit a blob of inline asm to the output streamer.
500   void
501   EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
502                 const MCTargetOptions &MCOptions,
503                 const MDNode *LocMDNode = nullptr,
504                 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
505
506   /// This method formats and emits the specified machine instruction that is an
507   /// inline asm.
508   void EmitInlineAsm(const MachineInstr *MI) const;
509
510   //===------------------------------------------------------------------===//
511   // Internal Implementation Details
512   //===------------------------------------------------------------------===//
513
514   /// This emits visibility information about symbol, if this is suported by the
515   /// target.
516   void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
517                       bool IsDefinition = true) const;
518
519   void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
520
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);
528 };
529 }
530
531 #endif