1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCSymbolELF.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/LEB128.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Path.h"
41 class MCAsmStreamer final : public MCStreamer {
42 std::unique_ptr<formatted_raw_ostream> OSOwner;
43 formatted_raw_ostream &OS;
45 std::unique_ptr<MCInstPrinter> InstPrinter;
46 std::unique_ptr<MCCodeEmitter> Emitter;
47 std::unique_ptr<MCAsmBackend> AsmBackend;
49 SmallString<128> CommentToEmit;
50 raw_svector_ostream CommentStream;
52 unsigned IsVerboseAsm : 1;
53 unsigned ShowInst : 1;
54 unsigned UseDwarfDirectory : 1;
56 void EmitRegisterName(int64_t Register);
57 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
58 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
61 MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
62 bool isVerboseAsm, bool useDwarfDirectory,
63 MCInstPrinter *printer, MCCodeEmitter *emitter,
64 MCAsmBackend *asmbackend, bool showInst)
65 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
66 MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
67 AsmBackend(asmbackend), CommentStream(CommentToEmit),
68 IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
69 UseDwarfDirectory(useDwarfDirectory) {
72 InstPrinter->setCommentStream(CommentStream);
75 inline void EmitEOL() {
76 // If we don't have any comments, just emit a \n.
84 void EmitSyntaxDirective() override;
86 void EmitCommentsAndEOL();
88 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
90 bool isVerboseAsm() const override { return IsVerboseAsm; }
92 /// hasRawTextSupport - We support EmitRawText.
93 bool hasRawTextSupport() const override { return true; }
95 /// AddComment - Add a comment that can be emitted to the generated .s
96 /// file if applicable as a QoI issue to make the output of the compiler
97 /// more readable. This only affects the MCAsmStreamer, and only when
98 /// verbose assembly output is enabled.
99 void AddComment(const Twine &T) override;
101 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
102 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
104 /// GetCommentOS - Return a raw_ostream that comments can be written to.
105 /// Unlike AddComment, you are required to terminate comments with \n if you
107 raw_ostream &GetCommentOS() override {
109 return nulls(); // Discard comments unless in verbose asm mode.
110 return CommentStream;
113 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
115 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
116 void AddBlankLine() override {
120 /// @name MCStreamer Interface
123 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
125 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
126 void EmitLabel(MCSymbol *Symbol) override;
128 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
129 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
130 void EmitDataRegion(MCDataRegionType Kind) override;
131 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
132 unsigned Update) override;
133 void EmitThumbFunc(MCSymbol *Func) override;
135 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
136 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
137 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
139 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
140 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
141 void EmitCOFFSymbolStorageClass(int StorageClass) override;
142 void EmitCOFFSymbolType(int Type) override;
143 void EndCOFFSymbolDef() override;
144 void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
145 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
146 void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
147 void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) override;
148 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
149 unsigned ByteAlignment) override;
151 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
153 /// @param Symbol - The common symbol to emit.
154 /// @param Size - The size of the common symbol.
155 /// @param ByteAlignment - The alignment of the common symbol in bytes.
156 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
157 unsigned ByteAlignment) override;
159 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
160 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
162 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
163 unsigned ByteAlignment = 0) override;
165 void EmitBytes(StringRef Data) override;
167 void EmitValueImpl(const MCExpr *Value, unsigned Size,
168 SMLoc Loc = SMLoc()) override;
169 void EmitIntValue(uint64_t Value, unsigned Size) override;
171 void EmitULEB128Value(const MCExpr *Value) override;
173 void EmitSLEB128Value(const MCExpr *Value) override;
175 void EmitGPRel64Value(const MCExpr *Value) override;
177 void EmitGPRel32Value(const MCExpr *Value) override;
180 void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
182 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
183 unsigned ValueSize = 1,
184 unsigned MaxBytesToEmit = 0) override;
186 void EmitCodeAlignment(unsigned ByteAlignment,
187 unsigned MaxBytesToEmit = 0) override;
189 void emitValueToOffset(const MCExpr *Offset,
190 unsigned char Value = 0) override;
192 void EmitFileDirective(StringRef Filename) override;
193 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
195 unsigned CUID = 0) override;
196 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
197 unsigned Column, unsigned Flags,
198 unsigned Isa, unsigned Discriminator,
199 StringRef FileName) override;
200 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
202 void EmitIdent(StringRef IdentString) override;
203 void EmitCFISections(bool EH, bool Debug) override;
204 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
205 void EmitCFIDefCfaOffset(int64_t Offset) override;
206 void EmitCFIDefCfaRegister(int64_t Register) override;
207 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
208 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
209 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
210 void EmitCFIRememberState() override;
211 void EmitCFIRestoreState() override;
212 void EmitCFISameValue(int64_t Register) override;
213 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
214 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
215 void EmitCFIEscape(StringRef Values) override;
216 void EmitCFIGnuArgsSize(int64_t Size) override;
217 void EmitCFISignalFrame() override;
218 void EmitCFIUndefined(int64_t Register) override;
219 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
220 void EmitCFIWindowSave() override;
222 void EmitWinCFIStartProc(const MCSymbol *Symbol) override;
223 void EmitWinCFIEndProc() override;
224 void EmitWinCFIStartChained() override;
225 void EmitWinCFIEndChained() override;
226 void EmitWinCFIPushReg(unsigned Register) override;
227 void EmitWinCFISetFrame(unsigned Register, unsigned Offset) override;
228 void EmitWinCFIAllocStack(unsigned Size) override;
229 void EmitWinCFISaveReg(unsigned Register, unsigned Offset) override;
230 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset) override;
231 void EmitWinCFIPushFrame(bool Code) override;
232 void EmitWinCFIEndProlog() override;
234 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) override;
235 void EmitWinEHHandlerData() override;
237 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
239 void EmitBundleAlignMode(unsigned AlignPow2) override;
240 void EmitBundleLock(bool AlignToEnd) override;
241 void EmitBundleUnlock() override;
243 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
244 /// the specified string in the output .s file. This capability is
245 /// indicated by the hasRawTextSupport() predicate.
246 void EmitRawTextImpl(StringRef String) override;
248 void FinishImpl() override;
251 } // end anonymous namespace.
253 /// AddComment - Add a comment that can be emitted to the generated .s
254 /// file if applicable as a QoI issue to make the output of the compiler
255 /// more readable. This only affects the MCAsmStreamer, and only when
256 /// verbose assembly output is enabled.
257 void MCAsmStreamer::AddComment(const Twine &T) {
258 if (!IsVerboseAsm) return;
260 T.toVector(CommentToEmit);
261 // Each comment goes on its own line.
262 CommentToEmit.push_back('\n');
265 void MCAsmStreamer::EmitCommentsAndEOL() {
266 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
271 StringRef Comments = CommentToEmit;
273 assert(Comments.back() == '\n' &&
274 "Comment array not newline terminated");
276 // Emit a line of comments.
277 OS.PadToColumn(MAI->getCommentColumn());
278 size_t Position = Comments.find('\n');
279 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
281 Comments = Comments.substr(Position+1);
282 } while (!Comments.empty());
284 CommentToEmit.clear();
287 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
288 assert(Bytes && "Invalid size!");
289 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
292 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
295 OS << MAI->getCommentString() << T;
299 void MCAsmStreamer::ChangeSection(MCSection *Section,
300 const MCExpr *Subsection) {
301 assert(Section && "Cannot switch to a null section!");
302 Section->PrintSwitchToSection(*MAI, OS, Subsection);
305 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
306 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
307 MCStreamer::EmitLabel(Symbol);
309 Symbol->print(OS, MAI);
310 OS << MAI->getLabelSuffix();
315 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
316 StringRef str = MCLOHIdToName(Kind);
319 int NbArgs = MCLOHIdToNbArgs(Kind);
320 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
321 assert(str != "" && "Invalid LOH name");
324 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
326 for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
331 (*It)->print(OS, MAI);
336 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
338 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
339 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
340 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
341 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
342 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
347 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
348 assert(!Options.empty() && "At least one option is required!");
349 OS << "\t.linker_option \"" << Options[0] << '"';
350 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
351 ie = Options.end(); it != ie; ++it) {
352 OS << ", " << '"' << *it << '"';
357 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
358 if (!MAI->doesSupportDataRegionDirectives())
361 case MCDR_DataRegion: OS << "\t.data_region"; break;
362 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
363 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
364 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
365 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
370 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
371 unsigned Minor, unsigned Update) {
373 case MCVM_WatchOSVersionMin: OS << "\t.watchos_version_min"; break;
374 case MCVM_TvOSVersionMin: OS << "\t.tvos_version_min"; break;
375 case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
376 case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
378 OS << " " << Major << ", " << Minor;
380 OS << ", " << Update;
384 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
385 // This needs to emit to a temporary string to get properly quoted
386 // MCSymbols when they have spaces in them.
387 OS << "\t.thumb_func";
388 // Only Mach-O hasSubsectionsViaSymbols()
389 if (MAI->hasSubsectionsViaSymbols()) {
391 Func->print(OS, MAI);
396 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
397 Symbol->print(OS, MAI);
399 Value->print(OS, MAI);
403 MCStreamer::EmitAssignment(Symbol, Value);
406 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
408 Alias->print(OS, MAI);
410 Symbol->print(OS, MAI);
414 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
415 MCSymbolAttr Attribute) {
417 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
418 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
419 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
420 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
421 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
422 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
423 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
424 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
425 if (!MAI->hasDotTypeDotSizeDirective())
426 return false; // Symbol attribute not supported
428 Symbol->print(OS, MAI);
429 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
431 default: return false;
432 case MCSA_ELF_TypeFunction: OS << "function"; break;
433 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
434 case MCSA_ELF_TypeObject: OS << "object"; break;
435 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
436 case MCSA_ELF_TypeCommon: OS << "common"; break;
437 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
438 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
442 case MCSA_Global: // .globl/.global
443 OS << MAI->getGlobalDirective();
445 case MCSA_Hidden: OS << "\t.hidden\t"; break;
446 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
447 case MCSA_Internal: OS << "\t.internal\t"; break;
448 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
449 case MCSA_Local: OS << "\t.local\t"; break;
450 case MCSA_NoDeadStrip:
451 if (!MAI->hasNoDeadStrip())
453 OS << "\t.no_dead_strip\t";
455 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
456 case MCSA_PrivateExtern:
457 OS << "\t.private_extern\t";
459 case MCSA_Protected: OS << "\t.protected\t"; break;
460 case MCSA_Reference: OS << "\t.reference\t"; break;
461 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
462 case MCSA_WeakDefinition:
463 OS << "\t.weak_definition\t";
466 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
467 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
470 Symbol->print(OS, MAI);
476 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
477 OS << ".desc" << ' ';
478 Symbol->print(OS, MAI);
479 OS << ',' << DescValue;
483 void MCAsmStreamer::EmitSyntaxDirective() {
484 if (MAI->getAssemblerDialect() == 1)
485 OS << "\t.intel_syntax noprefix\n";
486 // FIXME: Currently emit unprefix'ed registers.
487 // The intel_syntax directive has one optional argument
488 // with may have a value of prefix or noprefix.
491 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
493 Symbol->print(OS, MAI);
498 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
499 OS << "\t.scl\t" << StorageClass << ';';
503 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
504 OS << "\t.type\t" << Type << ';';
508 void MCAsmStreamer::EndCOFFSymbolDef() {
513 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
514 OS << "\t.safeseh\t";
515 Symbol->print(OS, MAI);
519 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
521 Symbol->print(OS, MAI);
525 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
526 OS << "\t.secrel32\t";
527 Symbol->print(OS, MAI);
531 void MCAsmStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {
532 assert(MAI->hasDotTypeDotSizeDirective());
534 Symbol->print(OS, MAI);
536 Value->print(OS, MAI);
540 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
541 unsigned ByteAlignment) {
543 Symbol->print(OS, MAI);
546 if (ByteAlignment != 0) {
547 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
548 OS << ',' << ByteAlignment;
550 OS << ',' << Log2_32(ByteAlignment);
555 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
557 /// @param Symbol - The common symbol to emit.
558 /// @param Size - The size of the common symbol.
559 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
560 unsigned ByteAlign) {
562 Symbol->print(OS, MAI);
566 switch (MAI->getLCOMMDirectiveAlignmentType()) {
567 case LCOMM::NoAlignment:
568 llvm_unreachable("alignment not supported on .lcomm!");
569 case LCOMM::ByteAlignment:
570 OS << ',' << ByteAlign;
572 case LCOMM::Log2Alignment:
573 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
574 OS << ',' << Log2_32(ByteAlign);
581 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
582 uint64_t Size, unsigned ByteAlignment) {
584 AssignFragment(Symbol, &Section->getDummyFragment());
586 // Note: a .zerofill directive does not switch sections.
589 // This is a mach-o specific directive.
590 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
591 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
595 Symbol->print(OS, MAI);
597 if (ByteAlignment != 0)
598 OS << ',' << Log2_32(ByteAlignment);
603 // .tbss sym, size, align
604 // This depends that the symbol has already been mangled from the original,
606 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
607 uint64_t Size, unsigned ByteAlignment) {
608 AssignFragment(Symbol, &Section->getDummyFragment());
610 assert(Symbol && "Symbol shouldn't be NULL!");
611 // Instead of using the Section we'll just use the shortcut.
612 // This is a mach-o specific directive and section.
614 Symbol->print(OS, MAI);
617 // Output align if we have it. We default to 1 so don't bother printing
619 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
624 static inline char toOctal(int X) { return (X&7)+'0'; }
626 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
629 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
630 unsigned char C = Data[i];
631 if (C == '"' || C == '\\') {
632 OS << '\\' << (char)C;
636 if (isprint((unsigned char)C)) {
642 case '\b': OS << "\\b"; break;
643 case '\f': OS << "\\f"; break;
644 case '\n': OS << "\\n"; break;
645 case '\r': OS << "\\r"; break;
646 case '\t': OS << "\\t"; break;
649 OS << toOctal(C >> 6);
650 OS << toOctal(C >> 3);
651 OS << toOctal(C >> 0);
659 void MCAsmStreamer::EmitBytes(StringRef Data) {
660 assert(getCurrentSection().first &&
661 "Cannot emit contents before setting section!");
662 if (Data.empty()) return;
664 if (Data.size() == 1) {
665 OS << MAI->getData8bitsDirective();
666 OS << (unsigned)(unsigned char)Data[0];
671 // If the data ends with 0 and the target supports .asciz, use it, otherwise
673 if (MAI->getAscizDirective() && Data.back() == 0) {
674 OS << MAI->getAscizDirective();
675 Data = Data.substr(0, Data.size()-1);
677 OS << MAI->getAsciiDirective();
680 PrintQuotedString(Data, OS);
684 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
685 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
688 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
690 assert(Size <= 8 && "Invalid size");
691 assert(getCurrentSection().first &&
692 "Cannot emit contents before setting section!");
693 const char *Directive = nullptr;
696 case 1: Directive = MAI->getData8bitsDirective(); break;
697 case 2: Directive = MAI->getData16bitsDirective(); break;
698 case 4: Directive = MAI->getData32bitsDirective(); break;
699 case 8: Directive = MAI->getData64bitsDirective(); break;
704 if (!Value->evaluateAsAbsolute(IntValue))
705 report_fatal_error("Don't know how to emit this value.");
707 // We couldn't handle the requested integer size so we fallback by breaking
708 // the request down into several, smaller, integers. Since sizes greater
709 // than eight are invalid and size equivalent to eight should have been
710 // handled earlier, we use four bytes as our largest piece of granularity.
711 bool IsLittleEndian = MAI->isLittleEndian();
712 for (unsigned Emitted = 0; Emitted != Size;) {
713 unsigned Remaining = Size - Emitted;
714 // The size of our partial emission must be a power of two less than
716 unsigned EmissionSize = PowerOf2Floor(Remaining);
717 if (EmissionSize > 4)
719 // Calculate the byte offset of our partial emission taking into account
720 // the endianness of the target.
721 unsigned ByteOffset =
722 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
723 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
724 // We truncate our partial emission to fit within the bounds of the
725 // emission domain. This produces nicer output and silences potential
726 // truncation warnings when round tripping through another assembler.
727 uint64_t Shift = 64 - EmissionSize * 8;
728 assert(Shift < static_cast<uint64_t>(
729 std::numeric_limits<unsigned long long>::digits) &&
730 "undefined behavior");
731 ValueToEmit &= ~0ULL >> Shift;
732 EmitIntValue(ValueToEmit, EmissionSize);
733 Emitted += EmissionSize;
738 assert(Directive && "Invalid size for machine code value!");
740 Value->print(OS, MAI);
744 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
746 if (Value->evaluateAsAbsolute(IntValue)) {
747 EmitULEB128IntValue(IntValue);
751 Value->print(OS, MAI);
755 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
757 if (Value->evaluateAsAbsolute(IntValue)) {
758 EmitSLEB128IntValue(IntValue);
762 Value->print(OS, MAI);
766 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
767 assert(MAI->getGPRel64Directive() != nullptr);
768 OS << MAI->getGPRel64Directive();
769 Value->print(OS, MAI);
773 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
774 assert(MAI->getGPRel32Directive() != nullptr);
775 OS << MAI->getGPRel32Directive();
776 Value->print(OS, MAI);
780 /// EmitFill - Emit NumBytes bytes worth of the value specified by
781 /// FillValue. This implements directives such as '.space'.
782 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
783 if (NumBytes == 0) return;
785 if (const char *ZeroDirective = MAI->getZeroDirective()) {
786 OS << ZeroDirective << NumBytes;
788 OS << ',' << (int)FillValue;
793 // Emit a byte at a time.
794 MCStreamer::EmitFill(NumBytes, FillValue);
797 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
799 unsigned MaxBytesToEmit) {
800 // Some assemblers don't support non-power of two alignments, so we always
801 // emit alignments as a power of two if possible.
802 if (isPowerOf2_32(ByteAlignment)) {
805 llvm_unreachable("Invalid size for machine code value!");
816 llvm_unreachable("Unsupported alignment size!");
819 if (MAI->getAlignmentIsInBytes())
822 OS << Log2_32(ByteAlignment);
824 if (Value || MaxBytesToEmit) {
826 OS.write_hex(truncateToSize(Value, ValueSize));
829 OS << ", " << MaxBytesToEmit;
835 // Non-power of two alignment. This is not widely supported by assemblers.
836 // FIXME: Parameterize this based on MAI.
838 default: llvm_unreachable("Invalid size for machine code value!");
839 case 1: OS << ".balign"; break;
840 case 2: OS << ".balignw"; break;
841 case 4: OS << ".balignl"; break;
842 case 8: llvm_unreachable("Unsupported alignment size!");
845 OS << ' ' << ByteAlignment;
846 OS << ", " << truncateToSize(Value, ValueSize);
848 OS << ", " << MaxBytesToEmit;
852 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
853 unsigned MaxBytesToEmit) {
854 // Emit with a text fill value.
855 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
859 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
860 unsigned char Value) {
861 // FIXME: Verify that Offset is associated with the current section.
863 Offset->print(OS, MAI);
864 OS << ", " << (unsigned)Value;
868 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
869 assert(MAI->hasSingleParameterDotFile());
871 PrintQuotedString(Filename, OS);
875 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
881 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
882 unsigned NumFiles = Table.getMCDwarfFiles().size();
883 FileNo = Table.getFile(Directory, Filename, FileNo);
886 if (NumFiles == Table.getMCDwarfFiles().size())
889 SmallString<128> FullPathName;
891 if (!UseDwarfDirectory && !Directory.empty()) {
892 if (sys::path::is_absolute(Filename))
895 FullPathName = Directory;
896 sys::path::append(FullPathName, Filename);
898 Filename = FullPathName;
902 OS << "\t.file\t" << FileNo << ' ';
903 if (!Directory.empty()) {
904 PrintQuotedString(Directory, OS);
907 PrintQuotedString(Filename, OS);
913 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
914 unsigned Column, unsigned Flags,
916 unsigned Discriminator,
917 StringRef FileName) {
918 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
919 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
920 OS << " basic_block";
921 if (Flags & DWARF2_FLAG_PROLOGUE_END)
922 OS << " prologue_end";
923 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
924 OS << " epilogue_begin";
926 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
927 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
930 if (Flags & DWARF2_FLAG_IS_STMT)
937 OS << " isa " << Isa;
939 OS << " discriminator " << Discriminator;
942 OS.PadToColumn(MAI->getCommentColumn());
943 OS << MAI->getCommentString() << ' ' << FileName << ':'
944 << Line << ':' << Column;
947 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
948 Isa, Discriminator, FileName);
951 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
952 // Always use the zeroth line table, since asm syntax only supports one line
954 return MCStreamer::getDwarfLineTableSymbol(0);
957 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
958 assert(MAI->hasIdentDirective() && ".ident directive not supported");
960 PrintQuotedString(IdentString, OS);
964 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
965 MCStreamer::EmitCFISections(EH, Debug);
966 OS << "\t.cfi_sections ";
970 OS << ", .debug_frame";
972 OS << ".debug_frame";
978 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
979 OS << "\t.cfi_startproc";
985 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
986 MCStreamer::EmitCFIEndProcImpl(Frame);
987 OS << "\t.cfi_endproc";
991 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
992 if (!MAI->useDwarfRegNumForCFI()) {
993 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
994 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
995 InstPrinter->printRegName(OS, LLVMRegister);
1001 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1002 MCStreamer::EmitCFIDefCfa(Register, Offset);
1003 OS << "\t.cfi_def_cfa ";
1004 EmitRegisterName(Register);
1005 OS << ", " << Offset;
1009 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1010 MCStreamer::EmitCFIDefCfaOffset(Offset);
1011 OS << "\t.cfi_def_cfa_offset " << Offset;
1015 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1016 OS << "\t.cfi_escape ";
1017 if (!Values.empty()) {
1018 size_t e = Values.size() - 1;
1019 for (size_t i = 0; i < e; ++i)
1020 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1021 OS << format("0x%02x", uint8_t(Values[e]));
1025 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1026 MCStreamer::EmitCFIEscape(Values);
1027 PrintCFIEscape(OS, Values);
1031 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1032 MCStreamer::EmitCFIGnuArgsSize(Size);
1034 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1035 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1037 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1041 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1042 MCStreamer::EmitCFIDefCfaRegister(Register);
1043 OS << "\t.cfi_def_cfa_register ";
1044 EmitRegisterName(Register);
1048 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1049 this->MCStreamer::EmitCFIOffset(Register, Offset);
1050 OS << "\t.cfi_offset ";
1051 EmitRegisterName(Register);
1052 OS << ", " << Offset;
1056 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1057 unsigned Encoding) {
1058 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1059 OS << "\t.cfi_personality " << Encoding << ", ";
1060 Sym->print(OS, MAI);
1064 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1065 MCStreamer::EmitCFILsda(Sym, Encoding);
1066 OS << "\t.cfi_lsda " << Encoding << ", ";
1067 Sym->print(OS, MAI);
1071 void MCAsmStreamer::EmitCFIRememberState() {
1072 MCStreamer::EmitCFIRememberState();
1073 OS << "\t.cfi_remember_state";
1077 void MCAsmStreamer::EmitCFIRestoreState() {
1078 MCStreamer::EmitCFIRestoreState();
1079 OS << "\t.cfi_restore_state";
1083 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1084 MCStreamer::EmitCFISameValue(Register);
1085 OS << "\t.cfi_same_value ";
1086 EmitRegisterName(Register);
1090 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1091 MCStreamer::EmitCFIRelOffset(Register, Offset);
1092 OS << "\t.cfi_rel_offset ";
1093 EmitRegisterName(Register);
1094 OS << ", " << Offset;
1098 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1099 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1100 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1104 void MCAsmStreamer::EmitCFISignalFrame() {
1105 MCStreamer::EmitCFISignalFrame();
1106 OS << "\t.cfi_signal_frame";
1110 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1111 MCStreamer::EmitCFIUndefined(Register);
1112 OS << "\t.cfi_undefined " << Register;
1116 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1117 MCStreamer::EmitCFIRegister(Register1, Register2);
1118 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1122 void MCAsmStreamer::EmitCFIWindowSave() {
1123 MCStreamer::EmitCFIWindowSave();
1124 OS << "\t.cfi_window_save";
1128 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) {
1129 MCStreamer::EmitWinCFIStartProc(Symbol);
1132 Symbol->print(OS, MAI);
1136 void MCAsmStreamer::EmitWinCFIEndProc() {
1137 MCStreamer::EmitWinCFIEndProc();
1139 OS << "\t.seh_endproc";
1143 void MCAsmStreamer::EmitWinCFIStartChained() {
1144 MCStreamer::EmitWinCFIStartChained();
1146 OS << "\t.seh_startchained";
1150 void MCAsmStreamer::EmitWinCFIEndChained() {
1151 MCStreamer::EmitWinCFIEndChained();
1153 OS << "\t.seh_endchained";
1157 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1159 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except);
1161 OS << "\t.seh_handler ";
1162 Sym->print(OS, MAI);
1170 void MCAsmStreamer::EmitWinEHHandlerData() {
1171 MCStreamer::EmitWinEHHandlerData();
1173 // Switch sections. Don't call SwitchSection directly, because that will
1174 // cause the section switch to be visible in the emitted assembly.
1175 // We only do this so the section switch that terminates the handler
1176 // data block is visible.
1177 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1179 WinEH::UnwindEmitter::getXDataSection(CurFrame->Function, getContext());
1180 SwitchSectionNoChange(XData);
1182 OS << "\t.seh_handlerdata";
1186 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register) {
1187 MCStreamer::EmitWinCFIPushReg(Register);
1189 OS << "\t.seh_pushreg " << Register;
1193 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) {
1194 MCStreamer::EmitWinCFISetFrame(Register, Offset);
1196 OS << "\t.seh_setframe " << Register << ", " << Offset;
1200 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size) {
1201 MCStreamer::EmitWinCFIAllocStack(Size);
1203 OS << "\t.seh_stackalloc " << Size;
1207 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) {
1208 MCStreamer::EmitWinCFISaveReg(Register, Offset);
1210 OS << "\t.seh_savereg " << Register << ", " << Offset;
1214 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) {
1215 MCStreamer::EmitWinCFISaveXMM(Register, Offset);
1217 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1221 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code) {
1222 MCStreamer::EmitWinCFIPushFrame(Code);
1224 OS << "\t.seh_pushframe";
1230 void MCAsmStreamer::EmitWinCFIEndProlog() {
1231 MCStreamer::EmitWinCFIEndProlog();
1233 OS << "\t.seh_endprologue";
1237 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1238 const MCSubtargetInfo &STI) {
1239 raw_ostream &OS = GetCommentOS();
1240 SmallString<256> Code;
1241 SmallVector<MCFixup, 4> Fixups;
1242 raw_svector_ostream VecOS(Code);
1243 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1245 // If we are showing fixups, create symbolic markers in the encoded
1246 // representation. We do this by making a per-bit map to the fixup item index,
1247 // then trying to display it as nicely as possible.
1248 SmallVector<uint8_t, 64> FixupMap;
1249 FixupMap.resize(Code.size() * 8);
1250 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1253 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1254 MCFixup &F = Fixups[i];
1255 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1256 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1257 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1258 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1259 FixupMap[Index] = 1 + i;
1263 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1264 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1265 OS << "encoding: [";
1266 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1270 // See if all bits are the same map entry.
1271 uint8_t MapEntry = FixupMap[i * 8 + 0];
1272 for (unsigned j = 1; j != 8; ++j) {
1273 if (FixupMap[i * 8 + j] == MapEntry)
1276 MapEntry = uint8_t(~0U);
1280 if (MapEntry != uint8_t(~0U)) {
1281 if (MapEntry == 0) {
1282 OS << format("0x%02x", uint8_t(Code[i]));
1285 // FIXME: Some of the 8 bits require fix up.
1286 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1287 << char('A' + MapEntry - 1) << '\'';
1289 OS << char('A' + MapEntry - 1);
1292 // Otherwise, write out in binary.
1294 for (unsigned j = 8; j--;) {
1295 unsigned Bit = (Code[i] >> j) & 1;
1298 if (MAI->isLittleEndian())
1299 FixupBit = i * 8 + j;
1301 FixupBit = i * 8 + (7-j);
1303 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1304 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1305 OS << char('A' + MapEntry - 1);
1313 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1314 MCFixup &F = Fixups[i];
1315 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1316 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1317 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1321 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1322 assert(getCurrentSection().first &&
1323 "Cannot emit contents before setting section!");
1325 // Show the encoding in a comment if we have a code emitter.
1327 AddEncodingComment(Inst, STI);
1329 // Show the MCInst if enabled.
1331 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1332 GetCommentOS() << "\n";
1335 if(getTargetStreamer())
1336 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1338 InstPrinter->printInst(&Inst, OS, "", STI);
1343 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1344 OS << "\t.bundle_align_mode " << AlignPow2;
1348 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1349 OS << "\t.bundle_lock";
1351 OS << " align_to_end";
1355 void MCAsmStreamer::EmitBundleUnlock() {
1356 OS << "\t.bundle_unlock";
1360 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1361 /// the specified string in the output .s file. This capability is
1362 /// indicated by the hasRawTextSupport() predicate.
1363 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1364 if (!String.empty() && String.back() == '\n')
1365 String = String.substr(0, String.size()-1);
1370 void MCAsmStreamer::FinishImpl() {
1371 // If we are generating dwarf for assembly source files dump out the sections.
1372 if (getContext().getGenDwarfForAssembly())
1373 MCGenDwarfInfo::Emit(this);
1375 // Emit the label for the line table, if requested - since the rest of the
1376 // line table will be defined by .loc/.file directives, and not emitted
1377 // directly, the label is the only work required here.
1378 auto &Tables = getContext().getMCDwarfLineTables();
1379 if (!Tables.empty()) {
1380 assert(Tables.size() == 1 && "asm output only supports one line table");
1381 if (auto *Label = Tables.begin()->second.getLabel()) {
1382 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1388 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1389 std::unique_ptr<formatted_raw_ostream> OS,
1390 bool isVerboseAsm, bool useDwarfDirectory,
1391 MCInstPrinter *IP, MCCodeEmitter *CE,
1392 MCAsmBackend *MAB, bool ShowInst) {
1393 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1394 useDwarfDirectory, IP, CE, MAB, ShowInst);