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