1 //===- MCStreamer.h - High-level Streaming Machine Code Output --*- 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 declares the MCStreamer class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_MC_MCSTREAMER_H 14 #define LLVM_MC_MCSTREAMER_H 15 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/Optional.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/MC/MCDirectives.h" 22 #include "llvm/MC/MCLinkerOptimizationHint.h" 23 #include "llvm/MC/MCSymbol.h" 24 #include "llvm/MC/MCWinEH.h" 25 #include "llvm/Support/Error.h" 26 #include "llvm/Support/MD5.h" 27 #include "llvm/Support/SMLoc.h" 28 #include "llvm/Support/TargetParser.h" 29 #include "llvm/Support/VersionTuple.h" 30 #include <cassert> 31 #include <cstdint> 32 #include <memory> 33 #include <string> 34 #include <utility> 35 #include <vector> 36 37 namespace llvm { 38 39 class AssemblerConstantPools; 40 class formatted_raw_ostream; 41 class MCAsmBackend; 42 class MCCodeEmitter; 43 struct MCCodePaddingContext; 44 class MCContext; 45 struct MCDwarfFrameInfo; 46 class MCExpr; 47 class MCInst; 48 class MCInstPrinter; 49 class MCRegister; 50 class MCSection; 51 class MCStreamer; 52 class MCSymbolRefExpr; 53 class MCSubtargetInfo; 54 class raw_ostream; 55 class Twine; 56 57 namespace codeview { 58 struct DefRangeRegisterRelHeader; 59 struct DefRangeSubfieldRegisterHeader; 60 struct DefRangeRegisterHeader; 61 struct DefRangeFramePointerRelHeader; 62 } 63 64 using MCSectionSubPair = std::pair<MCSection *, const MCExpr *>; 65 66 /// Target specific streamer interface. This is used so that targets can 67 /// implement support for target specific assembly directives. 68 /// 69 /// If target foo wants to use this, it should implement 3 classes: 70 /// * FooTargetStreamer : public MCTargetStreamer 71 /// * FooTargetAsmStreamer : public FooTargetStreamer 72 /// * FooTargetELFStreamer : public FooTargetStreamer 73 /// 74 /// FooTargetStreamer should have a pure virtual method for each directive. For 75 /// example, for a ".bar symbol_name" directive, it should have 76 /// virtual emitBar(const MCSymbol &Symbol) = 0; 77 /// 78 /// The FooTargetAsmStreamer and FooTargetELFStreamer classes implement the 79 /// method. The assembly streamer just prints ".bar symbol_name". The object 80 /// streamer does whatever is needed to implement .bar in the object file. 81 /// 82 /// In the assembly printer and parser the target streamer can be used by 83 /// calling getTargetStreamer and casting it to FooTargetStreamer: 84 /// 85 /// MCTargetStreamer &TS = OutStreamer.getTargetStreamer(); 86 /// FooTargetStreamer &ATS = static_cast<FooTargetStreamer &>(TS); 87 /// 88 /// The base classes FooTargetAsmStreamer and FooTargetELFStreamer should 89 /// *never* be treated differently. Callers should always talk to a 90 /// FooTargetStreamer. 91 class MCTargetStreamer { 92 protected: 93 MCStreamer &Streamer; 94 95 public: 96 MCTargetStreamer(MCStreamer &S); 97 virtual ~MCTargetStreamer(); 98 getStreamer()99 MCStreamer &getStreamer() { return Streamer; } 100 101 // Allow a target to add behavior to the EmitLabel of MCStreamer. 102 virtual void emitLabel(MCSymbol *Symbol); 103 // Allow a target to add behavior to the emitAssignment of MCStreamer. 104 virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value); 105 106 virtual void prettyPrintAsm(MCInstPrinter &InstPrinter, uint64_t Address, 107 const MCInst &Inst, const MCSubtargetInfo &STI, 108 raw_ostream &OS); 109 110 virtual void emitDwarfFileDirective(StringRef Directive); 111 112 /// Update streamer for a new active section. 113 /// 114 /// This is called by PopSection and SwitchSection, if the current 115 /// section changes. 116 virtual void changeSection(const MCSection *CurSection, MCSection *Section, 117 const MCExpr *SubSection, raw_ostream &OS); 118 119 virtual void emitValue(const MCExpr *Value); 120 121 /// Emit the bytes in \p Data into the output. 122 /// 123 /// This is used to emit bytes in \p Data as sequence of .byte directives. 124 virtual void emitRawBytes(StringRef Data); 125 126 virtual void finish(); 127 }; 128 129 // FIXME: declared here because it is used from 130 // lib/CodeGen/AsmPrinter/ARMException.cpp. 131 class ARMTargetStreamer : public MCTargetStreamer { 132 public: 133 ARMTargetStreamer(MCStreamer &S); 134 ~ARMTargetStreamer() override; 135 136 virtual void emitFnStart(); 137 virtual void emitFnEnd(); 138 virtual void emitCantUnwind(); 139 virtual void emitPersonality(const MCSymbol *Personality); 140 virtual void emitPersonalityIndex(unsigned Index); 141 virtual void emitHandlerData(); 142 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, 143 int64_t Offset = 0); 144 virtual void emitMovSP(unsigned Reg, int64_t Offset = 0); 145 virtual void emitPad(int64_t Offset); 146 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList, 147 bool isVector); 148 virtual void emitUnwindRaw(int64_t StackOffset, 149 const SmallVectorImpl<uint8_t> &Opcodes); 150 151 virtual void switchVendor(StringRef Vendor); 152 virtual void emitAttribute(unsigned Attribute, unsigned Value); 153 virtual void emitTextAttribute(unsigned Attribute, StringRef String); 154 virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue, 155 StringRef StringValue = ""); 156 virtual void emitFPU(unsigned FPU); 157 virtual void emitArch(ARM::ArchKind Arch); 158 virtual void emitArchExtension(unsigned ArchExt); 159 virtual void emitObjectArch(ARM::ArchKind Arch); 160 void emitTargetAttributes(const MCSubtargetInfo &STI); 161 virtual void finishAttributeSection(); 162 virtual void emitInst(uint32_t Inst, char Suffix = '\0'); 163 164 virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE); 165 166 virtual void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value); 167 168 void finish() override; 169 170 /// Reset any state between object emissions, i.e. the equivalent of 171 /// MCStreamer's reset method. 172 virtual void reset(); 173 174 /// Callback used to implement the ldr= pseudo. 175 /// Add a new entry to the constant pool for the current section and return an 176 /// MCExpr that can be used to refer to the constant pool location. 177 const MCExpr *addConstantPoolEntry(const MCExpr *, SMLoc Loc); 178 179 /// Callback used to implemnt the .ltorg directive. 180 /// Emit contents of constant pool for the current section. 181 void emitCurrentConstantPool(); 182 183 private: 184 std::unique_ptr<AssemblerConstantPools> ConstantPools; 185 }; 186 187 /// Streaming machine code generation interface. 188 /// 189 /// This interface is intended to provide a programatic interface that is very 190 /// similar to the level that an assembler .s file provides. It has callbacks 191 /// to emit bytes, handle directives, etc. The implementation of this interface 192 /// retains state to know what the current section is etc. 193 /// 194 /// There are multiple implementations of this interface: one for writing out 195 /// a .s file, and implementations that write out .o files of various formats. 196 /// 197 class MCStreamer { 198 MCContext &Context; 199 std::unique_ptr<MCTargetStreamer> TargetStreamer; 200 201 std::vector<MCDwarfFrameInfo> DwarfFrameInfos; 202 MCDwarfFrameInfo *getCurrentDwarfFrameInfo(); 203 204 /// Similar to DwarfFrameInfos, but for SEH unwind info. Chained frames may 205 /// refer to each other, so use std::unique_ptr to provide pointer stability. 206 std::vector<std::unique_ptr<WinEH::FrameInfo>> WinFrameInfos; 207 208 WinEH::FrameInfo *CurrentWinFrameInfo; 209 210 /// Tracks an index to represent the order a symbol was emitted in. 211 /// Zero means we did not emit that symbol. 212 DenseMap<const MCSymbol *, unsigned> SymbolOrdering; 213 214 /// This is stack of current and previous section values saved by 215 /// PushSection. 216 SmallVector<std::pair<MCSectionSubPair, MCSectionSubPair>, 4> SectionStack; 217 218 /// The next unique ID to use when creating a WinCFI-related section (.pdata 219 /// or .xdata). This ID ensures that we have a one-to-one mapping from 220 /// code section to unwind info section, which MSVC's incremental linker 221 /// requires. 222 unsigned NextWinCFIID = 0; 223 224 bool UseAssemblerInfoForParsing; 225 226 /// Is the assembler allowed to insert padding automatically? For 227 /// correctness reasons, we sometimes need to ensure instructions aren't 228 /// seperated in unexpected ways. At the moment, this feature is only 229 /// useable from an integrated assembler, but assembly syntax is under 230 /// discussion for future inclusion. 231 bool AllowAutoPadding = false; 232 233 protected: 234 MCStreamer(MCContext &Ctx); 235 236 virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame); 237 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame); 238 getCurrentWinFrameInfo()239 WinEH::FrameInfo *getCurrentWinFrameInfo() { 240 return CurrentWinFrameInfo; 241 } 242 243 virtual void EmitWindowsUnwindTables(); 244 245 virtual void EmitRawTextImpl(StringRef String); 246 247 /// Returns true if the the .cv_loc directive is in the right section. 248 bool checkCVLocSection(unsigned FuncId, unsigned FileNo, SMLoc Loc); 249 250 public: 251 MCStreamer(const MCStreamer &) = delete; 252 MCStreamer &operator=(const MCStreamer &) = delete; 253 virtual ~MCStreamer(); 254 255 void visitUsedExpr(const MCExpr &Expr); 256 virtual void visitUsedSymbol(const MCSymbol &Sym); 257 setTargetStreamer(MCTargetStreamer * TS)258 void setTargetStreamer(MCTargetStreamer *TS) { 259 TargetStreamer.reset(TS); 260 } 261 262 /// State management 263 /// 264 virtual void reset(); 265 getContext()266 MCContext &getContext() const { return Context; } 267 getAssemblerPtr()268 virtual MCAssembler *getAssemblerPtr() { return nullptr; } 269 setUseAssemblerInfoForParsing(bool v)270 void setUseAssemblerInfoForParsing(bool v) { UseAssemblerInfoForParsing = v; } getUseAssemblerInfoForParsing()271 bool getUseAssemblerInfoForParsing() { return UseAssemblerInfoForParsing; } 272 getTargetStreamer()273 MCTargetStreamer *getTargetStreamer() { 274 return TargetStreamer.get(); 275 } 276 setAllowAutoPadding(bool v)277 void setAllowAutoPadding(bool v) { AllowAutoPadding = v; } getAllowAutoPadding()278 bool getAllowAutoPadding() const { return AllowAutoPadding; } 279 280 /// When emitting an object file, create and emit a real label. When emitting 281 /// textual assembly, this should do nothing to avoid polluting our output. 282 virtual MCSymbol *EmitCFILabel(); 283 284 /// Retreive the current frame info if one is available and it is not yet 285 /// closed. Otherwise, issue an error and return null. 286 WinEH::FrameInfo *EnsureValidWinFrameInfo(SMLoc Loc); 287 288 unsigned getNumFrameInfos(); 289 ArrayRef<MCDwarfFrameInfo> getDwarfFrameInfos() const; 290 291 bool hasUnfinishedDwarfFrameInfo(); 292 getNumWinFrameInfos()293 unsigned getNumWinFrameInfos() { return WinFrameInfos.size(); } getWinFrameInfos()294 ArrayRef<std::unique_ptr<WinEH::FrameInfo>> getWinFrameInfos() const { 295 return WinFrameInfos; 296 } 297 298 void generateCompactUnwindEncodings(MCAsmBackend *MAB); 299 300 /// \name Assembly File Formatting. 301 /// @{ 302 303 /// Return true if this streamer supports verbose assembly and if it is 304 /// enabled. isVerboseAsm()305 virtual bool isVerboseAsm() const { return false; } 306 307 /// Return true if this asm streamer supports emitting unformatted text 308 /// to the .s file with EmitRawText. hasRawTextSupport()309 virtual bool hasRawTextSupport() const { return false; } 310 311 /// Is the integrated assembler required for this streamer to function 312 /// correctly? isIntegratedAssemblerRequired()313 virtual bool isIntegratedAssemblerRequired() const { return false; } 314 315 /// Add a textual comment. 316 /// 317 /// Typically for comments that can be emitted to the generated .s 318 /// file if applicable as a QoI issue to make the output of the compiler 319 /// more readable. This only affects the MCAsmStreamer, and only when 320 /// verbose assembly output is enabled. 321 /// 322 /// If the comment includes embedded \n's, they will each get the comment 323 /// prefix as appropriate. The added comment should not end with a \n. 324 /// By default, each comment is terminated with an end of line, i.e. the 325 /// EOL param is set to true by default. If one prefers not to end the 326 /// comment with a new line then the EOL param should be passed 327 /// with a false value. 328 virtual void AddComment(const Twine &T, bool EOL = true) {} 329 330 /// Return a raw_ostream that comments can be written to. Unlike 331 /// AddComment, you are required to terminate comments with \n if you use this 332 /// method. 333 virtual raw_ostream &GetCommentOS(); 334 335 /// Print T and prefix it with the comment string (normally #) and 336 /// optionally a tab. This prints the comment immediately, not at the end of 337 /// the current line. It is basically a safe version of EmitRawText: since it 338 /// only prints comments, the object streamer ignores it instead of asserting. 339 virtual void emitRawComment(const Twine &T, bool TabPrefix = true); 340 341 /// Add explicit comment T. T is required to be a valid 342 /// comment in the output and does not need to be escaped. 343 virtual void addExplicitComment(const Twine &T); 344 345 /// Emit added explicit comments. 346 virtual void emitExplicitComments(); 347 348 /// AddBlankLine - Emit a blank line to a .s file to pretty it up. AddBlankLine()349 virtual void AddBlankLine() {} 350 351 /// @} 352 353 /// \name Symbol & Section Management 354 /// @{ 355 356 /// Return the current section that the streamer is emitting code to. getCurrentSection()357 MCSectionSubPair getCurrentSection() const { 358 if (!SectionStack.empty()) 359 return SectionStack.back().first; 360 return MCSectionSubPair(); 361 } getCurrentSectionOnly()362 MCSection *getCurrentSectionOnly() const { return getCurrentSection().first; } 363 364 /// Return the previous section that the streamer is emitting code to. getPreviousSection()365 MCSectionSubPair getPreviousSection() const { 366 if (!SectionStack.empty()) 367 return SectionStack.back().second; 368 return MCSectionSubPair(); 369 } 370 371 /// Returns an index to represent the order a symbol was emitted in. 372 /// (zero if we did not emit that symbol) GetSymbolOrder(const MCSymbol * Sym)373 unsigned GetSymbolOrder(const MCSymbol *Sym) const { 374 return SymbolOrdering.lookup(Sym); 375 } 376 377 /// Update streamer for a new active section. 378 /// 379 /// This is called by PopSection and SwitchSection, if the current 380 /// section changes. 381 virtual void ChangeSection(MCSection *, const MCExpr *); 382 383 /// Save the current and previous section on the section stack. PushSection()384 void PushSection() { 385 SectionStack.push_back( 386 std::make_pair(getCurrentSection(), getPreviousSection())); 387 } 388 389 /// Restore the current and previous section from the section stack. 390 /// Calls ChangeSection as needed. 391 /// 392 /// Returns false if the stack was empty. PopSection()393 bool PopSection() { 394 if (SectionStack.size() <= 1) 395 return false; 396 auto I = SectionStack.end(); 397 --I; 398 MCSectionSubPair OldSection = I->first; 399 --I; 400 MCSectionSubPair NewSection = I->first; 401 402 if (OldSection != NewSection) 403 ChangeSection(NewSection.first, NewSection.second); 404 SectionStack.pop_back(); 405 return true; 406 } 407 SubSection(const MCExpr * Subsection)408 bool SubSection(const MCExpr *Subsection) { 409 if (SectionStack.empty()) 410 return false; 411 412 SwitchSection(SectionStack.back().first.first, Subsection); 413 return true; 414 } 415 416 /// Set the current section where code is being emitted to \p Section. This 417 /// is required to update CurSection. 418 /// 419 /// This corresponds to assembler directives like .section, .text, etc. 420 virtual void SwitchSection(MCSection *Section, 421 const MCExpr *Subsection = nullptr); 422 423 /// Set the current section where code is being emitted to \p Section. 424 /// This is required to update CurSection. This version does not call 425 /// ChangeSection. 426 void SwitchSectionNoChange(MCSection *Section, 427 const MCExpr *Subsection = nullptr) { 428 assert(Section && "Cannot switch to a null section!"); 429 MCSectionSubPair curSection = SectionStack.back().first; 430 SectionStack.back().second = curSection; 431 if (MCSectionSubPair(Section, Subsection) != curSection) 432 SectionStack.back().first = MCSectionSubPair(Section, Subsection); 433 } 434 435 /// Create the default sections and set the initial one. 436 virtual void InitSections(bool NoExecStack); 437 438 MCSymbol *endSection(MCSection *Section); 439 440 /// Sets the symbol's section. 441 /// 442 /// Each emitted symbol will be tracked in the ordering table, 443 /// so we can sort on them later. 444 void AssignFragment(MCSymbol *Symbol, MCFragment *Fragment); 445 446 /// Emit a label for \p Symbol into the current section. 447 /// 448 /// This corresponds to an assembler statement such as: 449 /// foo: 450 /// 451 /// \param Symbol - The symbol to emit. A given symbol should only be 452 /// emitted as a label once, and symbols emitted as a label should never be 453 /// used in an assignment. 454 // FIXME: These emission are non-const because we mutate the symbol to 455 // add the section we're emitting it to later. 456 virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()); 457 458 virtual void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol); 459 460 /// Note in the output the specified \p Flag. 461 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag); 462 463 /// Emit the given list \p Options of strings as linker 464 /// options into the output. EmitLinkerOptions(ArrayRef<std::string> Kind)465 virtual void EmitLinkerOptions(ArrayRef<std::string> Kind) {} 466 467 /// Note in the output the specified region \p Kind. EmitDataRegion(MCDataRegionType Kind)468 virtual void EmitDataRegion(MCDataRegionType Kind) {} 469 470 /// Specify the Mach-O minimum deployment target version. EmitVersionMin(MCVersionMinType Type,unsigned Major,unsigned Minor,unsigned Update,VersionTuple SDKVersion)471 virtual void EmitVersionMin(MCVersionMinType Type, unsigned Major, 472 unsigned Minor, unsigned Update, 473 VersionTuple SDKVersion) {} 474 475 /// Emit/Specify Mach-O build version command. 476 /// \p Platform should be one of MachO::PlatformType. EmitBuildVersion(unsigned Platform,unsigned Major,unsigned Minor,unsigned Update,VersionTuple SDKVersion)477 virtual void EmitBuildVersion(unsigned Platform, unsigned Major, 478 unsigned Minor, unsigned Update, 479 VersionTuple SDKVersion) {} 480 481 void EmitVersionForTarget(const Triple &Target, 482 const VersionTuple &SDKVersion); 483 484 /// Note in the output that the specified \p Func is a Thumb mode 485 /// function (ARM target only). 486 virtual void EmitThumbFunc(MCSymbol *Func); 487 488 /// Emit an assignment of \p Value to \p Symbol. 489 /// 490 /// This corresponds to an assembler statement such as: 491 /// symbol = value 492 /// 493 /// The assignment generates no code, but has the side effect of binding the 494 /// value in the current context. For the assembly streamer, this prints the 495 /// binding into the .s file. 496 /// 497 /// \param Symbol - The symbol being assigned to. 498 /// \param Value - The value for the symbol. 499 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value); 500 501 /// Emit an weak reference from \p Alias to \p Symbol. 502 /// 503 /// This corresponds to an assembler statement such as: 504 /// .weakref alias, symbol 505 /// 506 /// \param Alias - The alias that is being created. 507 /// \param Symbol - The symbol being aliased. 508 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol); 509 510 /// Add the given \p Attribute to \p Symbol. 511 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, 512 MCSymbolAttr Attribute) = 0; 513 514 /// Set the \p DescValue for the \p Symbol. 515 /// 516 /// \param Symbol - The symbol to have its n_desc field set. 517 /// \param DescValue - The value to set into the n_desc field. 518 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue); 519 520 /// Start emitting COFF symbol definition 521 /// 522 /// \param Symbol - The symbol to have its External & Type fields set. 523 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol); 524 525 /// Emit the storage class of the symbol. 526 /// 527 /// \param StorageClass - The storage class the symbol should have. 528 virtual void EmitCOFFSymbolStorageClass(int StorageClass); 529 530 /// Emit the type of the symbol. 531 /// 532 /// \param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h) 533 virtual void EmitCOFFSymbolType(int Type); 534 535 /// Marks the end of the symbol definition. 536 virtual void EndCOFFSymbolDef(); 537 538 virtual void EmitCOFFSafeSEH(MCSymbol const *Symbol); 539 540 /// Emits the symbol table index of a Symbol into the current section. 541 virtual void EmitCOFFSymbolIndex(MCSymbol const *Symbol); 542 543 /// Emits a COFF section index. 544 /// 545 /// \param Symbol - Symbol the section number relocation should point to. 546 virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol); 547 548 /// Emits a COFF section relative relocation. 549 /// 550 /// \param Symbol - Symbol the section relative relocation should point to. 551 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset); 552 553 /// Emits a COFF image relative relocation. 554 /// 555 /// \param Symbol - Symbol the image relative relocation should point to. 556 virtual void EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset); 557 558 /// Emits an lcomm directive with XCOFF csect information. 559 /// 560 /// \param LabelSym - Label on the block of storage. 561 /// \param Size - The size of the block of storage. 562 /// \param CsectSym - Csect name for the block of storage. 563 /// \param ByteAlignment - The alignment of the symbol in bytes. Must be a 564 /// power of 2. 565 virtual void EmitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size, 566 MCSymbol *CsectSym, 567 unsigned ByteAlignment); 568 569 /// Emit an ELF .size directive. 570 /// 571 /// This corresponds to an assembler statement such as: 572 /// .size symbol, expression 573 virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value); 574 575 /// Emit an ELF .symver directive. 576 /// 577 /// This corresponds to an assembler statement such as: 578 /// .symver _start, foo@@SOME_VERSION 579 /// \param AliasName - The versioned alias (i.e. "foo@@SOME_VERSION") 580 /// \param Aliasee - The aliased symbol (i.e. "_start") 581 virtual void emitELFSymverDirective(StringRef AliasName, 582 const MCSymbol *Aliasee); 583 584 /// Emit a Linker Optimization Hint (LOH) directive. 585 /// \param Args - Arguments of the LOH. EmitLOHDirective(MCLOHType Kind,const MCLOHArgs & Args)586 virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {} 587 588 /// Emit a common symbol. 589 /// 590 /// \param Symbol - The common symbol to emit. 591 /// \param Size - The size of the common symbol. 592 /// \param ByteAlignment - The alignment of the symbol if 593 /// non-zero. This must be a power of 2. 594 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, 595 unsigned ByteAlignment) = 0; 596 597 /// Emit a local common (.lcomm) symbol. 598 /// 599 /// \param Symbol - The common symbol to emit. 600 /// \param Size - The size of the common symbol. 601 /// \param ByteAlignment - The alignment of the common symbol in bytes. 602 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, 603 unsigned ByteAlignment); 604 605 /// Emit the zerofill section and an optional symbol. 606 /// 607 /// \param Section - The zerofill section to create and or to put the symbol 608 /// \param Symbol - The zerofill symbol to emit, if non-NULL. 609 /// \param Size - The size of the zerofill symbol. 610 /// \param ByteAlignment - The alignment of the zerofill symbol if 611 /// non-zero. This must be a power of 2 on some targets. 612 virtual void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr, 613 uint64_t Size = 0, unsigned ByteAlignment = 0, 614 SMLoc Loc = SMLoc()) = 0; 615 616 /// Emit a thread local bss (.tbss) symbol. 617 /// 618 /// \param Section - The thread local common section. 619 /// \param Symbol - The thread local common symbol to emit. 620 /// \param Size - The size of the symbol. 621 /// \param ByteAlignment - The alignment of the thread local common symbol 622 /// if non-zero. This must be a power of 2 on some targets. 623 virtual void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, 624 uint64_t Size, unsigned ByteAlignment = 0); 625 626 /// @} 627 /// \name Generating Data 628 /// @{ 629 630 /// Emit the bytes in \p Data into the output. 631 /// 632 /// This is used to implement assembler directives such as .byte, .ascii, 633 /// etc. 634 virtual void EmitBytes(StringRef Data); 635 636 /// Functionally identical to EmitBytes. When emitting textual assembly, this 637 /// method uses .byte directives instead of .ascii or .asciz for readability. 638 virtual void EmitBinaryData(StringRef Data); 639 640 /// Emit the expression \p Value into the output as a native 641 /// integer of the given \p Size bytes. 642 /// 643 /// This is used to implement assembler directives such as .word, .quad, 644 /// etc. 645 /// 646 /// \param Value - The value to emit. 647 /// \param Size - The size of the integer (in bytes) to emit. This must 648 /// match a native machine width. 649 /// \param Loc - The location of the expression for error reporting. 650 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size, 651 SMLoc Loc = SMLoc()); 652 653 void EmitValue(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc()); 654 655 /// Special case of EmitValue that avoids the client having 656 /// to pass in a MCExpr for constant integers. 657 virtual void EmitIntValue(uint64_t Value, unsigned Size); 658 659 /// Special case of EmitValue that avoids the client having to pass 660 /// in a MCExpr for constant integers & prints in Hex format for certain 661 /// modes. EmitIntValueInHex(uint64_t Value,unsigned Size)662 virtual void EmitIntValueInHex(uint64_t Value, unsigned Size) { 663 EmitIntValue(Value, Size); 664 } 665 666 virtual void EmitULEB128Value(const MCExpr *Value); 667 668 virtual void EmitSLEB128Value(const MCExpr *Value); 669 670 /// Special case of EmitULEB128Value that avoids the client having to 671 /// pass in a MCExpr for constant integers. 672 void EmitULEB128IntValue(uint64_t Value, unsigned PadTo = 0); 673 674 /// Special case of EmitSLEB128Value that avoids the client having to 675 /// pass in a MCExpr for constant integers. 676 void EmitSLEB128IntValue(int64_t Value); 677 678 /// Special case of EmitValue that avoids the client having to pass in 679 /// a MCExpr for MCSymbols. 680 void EmitSymbolValue(const MCSymbol *Sym, unsigned Size, 681 bool IsSectionRelative = false); 682 683 /// Emit the expression \p Value into the output as a dtprel 684 /// (64-bit DTP relative) value. 685 /// 686 /// This is used to implement assembler directives such as .dtpreldword on 687 /// targets that support them. 688 virtual void EmitDTPRel64Value(const MCExpr *Value); 689 690 /// Emit the expression \p Value into the output as a dtprel 691 /// (32-bit DTP relative) value. 692 /// 693 /// This is used to implement assembler directives such as .dtprelword on 694 /// targets that support them. 695 virtual void EmitDTPRel32Value(const MCExpr *Value); 696 697 /// Emit the expression \p Value into the output as a tprel 698 /// (64-bit TP relative) value. 699 /// 700 /// This is used to implement assembler directives such as .tpreldword on 701 /// targets that support them. 702 virtual void EmitTPRel64Value(const MCExpr *Value); 703 704 /// Emit the expression \p Value into the output as a tprel 705 /// (32-bit TP relative) value. 706 /// 707 /// This is used to implement assembler directives such as .tprelword on 708 /// targets that support them. 709 virtual void EmitTPRel32Value(const MCExpr *Value); 710 711 /// Emit the expression \p Value into the output as a gprel64 (64-bit 712 /// GP relative) value. 713 /// 714 /// This is used to implement assembler directives such as .gpdword on 715 /// targets that support them. 716 virtual void EmitGPRel64Value(const MCExpr *Value); 717 718 /// Emit the expression \p Value into the output as a gprel32 (32-bit 719 /// GP relative) value. 720 /// 721 /// This is used to implement assembler directives such as .gprel32 on 722 /// targets that support them. 723 virtual void EmitGPRel32Value(const MCExpr *Value); 724 725 /// Emit NumBytes bytes worth of the value specified by FillValue. 726 /// This implements directives such as '.space'. 727 void emitFill(uint64_t NumBytes, uint8_t FillValue); 728 729 /// Emit \p Size bytes worth of the value specified by \p FillValue. 730 /// 731 /// This is used to implement assembler directives such as .space or .skip. 732 /// 733 /// \param NumBytes - The number of bytes to emit. 734 /// \param FillValue - The value to use when filling bytes. 735 /// \param Loc - The location of the expression for error reporting. 736 virtual void emitFill(const MCExpr &NumBytes, uint64_t FillValue, 737 SMLoc Loc = SMLoc()); 738 739 /// Emit \p NumValues copies of \p Size bytes. Each \p Size bytes is 740 /// taken from the lowest order 4 bytes of \p Expr expression. 741 /// 742 /// This is used to implement assembler directives such as .fill. 743 /// 744 /// \param NumValues - The number of copies of \p Size bytes to emit. 745 /// \param Size - The size (in bytes) of each repeated value. 746 /// \param Expr - The expression from which \p Size bytes are used. 747 virtual void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr, 748 SMLoc Loc = SMLoc()); 749 750 /// Emit NumBytes worth of zeros. 751 /// This function properly handles data in virtual sections. 752 void EmitZeros(uint64_t NumBytes); 753 754 /// Emit some number of copies of \p Value until the byte alignment \p 755 /// ByteAlignment is reached. 756 /// 757 /// If the number of bytes need to emit for the alignment is not a multiple 758 /// of \p ValueSize, then the contents of the emitted fill bytes is 759 /// undefined. 760 /// 761 /// This used to implement the .align assembler directive. 762 /// 763 /// \param ByteAlignment - The alignment to reach. This must be a power of 764 /// two on some targets. 765 /// \param Value - The value to use when filling bytes. 766 /// \param ValueSize - The size of the integer (in bytes) to emit for 767 /// \p Value. This must match a native machine width. 768 /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If 769 /// the alignment cannot be reached in this many bytes, no bytes are 770 /// emitted. 771 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, 772 unsigned ValueSize = 1, 773 unsigned MaxBytesToEmit = 0); 774 775 /// Emit nops until the byte alignment \p ByteAlignment is reached. 776 /// 777 /// This used to align code where the alignment bytes may be executed. This 778 /// can emit different bytes for different sizes to optimize execution. 779 /// 780 /// \param ByteAlignment - The alignment to reach. This must be a power of 781 /// two on some targets. 782 /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If 783 /// the alignment cannot be reached in this many bytes, no bytes are 784 /// emitted. 785 virtual void EmitCodeAlignment(unsigned ByteAlignment, 786 unsigned MaxBytesToEmit = 0); 787 788 /// Emit some number of copies of \p Value until the byte offset \p 789 /// Offset is reached. 790 /// 791 /// This is used to implement assembler directives such as .org. 792 /// 793 /// \param Offset - The offset to reach. This may be an expression, but the 794 /// expression must be associated with the current section. 795 /// \param Value - The value to use when filling bytes. 796 virtual void emitValueToOffset(const MCExpr *Offset, unsigned char Value, 797 SMLoc Loc); 798 799 virtual void EmitCodePaddingBasicBlockStart(const MCCodePaddingContext & Context)800 EmitCodePaddingBasicBlockStart(const MCCodePaddingContext &Context) {} 801 802 virtual void EmitCodePaddingBasicBlockEnd(const MCCodePaddingContext & Context)803 EmitCodePaddingBasicBlockEnd(const MCCodePaddingContext &Context) {} 804 805 /// @} 806 807 /// Switch to a new logical file. This is used to implement the '.file 808 /// "foo.c"' assembler directive. 809 virtual void EmitFileDirective(StringRef Filename); 810 811 /// Emit the "identifiers" directive. This implements the 812 /// '.ident "version foo"' assembler directive. EmitIdent(StringRef IdentString)813 virtual void EmitIdent(StringRef IdentString) {} 814 815 /// Associate a filename with a specified logical file number. This 816 /// implements the DWARF2 '.file 4 "foo.c"' assembler directive. 817 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory, 818 StringRef Filename, 819 Optional<MD5::MD5Result> Checksum = None, 820 Optional<StringRef> Source = None, 821 unsigned CUID = 0) { 822 return cantFail( 823 tryEmitDwarfFileDirective(FileNo, Directory, Filename, Checksum, 824 Source, CUID)); 825 } 826 827 /// Associate a filename with a specified logical file number. 828 /// Also associate a directory, optional checksum, and optional source 829 /// text with the logical file. This implements the DWARF2 830 /// '.file 4 "dir/foo.c"' assembler directive, and the DWARF5 831 /// '.file 4 "dir/foo.c" md5 "..." source "..."' assembler directive. 832 virtual Expected<unsigned> tryEmitDwarfFileDirective( 833 unsigned FileNo, StringRef Directory, StringRef Filename, 834 Optional<MD5::MD5Result> Checksum = None, Optional<StringRef> Source = None, 835 unsigned CUID = 0); 836 837 /// Specify the "root" file of the compilation, using the ".file 0" extension. 838 virtual void emitDwarfFile0Directive(StringRef Directory, StringRef Filename, 839 Optional<MD5::MD5Result> Checksum, 840 Optional<StringRef> Source, 841 unsigned CUID = 0); 842 843 virtual void EmitCFIBKeyFrame(); 844 845 /// This implements the DWARF2 '.loc fileno lineno ...' assembler 846 /// directive. 847 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line, 848 unsigned Column, unsigned Flags, 849 unsigned Isa, unsigned Discriminator, 850 StringRef FileName); 851 852 /// Associate a filename with a specified logical file number, and also 853 /// specify that file's checksum information. This implements the '.cv_file 4 854 /// "foo.c"' assembler directive. Returns true on success. 855 virtual bool EmitCVFileDirective(unsigned FileNo, StringRef Filename, 856 ArrayRef<uint8_t> Checksum, 857 unsigned ChecksumKind); 858 859 /// Introduces a function id for use with .cv_loc. 860 virtual bool EmitCVFuncIdDirective(unsigned FunctionId); 861 862 /// Introduces an inline call site id for use with .cv_loc. Includes 863 /// extra information for inline line table generation. 864 virtual bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc, 865 unsigned IAFile, unsigned IALine, 866 unsigned IACol, SMLoc Loc); 867 868 /// This implements the CodeView '.cv_loc' assembler directive. 869 virtual void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, 870 unsigned Line, unsigned Column, 871 bool PrologueEnd, bool IsStmt, 872 StringRef FileName, SMLoc Loc); 873 874 /// This implements the CodeView '.cv_linetable' assembler directive. 875 virtual void EmitCVLinetableDirective(unsigned FunctionId, 876 const MCSymbol *FnStart, 877 const MCSymbol *FnEnd); 878 879 /// This implements the CodeView '.cv_inline_linetable' assembler 880 /// directive. 881 virtual void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId, 882 unsigned SourceFileId, 883 unsigned SourceLineNum, 884 const MCSymbol *FnStartSym, 885 const MCSymbol *FnEndSym); 886 887 /// This implements the CodeView '.cv_def_range' assembler 888 /// directive. 889 virtual void EmitCVDefRangeDirective( 890 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, 891 StringRef FixedSizePortion); 892 893 virtual void EmitCVDefRangeDirective( 894 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, 895 codeview::DefRangeRegisterRelHeader DRHdr); 896 897 virtual void EmitCVDefRangeDirective( 898 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, 899 codeview::DefRangeSubfieldRegisterHeader DRHdr); 900 901 virtual void EmitCVDefRangeDirective( 902 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, 903 codeview::DefRangeRegisterHeader DRHdr); 904 905 virtual void EmitCVDefRangeDirective( 906 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, 907 codeview::DefRangeFramePointerRelHeader DRHdr); 908 909 /// This implements the CodeView '.cv_stringtable' assembler directive. EmitCVStringTableDirective()910 virtual void EmitCVStringTableDirective() {} 911 912 /// This implements the CodeView '.cv_filechecksums' assembler directive. EmitCVFileChecksumsDirective()913 virtual void EmitCVFileChecksumsDirective() {} 914 915 /// This implements the CodeView '.cv_filechecksumoffset' assembler 916 /// directive. EmitCVFileChecksumOffsetDirective(unsigned FileNo)917 virtual void EmitCVFileChecksumOffsetDirective(unsigned FileNo) {} 918 919 /// This implements the CodeView '.cv_fpo_data' assembler directive. 920 virtual void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc Loc = {}) {} 921 922 /// Emit the absolute difference between two symbols. 923 /// 924 /// \pre Offset of \c Hi is greater than the offset \c Lo. 925 virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, 926 unsigned Size); 927 928 /// Emit the absolute difference between two symbols encoded with ULEB128. 929 virtual void emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi, 930 const MCSymbol *Lo); 931 932 virtual MCSymbol *getDwarfLineTableSymbol(unsigned CUID); 933 virtual void EmitCFISections(bool EH, bool Debug); 934 void EmitCFIStartProc(bool IsSimple, SMLoc Loc = SMLoc()); 935 void EmitCFIEndProc(); 936 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset); 937 virtual void EmitCFIDefCfaOffset(int64_t Offset); 938 virtual void EmitCFIDefCfaRegister(int64_t Register); 939 virtual void EmitCFIOffset(int64_t Register, int64_t Offset); 940 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding); 941 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding); 942 virtual void EmitCFIRememberState(); 943 virtual void EmitCFIRestoreState(); 944 virtual void EmitCFISameValue(int64_t Register); 945 virtual void EmitCFIRestore(int64_t Register); 946 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset); 947 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment); 948 virtual void EmitCFIEscape(StringRef Values); 949 virtual void EmitCFIReturnColumn(int64_t Register); 950 virtual void EmitCFIGnuArgsSize(int64_t Size); 951 virtual void EmitCFISignalFrame(); 952 virtual void EmitCFIUndefined(int64_t Register); 953 virtual void EmitCFIRegister(int64_t Register1, int64_t Register2); 954 virtual void EmitCFIWindowSave(); 955 virtual void EmitCFINegateRAState(); 956 957 virtual void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc = SMLoc()); 958 virtual void EmitWinCFIEndProc(SMLoc Loc = SMLoc()); 959 /// This is used on platforms, such as Windows on ARM64, that require function 960 /// or funclet sizes to be emitted in .xdata before the End marker is emitted 961 /// for the frame. We cannot use the End marker, as it is not set at the 962 /// point of emitting .xdata, in order to indicate that the frame is active. 963 virtual void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc = SMLoc()); 964 virtual void EmitWinCFIStartChained(SMLoc Loc = SMLoc()); 965 virtual void EmitWinCFIEndChained(SMLoc Loc = SMLoc()); 966 virtual void EmitWinCFIPushReg(MCRegister Register, SMLoc Loc = SMLoc()); 967 virtual void EmitWinCFISetFrame(MCRegister Register, unsigned Offset, 968 SMLoc Loc = SMLoc()); 969 virtual void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc = SMLoc()); 970 virtual void EmitWinCFISaveReg(MCRegister Register, unsigned Offset, 971 SMLoc Loc = SMLoc()); 972 virtual void EmitWinCFISaveXMM(MCRegister Register, unsigned Offset, 973 SMLoc Loc = SMLoc()); 974 virtual void EmitWinCFIPushFrame(bool Code, SMLoc Loc = SMLoc()); 975 virtual void EmitWinCFIEndProlog(SMLoc Loc = SMLoc()); 976 virtual void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except, 977 SMLoc Loc = SMLoc()); 978 virtual void EmitWinEHHandlerData(SMLoc Loc = SMLoc()); 979 980 virtual void emitCGProfileEntry(const MCSymbolRefExpr *From, 981 const MCSymbolRefExpr *To, uint64_t Count); 982 983 /// Get the .pdata section used for the given section. Typically the given 984 /// section is either the main .text section or some other COMDAT .text 985 /// section, but it may be any section containing code. 986 MCSection *getAssociatedPDataSection(const MCSection *TextSec); 987 988 /// Get the .xdata section used for the given section. 989 MCSection *getAssociatedXDataSection(const MCSection *TextSec); 990 991 virtual void EmitSyntaxDirective(); 992 993 /// Emit a .reloc directive. 994 /// Returns true if the relocation could not be emitted because Name is not 995 /// known. EmitRelocDirective(const MCExpr & Offset,StringRef Name,const MCExpr * Expr,SMLoc Loc,const MCSubtargetInfo & STI)996 virtual bool EmitRelocDirective(const MCExpr &Offset, StringRef Name, 997 const MCExpr *Expr, SMLoc Loc, 998 const MCSubtargetInfo &STI) { 999 return true; 1000 } 1001 EmitAddrsig()1002 virtual void EmitAddrsig() {} EmitAddrsigSym(const MCSymbol * Sym)1003 virtual void EmitAddrsigSym(const MCSymbol *Sym) {} 1004 1005 /// Emit the given \p Instruction into the current section. 1006 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI); 1007 1008 /// Set the bundle alignment mode from now on in the section. 1009 /// The argument is the power of 2 to which the alignment is set. The 1010 /// value 0 means turn the bundle alignment off. 1011 virtual void EmitBundleAlignMode(unsigned AlignPow2); 1012 1013 /// The following instructions are a bundle-locked group. 1014 /// 1015 /// \param AlignToEnd - If true, the bundle-locked group will be aligned to 1016 /// the end of a bundle. 1017 virtual void EmitBundleLock(bool AlignToEnd); 1018 1019 /// Ends a bundle-locked group. 1020 virtual void EmitBundleUnlock(); 1021 1022 /// If this file is backed by a assembly streamer, this dumps the 1023 /// specified string in the output .s file. This capability is indicated by 1024 /// the hasRawTextSupport() predicate. By default this aborts. 1025 void EmitRawText(const Twine &String); 1026 1027 /// Streamer specific finalization. 1028 virtual void FinishImpl(); 1029 /// Finish emission of machine code. 1030 void Finish(); 1031 mayHaveInstructions(MCSection & Sec)1032 virtual bool mayHaveInstructions(MCSection &Sec) const { return true; } 1033 }; 1034 1035 /// Create a dummy machine code streamer, which does nothing. This is useful for 1036 /// timing the assembler front end. 1037 MCStreamer *createNullStreamer(MCContext &Ctx); 1038 1039 /// Create a machine code streamer which will print out assembly for the native 1040 /// target, suitable for compiling with a native assembler. 1041 /// 1042 /// \param InstPrint - If given, the instruction printer to use. If not given 1043 /// the MCInst representation will be printed. This method takes ownership of 1044 /// InstPrint. 1045 /// 1046 /// \param CE - If given, a code emitter to use to show the instruction 1047 /// encoding inline with the assembly. This method takes ownership of \p CE. 1048 /// 1049 /// \param TAB - If given, a target asm backend to use to show the fixup 1050 /// information in conjunction with encoding information. This method takes 1051 /// ownership of \p TAB. 1052 /// 1053 /// \param ShowInst - Whether to show the MCInst representation inline with 1054 /// the assembly. 1055 MCStreamer *createAsmStreamer(MCContext &Ctx, 1056 std::unique_ptr<formatted_raw_ostream> OS, 1057 bool isVerboseAsm, bool useDwarfDirectory, 1058 MCInstPrinter *InstPrint, MCCodeEmitter *CE, 1059 MCAsmBackend *TAB, bool ShowInst); 1060 1061 } // end namespace llvm 1062 1063 #endif // LLVM_MC_MCSTREAMER_H 1064