1//===- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a class to be used as the base class for target specific
10// asm writers. This class primarily handles common functionality used by
11// all asm writers.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_ASMPRINTER_H
16#define LLVM_CODEGEN_ASMPRINTER_H
17
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Analysis/ProfileSummaryInfo.h"
23#include "llvm/Analysis/StaticDataProfileInfo.h"
24#include "llvm/BinaryFormat/Dwarf.h"
25#include "llvm/CodeGen/DwarfStringPoolEntry.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/StackMaps.h"
28#include "llvm/DebugInfo/CodeView/CodeView.h"
29#include "llvm/IR/InlineAsm.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/ErrorHandling.h"
32#include <cstdint>
33#include <memory>
34#include <utility>
35#include <vector>
36
37namespace llvm {
38
39class AddrLabelMap;
40class AsmPrinterHandler;
41class BasicBlock;
42class BasicBlockSectionsProfileReader;
43class BlockAddress;
44class Constant;
45class ConstantArray;
46class ConstantPtrAuth;
47class DataLayout;
48class DebugHandlerBase;
49class DIE;
50class DIEAbbrev;
51class DwarfDebug;
52class EHStreamer;
53class GCMetadataPrinter;
54class GCStrategy;
55class GlobalAlias;
56class GlobalObject;
57class GlobalValue;
58class GlobalVariable;
59class MachineBasicBlock;
60class MachineBlockFrequencyInfo;
61class MachineBlockHashInfoResult;
62class MachineConstantPoolValue;
63class MachineBranchProbabilityInfo;
64class MachineDominatorTree;
65class MachineFunction;
66class MachineInstr;
67class MachineJumpTableInfo;
68class MachineLoopInfo;
69class MachineModuleInfo;
70class MachineOptimizationRemarkEmitter;
71class MCAsmInfo;
72class MCCFIInstruction;
73class MCContext;
74class MCExpr;
75class MCInst;
76class MCSection;
77class MCStreamer;
78class MCSubtargetInfo;
79class MCSymbol;
80class MCTargetOptions;
81class MDNode;
82class Module;
83class PseudoProbeHandler;
84class raw_ostream;
85class StringRef;
86class TargetLoweringObjectFile;
87class TargetMachine;
88class Twine;
89
90namespace remarks {
91class RemarkStreamer;
92}
93
94/// This class is intended to be used as a driving class for all asm writers.
95class LLVM_ABI AsmPrinter : public MachineFunctionPass {
96public:
97 /// Target machine description.
98 TargetMachine &TM;
99
100 /// Target Asm Printer information.
101 const MCAsmInfo &MAI;
102
103 /// This is the context for the output file that we are streaming. This owns
104 /// all of the global MC-related objects for the generated translation unit.
105 MCContext &OutContext;
106
107 /// This is the MCStreamer object for the file we are generating. This
108 /// contains the transient state for the current translation unit that we are
109 /// generating (such as the current section etc).
110 std::unique_ptr<MCStreamer> OutStreamer;
111
112 /// The current machine function.
113 MachineFunction *MF = nullptr;
114
115 /// This is a pointer to the current MachineModuleInfo.
116 MachineModuleInfo *MMI = nullptr;
117
118 /// The pointer size in bytes for the default address space
119 unsigned PointerSize = 0;
120
121 /// This is a pointer to the current MachineDominatorTree.
122 MachineDominatorTree *MDT = nullptr;
123
124 /// This is a pointer to the current MachineLoopInfo.
125 MachineLoopInfo *MLI = nullptr;
126
127 /// Optimization remark emitter.
128 MachineOptimizationRemarkEmitter *ORE = nullptr;
129
130 /// The symbol for the entry in __patchable_function_entires.
131 MCSymbol *CurrentPatchableFunctionEntrySym = nullptr;
132
133 /// The symbol for the current function. This is recalculated at the beginning
134 /// of each call to runOnMachineFunction().
135 MCSymbol *CurrentFnSym = nullptr;
136
137 /// The symbol for the current function descriptor on AIX. This is created
138 /// at the beginning of each call to SetupMachineFunction().
139 MCSymbol *CurrentFnDescSym = nullptr;
140
141 /// The symbol used to represent the start of the current function for the
142 /// purpose of calculating its size (e.g. using the .size directive). By
143 /// default, this is equal to CurrentFnSym.
144 MCSymbol *CurrentFnSymForSize = nullptr;
145
146 /// Vector of symbols marking the end of the callsites in the current
147 /// function, keyed by their containing basic block.
148 /// The callsite symbols of each block are stored in the order they appear
149 /// in that block.
150 DenseMap<const MachineBasicBlock *, SmallVector<MCSymbol *, 1>>
151 CurrentFnCallsiteEndSymbols;
152
153 /// Provides the profile information for constants.
154 const StaticDataProfileInfo *SDPI = nullptr;
155
156 /// The profile summary information.
157 const ProfileSummaryInfo *PSI = nullptr;
158
159 /// Map a basic block section ID to the begin and end symbols of that section
160 /// which determine the section's range.
161 struct MBBSectionRange {
162 MCSymbol *BeginLabel, *EndLabel;
163 };
164
165 MapVector<MBBSectionID, MBBSectionRange> MBBSectionRanges;
166
167 /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of
168 /// its number of uses by other globals.
169 using GOTEquivUsePair = std::pair<const GlobalVariable *, unsigned>;
170 MapVector<const MCSymbol *, GOTEquivUsePair> GlobalGOTEquivs;
171
172 // Flags representing which CFI section is required for a function/module.
173 enum class CFISection : unsigned {
174 None = 0, ///< Do not emit either .eh_frame or .debug_frame
175 EH = 1, ///< Emit .eh_frame
176 Debug = 2 ///< Emit .debug_frame
177 };
178
179 // Callbacks to get analyses to allow portability between the new and
180 // legacy pass managers.
181 // TODO(boomanaiden154): Remove these and use a more native solution once
182 // we drop support for the legacy PM.
183 std::function<MachineModuleInfo *()> GetMMI;
184 std::function<MachineOptimizationRemarkEmitter *(MachineFunction &)> GetORE;
185 std::function<MachineDominatorTree *(MachineFunction &)> GetMDT;
186 std::function<MachineLoopInfo *(MachineFunction &)> GetMLI;
187 std::function<MachineBranchProbabilityInfo *(MachineFunction &)> GetMBPI;
188 std::function<MachineBlockFrequencyInfo *(MachineFunction &)> GetMBFI;
189 std::function<MachineBlockHashInfoResult *(MachineFunction &)> GetMBHI;
190 /// Returns the basic block sections profile reader if available, nullptr
191 /// otherwise.
192 std::function<BasicBlockSectionsProfileReader *(MachineFunction &)> GetBBSPR;
193 std::function<void(Module &)> BeginGCAssembly;
194 std::function<void(Module &)> FinishGCAssembly;
195 std::function<void(Module &)> EmitStackMaps;
196 std::function<void()> AssertDebugEHFinalized;
197
198private:
199 MCSymbol *CurrentFnEnd = nullptr;
200
201 /// Map a basic block section ID to the exception symbol associated with that
202 /// section. Map entries are assigned and looked up via
203 /// AsmPrinter::getMBBExceptionSym.
204 DenseMap<MBBSectionID, MCSymbol *> MBBSectionExceptionSyms;
205
206 // The symbol used to represent the start of the current BB section of the
207 // function. This is used to calculate the size of the BB section.
208 MCSymbol *CurrentSectionBeginSym = nullptr;
209
210 /// This map keeps track of which symbol is being used for the specified basic
211 /// block's address of label.
212 std::unique_ptr<AddrLabelMap> AddrLabelSymbols;
213
214 /// The garbage collection metadata printer table.
215 DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>> GCMetadataPrinters;
216
217 /// Emit comments in assembly output if this is true.
218 bool VerboseAsm;
219
220 /// Store symbols and type identifiers used to create callgraph section
221 /// entries related to a function.
222 struct FunctionCallGraphInfo {
223 /// Numeric type identifier used in callgraph section for indirect calls
224 /// and targets.
225 using CGTypeId = uint64_t;
226
227 /// Unique target type IDs.
228 SmallSetVector<CGTypeId, 4> IndirectCalleeTypeIDs;
229 /// Unique direct callees.
230 SmallSetVector<MCSymbol *, 4> DirectCallees;
231 };
232
233 enum CallGraphSectionFormatVersion : uint8_t {
234 V_0 = 0,
235 };
236
237 /// Output stream for the stack usage file (i.e., .su file).
238 std::unique_ptr<raw_fd_ostream> StackUsageStream;
239
240 /// List of symbols to be inserted into PC sections.
241 DenseMap<const MDNode *, SmallVector<const MCSymbol *>> PCSectionsSymbols;
242
243 static char ID;
244
245protected:
246 MCSymbol *CurrentFnBegin = nullptr;
247
248 /// For dso_local functions, the current $local alias for the function.
249 MCSymbol *CurrentFnBeginLocal = nullptr;
250
251 /// A handle to the EH info emitter (if present).
252 SmallVector<std::unique_ptr<EHStreamer>, 1> EHHandlers;
253
254 // A vector of all Debuginfo emitters we should use. Protected so that
255 // targets can add their own. This vector maintains ownership of the
256 // emitters.
257 SmallVector<std::unique_ptr<AsmPrinterHandler>, 2> Handlers;
258 size_t NumUserHandlers = 0;
259
260 StackMaps SM;
261
262private:
263 /// If generated on the fly this own the instance.
264 std::unique_ptr<MachineDominatorTree> OwnedMDT;
265
266 /// If generated on the fly this own the instance.
267 std::unique_ptr<MachineLoopInfo> OwnedMLI;
268
269 /// If the target supports dwarf debug info, this pointer is non-null.
270 DwarfDebug *DD = nullptr;
271
272 /// A handler that supports pseudo probe emission with embedded inline
273 /// context.
274 std::unique_ptr<PseudoProbeHandler> PP;
275
276 /// CFISection type the module needs i.e. either .eh_frame or .debug_frame.
277 CFISection ModuleCFISection = CFISection::None;
278
279 /// True if the module contains split-stack functions. This is used to
280 /// emit .note.GNU-split-stack section as required by the linker for
281 /// special handling split-stack function calling no-split-stack function.
282 bool HasSplitStack = false;
283
284 /// True if the module contains no-split-stack functions. This is used to emit
285 /// .note.GNU-no-split-stack section when it also contains functions without a
286 /// split stack prologue.
287 bool HasNoSplitStack = false;
288
289 /// True if debugging information is available in this module.
290 bool DbgInfoAvailable = false;
291
292protected:
293 AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer,
294 char &ID = AsmPrinter::ID);
295
296 /// Create the DwarfDebug handler. Targets can override this to provide
297 /// custom debug information handling.
298 virtual DwarfDebug *createDwarfDebug();
299
300public:
301 ~AsmPrinter() override;
302
303 DwarfDebug *getDwarfDebug() { return DD; }
304 DwarfDebug *getDwarfDebug() const { return DD; }
305
306 uint16_t getDwarfVersion() const;
307 void setDwarfVersion(uint16_t Version);
308
309 bool isDwarf64() const;
310
311 /// Returns 4 for DWARF32 and 8 for DWARF64.
312 unsigned int getDwarfOffsetByteSize() const;
313
314 /// Returns 4 for DWARF32 and 12 for DWARF64.
315 unsigned int getUnitLengthFieldByteSize() const;
316
317 /// Returns information about the byte size of DW_FORM values.
318 dwarf::FormParams getDwarfFormParams() const;
319
320 bool isPositionIndependent() const;
321
322 /// Return true if assembly output should contain comments.
323 bool isVerbose() const { return VerboseAsm; }
324
325 /// Return a unique ID for the current function.
326 unsigned getFunctionNumber() const;
327
328 /// Return symbol for the function pseudo stack if the stack frame is not a
329 /// register based.
330 virtual const MCSymbol *getFunctionFrameSymbol() const { return nullptr; }
331
332 MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
333 MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
334
335 // Return the exception symbol associated with the MBB section containing a
336 // given basic block.
337 MCSymbol *getMBBExceptionSym(const MachineBasicBlock &MBB);
338
339 /// Return the symbol to be used for the specified basic block when its
340 /// address is taken. This cannot be its normal LBB label because the block
341 /// may be accessed outside its containing function.
342 MCSymbol *getAddrLabelSymbol(const BasicBlock *BB) {
343 return getAddrLabelSymbolToEmit(BB).front();
344 }
345
346 /// Return the symbol to be used for the specified basic block when its
347 /// address is taken. If other blocks were RAUW'd to this one, we may have
348 /// to emit them as well, return the whole set.
349 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(const BasicBlock *BB);
350
351 /// Creates a new symbol to be used for the end of a callsite at the specified
352 /// basic block.
353 MCSymbol *createCallsiteEndSymbol(const MachineBasicBlock &MBB);
354
355 /// If the specified function has had any references to address-taken blocks
356 /// generated, but the block got deleted, return the symbol now so we can
357 /// emit it. This prevents emitting a reference to a symbol that has no
358 /// definition.
359 void takeDeletedSymbolsForFunction(const Function *F,
360 std::vector<MCSymbol *> &Result);
361
362 /// Return information about object file lowering.
363 const TargetLoweringObjectFile &getObjFileLowering() const;
364
365 /// Return information about data layout.
366 const DataLayout &getDataLayout() const;
367
368 /// Return the pointer size in bytes from the target triple.
369 unsigned getPointerSize() const { return PointerSize; }
370
371 /// Return information about subtarget.
372 const MCSubtargetInfo &getSubtargetInfo() const;
373
374 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
375
376 /// Return the current section we are emitting to.
377 const MCSection *getCurrentSection() const;
378
379 void getNameWithPrefix(SmallVectorImpl<char> &Name,
380 const GlobalValue *GV) const;
381
382 MCSymbol *getSymbol(const GlobalValue *GV) const;
383
384 /// Similar to getSymbol() but preferred for references. On ELF, this uses a
385 /// local symbol if a reference to GV is guaranteed to be resolved to the
386 /// definition in the same module.
387 MCSymbol *getSymbolPreferLocal(const GlobalValue &GV) const;
388
389 bool doesDwarfUseRelocationsAcrossSections() const {
390 return DwarfUsesRelocationsAcrossSections;
391 }
392
393 void setDwarfUsesRelocationsAcrossSections(bool Enable) {
394 DwarfUsesRelocationsAcrossSections = Enable;
395 }
396
397 /// Returns a section suffix (hot or unlikely) for the constant if profiles
398 /// are available. Returns empty string otherwise.
399 StringRef getConstantSectionSuffix(const Constant *C) const;
400
401 /// If MI is an indirect call, add expected type IDs to indirect type ids
402 /// list. If MI is a direct call add the callee symbol to direct callsites
403 /// list of FuncCGInfo.
404 void handleCallsiteForCallgraph(
405 FunctionCallGraphInfo &FuncCGInfo,
406 const MachineFunction::CallSiteInfoMap &CallSitesInfoMap,
407 const MachineInstr &MI);
408
409 //===------------------------------------------------------------------===//
410 // XRay instrumentation implementation.
411 //===------------------------------------------------------------------===//
412public:
413 // This describes the kind of sled we're storing in the XRay table.
414 enum class SledKind : uint8_t {
415 FUNCTION_ENTER = 0,
416 FUNCTION_EXIT = 1,
417 TAIL_CALL = 2,
418 LOG_ARGS_ENTER = 3,
419 CUSTOM_EVENT = 4,
420 TYPED_EVENT = 5,
421 };
422
423 // The table will contain these structs that point to the sled, the function
424 // containing the sled, and what kind of sled (and whether they should always
425 // be instrumented). We also use a version identifier that the runtime can use
426 // to decide what to do with the sled, depending on the version of the sled.
427 struct XRayFunctionEntry {
428 const MCSymbol *Sled;
429 const MCSymbol *Function;
430 SledKind Kind;
431 bool AlwaysInstrument;
432 const class Function *Fn;
433 uint8_t Version;
434
435 LLVM_ABI void emit(int, MCStreamer *) const;
436 };
437
438 // All the sleds to be emitted.
439 SmallVector<XRayFunctionEntry, 4> Sleds;
440
441 // Helper function to record a given XRay sled.
442 void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind,
443 uint8_t Version = 0);
444
445 /// Emit a table with all XRay instrumentation points.
446 void emitXRayTable();
447
448 void emitPatchableFunctionEntries();
449
450 //===------------------------------------------------------------------===//
451 // MachineFunctionPass Implementation.
452 //===------------------------------------------------------------------===//
453
454 /// Record analysis usage.
455 void getAnalysisUsage(AnalysisUsage &AU) const override;
456
457 /// Set up the AsmPrinter when we are working on a new module. If your pass
458 /// overrides this, it must make sure to explicitly call this implementation.
459 bool doInitialization(Module &M) override;
460
461 /// Shut down the asmprinter. If you override this in your pass, you must make
462 /// sure to call it explicitly.
463 bool doFinalization(Module &M) override;
464
465 /// Emit the specified function out to the OutStreamer.
466 bool runOnMachineFunction(MachineFunction &MF) override {
467 SetupMachineFunction(MF);
468 emitFunctionBody();
469 return false;
470 }
471
472 //===------------------------------------------------------------------===//
473 // Coarse grained IR lowering routines.
474 //===------------------------------------------------------------------===//
475
476 /// This should be called when a new MachineFunction is being processed from
477 /// runOnMachineFunction.
478 virtual void SetupMachineFunction(MachineFunction &MF);
479
480 /// This method emits the body and trailer for a function.
481 void emitFunctionBody();
482
483 void emitCFIInstruction(const MachineInstr &MI);
484
485 void emitFrameAlloc(const MachineInstr &MI);
486
487 void emitStackSizeSection(const MachineFunction &MF);
488
489 void emitStackUsage(const MachineFunction &MF);
490
491 void emitBBAddrMapSection(const MachineFunction &MF);
492
493 void emitKCFITrapEntry(const MachineFunction &MF, const MCSymbol *Symbol);
494 virtual void emitKCFITypeId(const MachineFunction &MF);
495
496 void emitCallGraphSection(const MachineFunction &MF,
497 FunctionCallGraphInfo &FuncCGInfo);
498
499 /// Helper to emit a symbol for the prefetch target associated with the given
500 /// BBID and callsite index. The symbol is emitted as a label and its linkage
501 /// is set based on the function's linkage.
502 void emitPrefetchTargetSymbol(const UniqueBBID &BBID, unsigned CallsiteIndex);
503
504 /// Emit prefetch targets that were not mapped to any basic block. These
505 /// targets are emitted at the beginning of the function body.
506 void emitDanglingPrefetchTargets();
507
508 void emitPseudoProbe(const MachineInstr &MI);
509
510 void emitRemarksSection(remarks::RemarkStreamer &RS);
511
512 /// Emits a label as reference for PC sections.
513 void emitPCSectionsLabel(const MachineFunction &MF, const MDNode &MD);
514
515 /// Emits the PC sections collected from instructions.
516 void emitPCSections(const MachineFunction &MF);
517
518 /// Get the CFISection type for a function.
519 CFISection getFunctionCFISectionType(const Function &F) const;
520
521 /// Get the CFISection type for a function.
522 CFISection getFunctionCFISectionType(const MachineFunction &MF) const;
523
524 /// Get the CFISection type for the module.
525 CFISection getModuleCFISectionType() const { return ModuleCFISection; }
526
527 /// Returns true if valid debug info is present.
528 bool hasDebugInfo() const { return DbgInfoAvailable; }
529
530 bool needsSEHMoves();
531
532 /// Since emitting CFI unwind information is entangled with supporting the
533 /// exceptions, this returns true for platforms which use CFI unwind
534 /// information for other purposes (debugging, sanitizers, ...) when
535 /// `MCAsmInfo::ExceptionsType == ExceptionHandling::None`.
536 bool usesCFIWithoutEH() const;
537
538 /// Print to the current output stream assembly representations of the
539 /// constants in the constant pool MCP. This is used to print out constants
540 /// which have been "spilled to memory" by the code generator.
541 virtual void emitConstantPool();
542
543 /// Print assembly representations of the jump tables used by the current
544 /// function to the current output stream.
545 virtual void emitJumpTableInfo();
546
547 /// Emit the specified global variable to the .s file.
548 virtual void emitGlobalVariable(const GlobalVariable *GV);
549
550 /// Emit the specified global variable to the .s file, with an explicit
551 /// alignment granule applied to both address and size.
552 virtual void emitGlobalVariable(const GlobalVariable *GV,
553 MaybeAlign AlignmentGranule);
554
555 /// Check to see if the specified global is a special global used by LLVM. If
556 /// so, emit it and return true, otherwise do nothing and return false.
557 bool emitSpecialLLVMGlobal(const GlobalVariable *GV);
558
559 /// `llvm.global_ctors` and `llvm.global_dtors` are arrays of Structor
560 /// structs.
561 ///
562 /// Priority - init priority
563 /// Func - global initialization or global clean-up function
564 /// ComdatKey - associated data
565 struct Structor {
566 int Priority = 0;
567 Constant *Func = nullptr;
568 GlobalValue *ComdatKey = nullptr;
569
570 Structor() = default;
571 };
572
573 /// This method gathers an array of Structors and then sorts them out by
574 /// Priority.
575 /// @param List The initializer of `llvm.global_ctors` or `llvm.global_dtors`
576 /// array.
577 /// @param[out] Structors Sorted Structor structs by Priority.
578 void preprocessXXStructorList(const DataLayout &DL, const Constant *List,
579 SmallVector<Structor, 8> &Structors);
580
581 /// This method emits `llvm.global_ctors` or `llvm.global_dtors` list.
582 virtual void emitXXStructorList(const DataLayout &DL, const Constant *List,
583 bool IsCtor);
584
585 /// Emit an alignment directive to the specified power of two boundary. If a
586 /// global value is specified, and if that global has an explicit alignment
587 /// requested, it will override the alignment request if required for
588 /// correctness. Returns the effective alignment that was emitted (which may
589 /// exceed \p Alignment when \p GV has a stricter explicit alignment).
590 Align emitAlignment(Align Alignment, const GlobalObject *GV = nullptr,
591 unsigned MaxBytesToEmit = 0) const;
592
593 /// Lower the specified LLVM Constant to an MCExpr.
594 /// When BaseCV is present, we are lowering the element at BaseCV plus Offset.
595 virtual const MCExpr *lowerConstant(const Constant *CV,
596 const Constant *BaseCV = nullptr,
597 uint64_t Offset = 0);
598
599 /// Print a general LLVM constant to the .s file.
600 /// On AIX, when an alias refers to a sub-element of a global variable, the
601 /// label of that alias needs to be emitted before the corresponding element.
602 using AliasMapTy = DenseMap<uint64_t, SmallVector<const GlobalAlias *, 1>>;
603 void emitGlobalConstant(const DataLayout &DL, const Constant *CV,
604 AliasMapTy *AliasList = nullptr);
605
606 /// Unnamed constant global variables solely contaning a pointer to
607 /// another globals variable act like a global variable "proxy", or GOT
608 /// equivalents, i.e., it's only used to hold the address of the latter. One
609 /// optimization is to replace accesses to these proxies by using the GOT
610 /// entry for the final global instead. Hence, we select GOT equivalent
611 /// candidates among all the module global variables, avoid emitting them
612 /// unnecessarily and finally replace references to them by pc relative
613 /// accesses to GOT entries.
614 void computeGlobalGOTEquivs(Module &M);
615
616 /// Constant expressions using GOT equivalent globals may not be
617 /// eligible for PC relative GOT entry conversion, in such cases we need to
618 /// emit the proxies we previously omitted in EmitGlobalVariable.
619 void emitGlobalGOTEquivs();
620
621 //===------------------------------------------------------------------===//
622 // Overridable Hooks
623 //===------------------------------------------------------------------===//
624
625 void addAsmPrinterHandler(std::unique_ptr<AsmPrinterHandler> Handler);
626
627 // Targets can, or in the case of EmitInstruction, must implement these to
628 // customize output.
629
630 /// This virtual method can be overridden by targets that want to emit
631 /// something at the start of their file.
632 virtual void emitStartOfAsmFile(Module &) {}
633
634 /// This virtual method can be overridden by targets that want to emit
635 /// something at the end of their file.
636 virtual void emitEndOfAsmFile(Module &) {}
637
638 /// Targets can override this to emit stuff before the first basic block in
639 /// the function.
640 virtual void emitFunctionBodyStart() {}
641
642 /// Targets can override this to emit stuff after the last basic block in the
643 /// function.
644 virtual void emitFunctionBodyEnd() {}
645
646 /// Targets can override this to emit stuff at the start of a basic block.
647 /// By default, this method prints the label for the specified
648 /// MachineBasicBlock, an alignment (if present) and a comment describing it
649 /// if appropriate.
650 virtual void emitBasicBlockStart(const MachineBasicBlock &MBB);
651
652 /// Targets can override this to emit stuff at the end of a basic block.
653 virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB);
654
655 /// Targets should implement this to emit instructions.
656 virtual void emitInstruction(const MachineInstr *) {
657 llvm_unreachable("EmitInstruction not implemented");
658 }
659
660 /// Return the symbol for the specified constant pool entry.
661 virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
662
663 virtual void emitFunctionEntryLabel();
664
665 virtual void emitFunctionDescriptor() {
666 llvm_unreachable("Function descriptor is target-specific.");
667 }
668
669 virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
670
671 /// Targets can override this to change how global constants that are part of
672 /// a C++ static/global constructor list are emitted.
673 virtual void emitXXStructor(const DataLayout &DL, const Constant *CV) {
674 emitGlobalConstant(DL, CV);
675 }
676
677 virtual const MCExpr *lowerConstantPtrAuth(const ConstantPtrAuth &CPA) {
678 reportFatalUsageError(reason: "ptrauth constant lowering not implemented");
679 }
680
681 /// Lower the specified BlockAddress to an MCExpr.
682 virtual const MCExpr *lowerBlockAddressConstant(const BlockAddress &BA);
683
684 /// Return true if the basic block has exactly one predecessor and the control
685 /// transfer mechanism between the predecessor and this block is a
686 /// fall-through.
687 virtual bool
688 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
689
690 /// Targets can override this to customize the output of IMPLICIT_DEF
691 /// instructions in verbose mode.
692 virtual void emitImplicitDef(const MachineInstr *MI) const;
693
694 /// getSubtargetInfo() cannot be used where this is needed because we don't
695 /// have a MachineFunction when we're lowering a GlobalIFunc, and
696 /// getSubtargetInfo requires one. Override the implementation in targets
697 /// that support the Mach-O IFunc lowering.
698 virtual const MCSubtargetInfo *getIFuncMCSubtargetInfo() const {
699 return nullptr;
700 }
701
702 virtual void emitMachOIFuncStubBody(Module &M, const GlobalIFunc &GI,
703 MCSymbol *LazyPointer) {
704 llvm_unreachable(
705 "Mach-O IFunc lowering is not yet supported on this target");
706 }
707
708 virtual void emitMachOIFuncStubHelperBody(Module &M, const GlobalIFunc &GI,
709 MCSymbol *LazyPointer) {
710 llvm_unreachable(
711 "Mach-O IFunc lowering is not yet supported on this target");
712 }
713
714 /// Emit N NOP instructions.
715 void emitNops(unsigned N);
716
717 //===------------------------------------------------------------------===//
718 // Symbol Lowering Routines.
719 //===------------------------------------------------------------------===//
720
721 MCSymbol *createTempSymbol(const Twine &Name) const;
722
723 /// Return the MCSymbol for a private symbol with global value name as its
724 /// base, with the specified suffix.
725 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
726 StringRef Suffix) const;
727
728 /// Return the MCSymbol for the specified ExternalSymbol.
729 MCSymbol *GetExternalSymbolSymbol(const Twine &Sym) const;
730
731 /// Return the symbol for the specified jump table entry.
732 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
733
734 /// Return the symbol for the specified jump table .set
735 /// FIXME: privatize to AsmPrinter.
736 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
737
738 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
739 /// basic block.
740 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
741 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
742
743 //===------------------------------------------------------------------===//
744 // Emission Helper Routines.
745 //===------------------------------------------------------------------===//
746
747 /// This is just convenient handler for printing offsets.
748 void printOffset(int64_t Offset, raw_ostream &OS) const;
749
750 /// Emit a byte directive and value.
751 void emitInt8(int Value) const;
752
753 /// Emit a short directive and value.
754 void emitInt16(int Value) const;
755
756 /// Emit a long directive and value.
757 void emitInt32(int Value) const;
758
759 /// Emit a long long directive and value.
760 void emitInt64(uint64_t Value) const;
761
762 /// Emit the specified signed leb128 value.
763 void emitSLEB128(int64_t Value, const char *Desc = nullptr) const;
764
765 /// Emit the specified unsigned leb128 value.
766 void emitULEB128(uint64_t Value, const char *Desc = nullptr,
767 unsigned PadTo = 0) const;
768
769 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
770 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
771 /// .set if it is available.
772 void emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
773 unsigned Size) const;
774
775 /// Emit something like ".uleb128 Hi-Lo".
776 void emitLabelDifferenceAsULEB128(const MCSymbol *Hi,
777 const MCSymbol *Lo) const;
778
779 /// Emit something like ".long Label+Offset" where the size in bytes of the
780 /// directive is specified by Size and Label specifies the label. This
781 /// implicitly uses .set if it is available.
782 void emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
783 unsigned Size, bool IsSectionRelative = false) const;
784
785 /// Emit something like ".long Label" where the size in bytes of the directive
786 /// is specified by Size and Label specifies the label.
787 void emitLabelReference(const MCSymbol *Label, unsigned Size,
788 bool IsSectionRelative = false) const {
789 emitLabelPlusOffset(Label, Offset: 0, Size, IsSectionRelative);
790 }
791
792 //===------------------------------------------------------------------===//
793 // Dwarf Emission Helper Routines
794 //===------------------------------------------------------------------===//
795
796 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
797 /// assembly output is enabled, we output comments describing the encoding.
798 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
799 void emitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
800
801 /// Return the size of the encoding in bytes.
802 unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
803
804 /// Emit reference to a ttype global with a specified encoding.
805 virtual void emitTTypeReference(const GlobalValue *GV, unsigned Encoding);
806
807 /// Emit a reference to a symbol for use in dwarf. Different object formats
808 /// represent this in different ways. Some use a relocation others encode
809 /// the label offset in its section.
810 void emitDwarfSymbolReference(const MCSymbol *Label,
811 bool ForceOffset = false) const;
812
813 /// Emit the 4- or 8-byte offset of a string from the start of its section.
814 ///
815 /// When possible, emit a DwarfStringPool section offset without any
816 /// relocations, and without using the symbol. Otherwise, defers to \a
817 /// emitDwarfSymbolReference().
818 ///
819 /// The length of the emitted value depends on the DWARF format.
820 void emitDwarfStringOffset(DwarfStringPoolEntry S) const;
821
822 /// Emit the 4-or 8-byte offset of a string from the start of its section.
823 void emitDwarfStringOffset(DwarfStringPoolEntryRef S) const {
824 emitDwarfStringOffset(S: S.getEntry());
825 }
826
827 /// Emit something like ".long Label + Offset" or ".quad Label + Offset"
828 /// depending on the DWARF format.
829 void emitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const;
830
831 /// Emit 32- or 64-bit value depending on the DWARF format.
832 void emitDwarfLengthOrOffset(uint64_t Value) const;
833
834 /// Emit a unit length field. The actual format, DWARF32 or DWARF64, is chosen
835 /// according to the settings.
836 void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) const;
837
838 /// Emit a unit length field. The actual format, DWARF32 or DWARF64, is chosen
839 /// according to the settings.
840 /// Return the end symbol generated inside, the caller needs to emit it.
841 MCSymbol *emitDwarfUnitLength(const Twine &Prefix,
842 const Twine &Comment) const;
843
844 /// Emit reference to a call site with a specified encoding
845 void emitCallSiteOffset(const MCSymbol *Hi, const MCSymbol *Lo,
846 unsigned Encoding) const;
847 /// Emit an integer value corresponding to the call site encoding
848 void emitCallSiteValue(uint64_t Value, unsigned Encoding) const;
849
850 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
851 virtual unsigned getISAEncoding() { return 0; }
852
853 /// Emit the directive and value for debug thread local expression
854 ///
855 /// \p Value - The value to emit.
856 /// \p Size - The size of the integer (in bytes) to emit.
857 virtual void emitDebugValue(const MCExpr *Value, unsigned Size) const;
858
859 //===------------------------------------------------------------------===//
860 // Dwarf Lowering Routines
861 //===------------------------------------------------------------------===//
862
863 /// Emit frame instruction to describe the layout of the frame.
864 void emitCFIInstruction(const MCCFIInstruction &Inst) const;
865
866 /// Emit Dwarf abbreviation table.
867 template <typename T> void emitDwarfAbbrevs(const T &Abbrevs) const {
868 // For each abbreviation.
869 for (const auto &Abbrev : Abbrevs)
870 emitDwarfAbbrev(Abbrev: *Abbrev);
871
872 // Mark end of abbreviations.
873 emitULEB128(Value: 0, Desc: "EOM(3)");
874 }
875
876 void emitDwarfAbbrev(const DIEAbbrev &Abbrev) const;
877
878 /// Recursively emit Dwarf DIE tree.
879 void emitDwarfDIE(const DIE &Die) const;
880
881 //===------------------------------------------------------------------===//
882 // CodeView Helper Routines
883 //===------------------------------------------------------------------===//
884
885 /// Gets information required to create a CodeView debug symbol for a jump
886 /// table.
887 /// Return value is <Base Address, Base Offset, Branch Address, Entry Size>
888 virtual std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
889 codeview::JumpTableEntrySize>
890 getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr,
891 const MCSymbol *BranchLabel) const;
892
893 //===------------------------------------------------------------------===//
894 // COFF Helper Routines
895 //===------------------------------------------------------------------===//
896
897 /// Emits symbols and data to allow functions marked with the
898 /// loader-replaceable attribute to be replaceable.
899 void emitCOFFReplaceableFunctionData(Module &M);
900
901 /// Emits the @feat.00 symbol indicating the features enabled in this module.
902 void emitCOFFFeatureSymbol(Module &M);
903
904 //===------------------------------------------------------------------===//
905 // Inline Asm Support
906 //===------------------------------------------------------------------===//
907
908 // These are hooks that targets can override to implement inline asm
909 // support. These should probably be moved out of AsmPrinter someday.
910
911 /// Print information related to the specified machine instr that is
912 /// independent of the operand, and may be independent of the instr itself.
913 /// This can be useful for portably encoding the comment character or other
914 /// bits of target-specific knowledge into the asmstrings. The syntax used is
915 /// ${:comment}. Targets can override this to add support for their own
916 /// strange codes.
917 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
918 StringRef Code) const;
919
920 /// Print the MachineOperand as a symbol. Targets with complex handling of
921 /// symbol references should override the base implementation.
922 virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS);
923
924 /// Print the specified operand of MI, an INLINEASM instruction, using the
925 /// specified assembler variant. Targets should override this to format as
926 /// appropriate. This method can return true if the operand is erroneous.
927 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
928 const char *ExtraCode, raw_ostream &OS);
929
930 /// Print the specified operand of MI, an INLINEASM instruction, using the
931 /// specified assembler variant as an address. Targets should override this to
932 /// format as appropriate. This method can return true if the operand is
933 /// erroneous.
934 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
935 const char *ExtraCode, raw_ostream &OS);
936
937 /// Let the target do anything it needs to do before emitting inlineasm.
938 /// \p StartInfo - the subtarget info before parsing inline asm
939 virtual void emitInlineAsmStart() const;
940
941 /// Let the target do anything it needs to do after emitting inlineasm.
942 /// This callback can be used restore the original mode in case the
943 /// inlineasm contains directives to switch modes.
944 /// \p StartInfo - the original subtarget info before inline asm
945 /// \p EndInfo - the final subtarget info after parsing the inline asm,
946 /// or NULL if the value is unknown.
947 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
948 const MCSubtargetInfo *EndInfo,
949 const MachineInstr *MI);
950
951 /// Emit necessary directives to allow use of instructions that are permitted
952 /// by target features enabled by STI, but are not permitted by target
953 /// features enabled by the global subtarget (TM.getSubTargetInfo()).
954 /// Returns whether anything was emitted.
955 virtual bool emitTargetFeaturePush(const MCSubtargetInfo &STI) {
956 return false;
957 }
958
959 /// Emit necessary directives to restore target feature state.
960 /// The \p DidPush argument is the result of the prior emitTargetFeaturePush()
961 /// call.
962 virtual void emitTargetFeaturePop(const MCSubtargetInfo &STI, bool DidPush) {}
963
964 /// This emits visibility information about symbol, if this is supported by
965 /// the target.
966 void emitVisibility(MCSymbol *Sym, unsigned Visibility,
967 bool IsDefinition = true) const;
968
969 /// This emits linkage information about \p GVSym based on \p GV, if this is
970 /// supported by the target.
971 virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
972
973 /// Return the alignment for the specified \p GV.
974 static Align getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
975 Align InAlign = Align(1));
976
977private:
978 /// Private state for PrintSpecial()
979 // Assign a unique ID to this machine instruction.
980 mutable const MachineInstr *LastMI = nullptr;
981 mutable unsigned LastFn = 0;
982 mutable unsigned Counter = ~0U;
983
984 bool DwarfUsesRelocationsAcrossSections = false;
985
986 /// This method emits the header for the current function.
987 virtual void emitFunctionHeader();
988
989 /// This method emits a comment next to header for the current function.
990 virtual void emitFunctionHeaderComment();
991
992 /// This method emits prefix-like data before the current function.
993 void emitFunctionPrefix(ArrayRef<const Constant *> Prefix);
994
995 /// Emit a blob of inline asm to the output streamer.
996 virtual void
997 emitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
998 const MCTargetOptions &MCOptions,
999 const MDNode *LocMDNode = nullptr,
1000 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT,
1001 const MachineInstr *MI = nullptr);
1002
1003 /// This method formats and emits the specified machine instruction that is an
1004 /// inline asm.
1005 void emitInlineAsm(const MachineInstr *MI);
1006
1007 /// Add inline assembly info to the diagnostics machinery, so we can
1008 /// emit file and position info. Returns SrcMgr memory buffer position.
1009 unsigned addInlineAsmDiagBuffer(StringRef AsmStr,
1010 const MDNode *LocMDNode) const;
1011
1012 //===------------------------------------------------------------------===//
1013 // Internal Implementation Details
1014 //===------------------------------------------------------------------===//
1015
1016 virtual void emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
1017 ArrayRef<unsigned> JumpTableIndices);
1018
1019 void emitJumpTableSizesSection(const MachineJumpTableInfo &MJTI,
1020 const Function &F) const;
1021
1022 void emitLLVMUsedList(const ConstantArray *InitList);
1023 /// Emit llvm.ident metadata in an '.ident' directive.
1024 void emitModuleIdents(Module &M);
1025 /// Emit bytes for llvm.commandline metadata.
1026 virtual void emitModuleCommandLines(Module &M);
1027
1028 GCMetadataPrinter *getOrCreateGCPrinter(GCStrategy &S);
1029 virtual void emitGlobalIFunc(Module &M, const GlobalIFunc &GI);
1030
1031 /// This method decides whether the specified basic block requires a label.
1032 bool shouldEmitLabelForBasicBlock(const MachineBasicBlock &MBB) const;
1033
1034protected:
1035 virtual void emitJumpTableEntry(const MachineJumpTableInfo &MJTI,
1036 const MachineBasicBlock *MBB,
1037 unsigned uid) const;
1038 virtual void emitGlobalAlias(const Module &M, const GlobalAlias &GA);
1039 virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const {
1040 return false;
1041 }
1042
1043 /// Returns a optional minimum alignment that applies to both the address and
1044 /// the allocation size of the global. This is used for systems like CHERI and
1045 /// MTE that impose a minimum alignment, and require globals to be padded to
1046 /// that alignment.
1047 virtual MaybeAlign
1048 getRequiredGlobalAlignmentGranule(const GlobalVariable &GV) {
1049 return std::nullopt;
1050 };
1051};
1052
1053LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM,
1054 AsmPrinter &AsmPrinter);
1055
1056LLVM_ABI void
1057setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM,
1058 MachineFunction &MF, AsmPrinter &AsmPrinter);
1059
1060} // end namespace llvm
1061
1062#endif // LLVM_CODEGEN_ASMPRINTER_H
1063