1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output --------------------===//
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/SmallString.h"
12 #include "llvm/ADT/STLExtras.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/MCSymbol.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/MathExtras.h"
33 #include "llvm/Support/Path.h"
35 #include <unordered_map>
40 class MCAsmStreamer : public MCStreamer {
42 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 enum EHSymbolFlags { EHGlobal = 1,
57 EHWeakDefinition = 1 << 1,
58 EHPrivateExtern = 1 << 2 };
59 DenseMap<const MCSymbol*, unsigned> FlagMap;
61 void EmitRegisterName(int64_t Register);
62 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
63 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
66 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
67 bool isVerboseAsm, bool useDwarfDirectory,
68 MCInstPrinter *printer, MCCodeEmitter *emitter,
69 MCAsmBackend *asmbackend, bool showInst)
70 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
71 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
72 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
73 ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
74 if (InstPrinter && IsVerboseAsm)
75 InstPrinter->setCommentStream(CommentStream);
78 inline void EmitEOL() {
79 // If we don't have any comments, just emit a \n.
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(const MCSection *Section,
124 const MCExpr *Subsection) override;
126 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
127 void EmitLabel(MCSymbol *Symbol) override;
128 void EmitDebugLabel(MCSymbol *Symbol) override;
130 void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
131 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
132 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
133 void EmitDataRegion(MCDataRegionType Kind) override;
134 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
135 unsigned Update) override;
136 void EmitThumbFunc(MCSymbol *Func) override;
138 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
139 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
140 void EmitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
141 const MCSymbol *Label,
142 unsigned PointerSize) override;
143 void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
144 const MCSymbol *Label) override;
146 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
148 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
149 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
150 void EmitCOFFSymbolStorageClass(int StorageClass) override;
151 void EmitCOFFSymbolType(int Type) override;
152 void EndCOFFSymbolDef() override;
153 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
154 void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
155 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
156 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
157 unsigned ByteAlignment) override;
159 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
161 /// @param Symbol - The common symbol to emit.
162 /// @param Size - The size of the common symbol.
163 /// @param ByteAlignment - The alignment of the common symbol in bytes.
164 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
165 unsigned ByteAlignment) override;
167 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = nullptr,
168 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
170 void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
171 uint64_t Size, unsigned ByteAlignment = 0) override;
173 void EmitBytes(StringRef Data) override;
175 void EmitValueImpl(const MCExpr *Value, unsigned Size,
176 const SMLoc &Loc = SMLoc()) override;
177 void EmitIntValue(uint64_t Value, unsigned Size) override;
179 void EmitULEB128Value(const MCExpr *Value) override;
181 void EmitSLEB128Value(const MCExpr *Value) override;
183 void EmitGPRel64Value(const MCExpr *Value) override;
185 void EmitGPRel32Value(const MCExpr *Value) override;
188 void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
190 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
191 unsigned ValueSize = 1,
192 unsigned MaxBytesToEmit = 0) override;
194 void EmitCodeAlignment(unsigned ByteAlignment,
195 unsigned MaxBytesToEmit = 0) override;
197 bool EmitValueToOffset(const MCExpr *Offset,
198 unsigned char Value = 0) override;
200 void EmitFileDirective(StringRef Filename) override;
201 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
203 unsigned CUID = 0) override;
204 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
205 unsigned Column, unsigned Flags,
206 unsigned Isa, unsigned Discriminator,
207 StringRef FileName) override;
208 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
210 void EmitIdent(StringRef IdentString) override;
211 void EmitCFISections(bool EH, bool Debug) override;
212 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
213 void EmitCFIDefCfaOffset(int64_t Offset) override;
214 void EmitCFIDefCfaRegister(int64_t Register) override;
215 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
216 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
217 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
218 void EmitCFIRememberState() override;
219 void EmitCFIRestoreState() override;
220 void EmitCFISameValue(int64_t Register) override;
221 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
222 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
223 void EmitCFISignalFrame() override;
224 void EmitCFIUndefined(int64_t Register) override;
225 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
226 void EmitCFIWindowSave() override;
228 void EmitWin64EHStartProc(const MCSymbol *Symbol) override;
229 void EmitWin64EHEndProc() override;
230 void EmitWin64EHStartChained() override;
231 void EmitWin64EHEndChained() override;
232 void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
233 bool Except) override;
234 void EmitWin64EHHandlerData() override;
235 void EmitWin64EHPushReg(unsigned Register) override;
236 void EmitWin64EHSetFrame(unsigned Register, unsigned Offset) override;
237 void EmitWin64EHAllocStack(unsigned Size) override;
238 void EmitWin64EHSaveReg(unsigned Register, unsigned Offset) override;
239 void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) override;
240 void EmitWin64EHPushFrame(bool Code) override;
241 void EmitWin64EHEndProlog() override;
243 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
245 void EmitBundleAlignMode(unsigned AlignPow2) override;
246 void EmitBundleLock(bool AlignToEnd) override;
247 void EmitBundleUnlock() override;
249 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
250 /// the specified string in the output .s file. This capability is
251 /// indicated by the hasRawTextSupport() predicate.
252 void EmitRawTextImpl(StringRef String) override;
254 void FinishImpl() override;
257 } // end anonymous namespace.
259 /// AddComment - Add a comment that can be emitted to the generated .s
260 /// file if applicable as a QoI issue to make the output of the compiler
261 /// more readable. This only affects the MCAsmStreamer, and only when
262 /// verbose assembly output is enabled.
263 void MCAsmStreamer::AddComment(const Twine &T) {
264 if (!IsVerboseAsm) return;
266 // Make sure that CommentStream is flushed.
267 CommentStream.flush();
269 T.toVector(CommentToEmit);
270 // Each comment goes on its own line.
271 CommentToEmit.push_back('\n');
273 // Tell the comment stream that the vector changed underneath it.
274 CommentStream.resync();
277 void MCAsmStreamer::EmitCommentsAndEOL() {
278 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
283 CommentStream.flush();
284 StringRef Comments = CommentToEmit.str();
286 assert(Comments.back() == '\n' &&
287 "Comment array not newline terminated");
289 // Emit a line of comments.
290 OS.PadToColumn(MAI->getCommentColumn());
291 size_t Position = Comments.find('\n');
292 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
294 Comments = Comments.substr(Position+1);
295 } while (!Comments.empty());
297 CommentToEmit.clear();
298 // Tell the comment stream that the vector changed underneath it.
299 CommentStream.resync();
302 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
303 assert(Bytes && "Invalid size!");
304 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
307 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
310 OS << MAI->getCommentString() << T;
314 void MCAsmStreamer::ChangeSection(const MCSection *Section,
315 const MCExpr *Subsection) {
316 assert(Section && "Cannot switch to a null section!");
317 Section->PrintSwitchToSection(*MAI, OS, Subsection);
320 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
321 MCSymbol *EHSymbol) {
324 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
325 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
326 MCStreamer::EmitLabel(Symbol);
328 OS << *Symbol << MAI->getLabelSuffix();
332 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
333 StringRef str = MCLOHIdToName(Kind);
336 int NbArgs = MCLOHIdToNbArgs(Kind);
337 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
338 assert(str != "" && "Invalid LOH name");
341 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
343 for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
353 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
354 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
355 MCStreamer::EmitDebugLabel(Symbol);
357 OS << *Symbol << MAI->getDebugLabelSuffix();
361 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
363 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
364 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
365 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
366 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
367 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
372 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
373 assert(!Options.empty() && "At least one option is required!");
374 OS << "\t.linker_option \"" << Options[0] << '"';
375 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
376 ie = Options.end(); it != ie; ++it) {
377 OS << ", " << '"' << *it << '"';
382 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
383 if (!MAI->doesSupportDataRegionDirectives())
386 case MCDR_DataRegion: OS << "\t.data_region"; break;
387 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
388 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
389 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
390 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
395 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
396 unsigned Minor, unsigned Update) {
398 case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
399 case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
401 OS << " " << Major << ", " << Minor;
403 OS << ", " << Update;
407 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
408 // This needs to emit to a temporary string to get properly quoted
409 // MCSymbols when they have spaces in them.
410 OS << "\t.thumb_func";
411 // Only Mach-O hasSubsectionsViaSymbols()
412 if (MAI->hasSubsectionsViaSymbols())
417 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
418 OS << *Symbol << " = " << *Value;
421 MCStreamer::EmitAssignment(Symbol, Value);
424 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
425 OS << ".weakref " << *Alias << ", " << *Symbol;
429 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
430 const MCSymbol *LastLabel,
431 const MCSymbol *Label,
432 unsigned PointerSize) {
433 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
436 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
437 const MCSymbol *Label) {
438 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
439 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
440 AddrDelta = ForceExpAbs(AddrDelta);
441 EmitValue(AddrDelta, 4);
445 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
446 MCSymbolAttr Attribute) {
448 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
449 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
450 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
451 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
452 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
453 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
454 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
455 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
456 if (!MAI->hasDotTypeDotSizeDirective())
457 return false; // Symbol attribute not supported
458 OS << "\t.type\t" << *Symbol << ','
459 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
461 default: return false;
462 case MCSA_ELF_TypeFunction: OS << "function"; break;
463 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
464 case MCSA_ELF_TypeObject: OS << "object"; break;
465 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
466 case MCSA_ELF_TypeCommon: OS << "common"; break;
467 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
468 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
472 case MCSA_Global: // .globl/.global
473 OS << MAI->getGlobalDirective();
474 FlagMap[Symbol] |= EHGlobal;
476 case MCSA_Hidden: OS << "\t.hidden\t"; break;
477 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
478 case MCSA_Internal: OS << "\t.internal\t"; break;
479 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
480 case MCSA_Local: OS << "\t.local\t"; break;
481 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
482 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
483 case MCSA_PrivateExtern:
484 OS << "\t.private_extern\t";
485 FlagMap[Symbol] |= EHPrivateExtern;
487 case MCSA_Protected: OS << "\t.protected\t"; break;
488 case MCSA_Reference: OS << "\t.reference\t"; break;
489 case MCSA_Weak: OS << "\t.weak\t"; break;
490 case MCSA_WeakDefinition:
491 OS << "\t.weak_definition\t";
492 FlagMap[Symbol] |= EHWeakDefinition;
495 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
496 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
505 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
506 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
510 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
511 OS << "\t.def\t " << *Symbol << ';';
515 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
516 OS << "\t.scl\t" << StorageClass << ';';
520 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
521 OS << "\t.type\t" << Type << ';';
525 void MCAsmStreamer::EndCOFFSymbolDef() {
530 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
531 OS << "\t.secidx\t" << *Symbol;
535 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
536 OS << "\t.secrel32\t" << *Symbol;
540 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
541 assert(MAI->hasDotTypeDotSizeDirective());
542 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
545 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
546 unsigned ByteAlignment) {
547 // Common symbols do not belong to any actual section.
548 AssignSection(Symbol, nullptr);
550 OS << "\t.comm\t" << *Symbol << ',' << Size;
551 if (ByteAlignment != 0) {
552 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
553 OS << ',' << ByteAlignment;
555 OS << ',' << Log2_32(ByteAlignment);
560 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
562 /// @param Symbol - The common symbol to emit.
563 /// @param Size - The size of the common symbol.
564 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
565 unsigned ByteAlign) {
566 // Common symbols do not belong to any actual section.
567 AssignSection(Symbol, nullptr);
569 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
571 switch (MAI->getLCOMMDirectiveAlignmentType()) {
572 case LCOMM::NoAlignment:
573 llvm_unreachable("alignment not supported on .lcomm!");
574 case LCOMM::ByteAlignment:
575 OS << ',' << ByteAlign;
577 case LCOMM::Log2Alignment:
578 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
579 OS << ',' << Log2_32(ByteAlign);
586 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
587 uint64_t Size, unsigned ByteAlignment) {
589 AssignSection(Symbol, Section);
591 // Note: a .zerofill directive does not switch sections.
594 // This is a mach-o specific directive.
595 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
596 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
599 OS << ',' << *Symbol << ',' << Size;
600 if (ByteAlignment != 0)
601 OS << ',' << Log2_32(ByteAlignment);
606 // .tbss sym, size, align
607 // This depends that the symbol has already been mangled from the original,
609 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
610 uint64_t Size, unsigned ByteAlignment) {
611 AssignSection(Symbol, Section);
613 assert(Symbol && "Symbol shouldn't be NULL!");
614 // Instead of using the Section we'll just use the shortcut.
615 // This is a mach-o specific directive and section.
616 OS << ".tbss " << *Symbol << ", " << Size;
618 // Output align if we have it. We default to 1 so don't bother printing
620 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
625 static inline char toOctal(int X) { return (X&7)+'0'; }
627 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
630 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
631 unsigned char C = Data[i];
632 if (C == '"' || C == '\\') {
633 OS << '\\' << (char)C;
637 if (isprint((unsigned char)C)) {
643 case '\b': OS << "\\b"; break;
644 case '\f': OS << "\\f"; break;
645 case '\n': OS << "\\n"; break;
646 case '\r': OS << "\\r"; break;
647 case '\t': OS << "\\t"; break;
650 OS << toOctal(C >> 6);
651 OS << toOctal(C >> 3);
652 OS << toOctal(C >> 0);
661 void MCAsmStreamer::EmitBytes(StringRef Data) {
662 assert(getCurrentSection().first &&
663 "Cannot emit contents before setting section!");
664 if (Data.empty()) return;
666 if (Data.size() == 1) {
667 OS << MAI->getData8bitsDirective();
668 OS << (unsigned)(unsigned char)Data[0];
673 // If the data ends with 0 and the target supports .asciz, use it, otherwise
675 if (MAI->getAscizDirective() && Data.back() == 0) {
676 OS << MAI->getAscizDirective();
677 Data = Data.substr(0, Data.size()-1);
679 OS << MAI->getAsciiDirective();
682 PrintQuotedString(Data, OS);
686 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
687 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
690 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
692 assert(Size <= 8 && "Invalid size");
693 assert(getCurrentSection().first &&
694 "Cannot emit contents before setting section!");
695 const char *Directive = nullptr;
698 case 1: Directive = MAI->getData8bitsDirective(); break;
699 case 2: Directive = MAI->getData16bitsDirective(); break;
700 case 4: Directive = MAI->getData32bitsDirective(); break;
701 case 8: Directive = MAI->getData64bitsDirective(); break;
706 if (!Value->EvaluateAsAbsolute(IntValue))
707 report_fatal_error("Don't know how to emit this value.");
709 // We couldn't handle the requested integer size so we fallback by breaking
710 // the request down into several, smaller, integers. Since sizes greater
711 // than eight are invalid and size equivalent to eight should have been
712 // handled earlier, we use four bytes as our largest piece of granularity.
713 bool IsLittleEndian = MAI->isLittleEndian();
714 for (unsigned Emitted = 0; Emitted != Size;) {
715 unsigned Remaining = Size - Emitted;
716 // The size of our partial emission must be a power of two less than
718 unsigned EmissionSize = PowerOf2Floor(Remaining);
719 if (EmissionSize > 4)
721 // Calculate the byte offset of our partial emission taking into account
722 // the endianness of the target.
723 unsigned ByteOffset =
724 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
725 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
726 // We truncate our partial emission to fit within the bounds of the
727 // emission domain. This produces nicer output and silences potential
728 // truncation warnings when round tripping through another assembler.
729 ValueToEmit &= ~0ULL >> (64 - EmissionSize * 8);
730 EmitIntValue(ValueToEmit, EmissionSize);
731 Emitted += EmissionSize;
736 assert(Directive && "Invalid size for machine code value!");
737 OS << Directive << *Value;
741 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
743 if (Value->EvaluateAsAbsolute(IntValue)) {
744 EmitULEB128IntValue(IntValue);
747 assert(MAI->hasLEB128() && "Cannot print a .uleb");
748 OS << ".uleb128 " << *Value;
752 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
754 if (Value->EvaluateAsAbsolute(IntValue)) {
755 EmitSLEB128IntValue(IntValue);
758 assert(MAI->hasLEB128() && "Cannot print a .sleb");
759 OS << ".sleb128 " << *Value;
763 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
764 assert(MAI->getGPRel64Directive() != nullptr);
765 OS << MAI->getGPRel64Directive() << *Value;
769 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
770 assert(MAI->getGPRel32Directive() != nullptr);
771 OS << MAI->getGPRel32Directive() << *Value;
776 /// EmitFill - Emit NumBytes bytes worth of the value specified by
777 /// FillValue. This implements directives such as '.space'.
778 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
779 if (NumBytes == 0) return;
781 if (const char *ZeroDirective = MAI->getZeroDirective()) {
782 OS << ZeroDirective << NumBytes;
784 OS << ',' << (int)FillValue;
789 // Emit a byte at a time.
790 MCStreamer::EmitFill(NumBytes, FillValue);
793 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
795 unsigned MaxBytesToEmit) {
796 // Some assemblers don't support non-power of two alignments, so we always
797 // emit alignments as a power of two if possible.
798 if (isPowerOf2_32(ByteAlignment)) {
801 llvm_unreachable("Invalid size for machine code value!");
812 llvm_unreachable("Unsupported alignment size!");
815 if (MAI->getAlignmentIsInBytes())
818 OS << Log2_32(ByteAlignment);
820 if (Value || MaxBytesToEmit) {
822 OS.write_hex(truncateToSize(Value, ValueSize));
825 OS << ", " << MaxBytesToEmit;
831 // Non-power of two alignment. This is not widely supported by assemblers.
832 // FIXME: Parameterize this based on MAI.
834 default: llvm_unreachable("Invalid size for machine code value!");
835 case 1: OS << ".balign"; break;
836 case 2: OS << ".balignw"; break;
837 case 4: OS << ".balignl"; break;
838 case 8: llvm_unreachable("Unsupported alignment size!");
841 OS << ' ' << ByteAlignment;
842 OS << ", " << truncateToSize(Value, ValueSize);
844 OS << ", " << MaxBytesToEmit;
848 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
849 unsigned MaxBytesToEmit) {
850 // Emit with a text fill value.
851 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
855 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
856 unsigned char Value) {
857 // FIXME: Verify that Offset is associated with the current section.
858 OS << ".org " << *Offset << ", " << (unsigned) Value;
864 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
865 assert(MAI->hasSingleParameterDotFile());
867 PrintQuotedString(Filename, OS);
871 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
877 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
878 unsigned NumFiles = Table.getMCDwarfFiles().size();
879 FileNo = Table.getFile(Directory, Filename, FileNo);
882 if (NumFiles == Table.getMCDwarfFiles().size())
885 SmallString<128> FullPathName;
887 if (!UseDwarfDirectory && !Directory.empty()) {
888 if (sys::path::is_absolute(Filename))
891 FullPathName = Directory;
892 sys::path::append(FullPathName, Filename);
894 Filename = FullPathName;
898 OS << "\t.file\t" << FileNo << ' ';
899 if (!Directory.empty()) {
900 PrintQuotedString(Directory, OS);
903 PrintQuotedString(Filename, OS);
909 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
910 unsigned Column, unsigned Flags,
912 unsigned Discriminator,
913 StringRef FileName) {
914 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
915 Isa, Discriminator, FileName);
916 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
917 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
918 OS << " basic_block";
919 if (Flags & DWARF2_FLAG_PROLOGUE_END)
920 OS << " prologue_end";
921 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
922 OS << " epilogue_begin";
924 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
925 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
928 if (Flags & DWARF2_FLAG_IS_STMT)
935 OS << " isa " << Isa;
937 OS << " discriminator " << Discriminator;
940 OS.PadToColumn(MAI->getCommentColumn());
941 OS << MAI->getCommentString() << ' ' << FileName << ':'
942 << Line << ':' << Column;
947 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
948 // Always use the zeroth line table, since asm syntax only supports one line
950 return MCStreamer::getDwarfLineTableSymbol(0);
953 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
954 assert(MAI->hasIdentDirective() && ".ident directive not supported");
956 PrintQuotedString(IdentString, OS);
960 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
961 MCStreamer::EmitCFISections(EH, Debug);
962 OS << "\t.cfi_sections ";
966 OS << ", .debug_frame";
968 OS << ".debug_frame";
974 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
975 OS << "\t.cfi_startproc";
981 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
982 // Put a dummy non-null value in Frame.End to mark that this frame has been
984 Frame.End = (MCSymbol *) 1;
986 OS << "\t.cfi_endproc";
990 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
991 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
992 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
993 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
994 InstPrinter->printRegName(OS, LLVMRegister);
1000 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1001 MCStreamer::EmitCFIDefCfa(Register, Offset);
1002 OS << "\t.cfi_def_cfa ";
1003 EmitRegisterName(Register);
1004 OS << ", " << Offset;
1008 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1009 MCStreamer::EmitCFIDefCfaOffset(Offset);
1010 OS << "\t.cfi_def_cfa_offset " << Offset;
1014 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1015 MCStreamer::EmitCFIDefCfaRegister(Register);
1016 OS << "\t.cfi_def_cfa_register ";
1017 EmitRegisterName(Register);
1021 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1022 this->MCStreamer::EmitCFIOffset(Register, Offset);
1023 OS << "\t.cfi_offset ";
1024 EmitRegisterName(Register);
1025 OS << ", " << Offset;
1029 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1030 unsigned Encoding) {
1031 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1032 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1036 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1037 MCStreamer::EmitCFILsda(Sym, Encoding);
1038 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1042 void MCAsmStreamer::EmitCFIRememberState() {
1043 MCStreamer::EmitCFIRememberState();
1044 OS << "\t.cfi_remember_state";
1048 void MCAsmStreamer::EmitCFIRestoreState() {
1049 MCStreamer::EmitCFIRestoreState();
1050 OS << "\t.cfi_restore_state";
1054 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1055 MCStreamer::EmitCFISameValue(Register);
1056 OS << "\t.cfi_same_value ";
1057 EmitRegisterName(Register);
1061 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1062 MCStreamer::EmitCFIRelOffset(Register, Offset);
1063 OS << "\t.cfi_rel_offset ";
1064 EmitRegisterName(Register);
1065 OS << ", " << Offset;
1069 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1070 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1071 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1075 void MCAsmStreamer::EmitCFISignalFrame() {
1076 MCStreamer::EmitCFISignalFrame();
1077 OS << "\t.cfi_signal_frame";
1081 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1082 MCStreamer::EmitCFIUndefined(Register);
1083 OS << "\t.cfi_undefined " << Register;
1087 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1088 MCStreamer::EmitCFIRegister(Register1, Register2);
1089 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1093 void MCAsmStreamer::EmitCFIWindowSave() {
1094 MCStreamer::EmitCFIWindowSave();
1095 OS << "\t.cfi_window_save";
1099 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1100 MCStreamer::EmitWin64EHStartProc(Symbol);
1102 OS << ".seh_proc " << *Symbol;
1106 void MCAsmStreamer::EmitWin64EHEndProc() {
1107 MCStreamer::EmitWin64EHEndProc();
1109 OS << "\t.seh_endproc";
1113 void MCAsmStreamer::EmitWin64EHStartChained() {
1114 MCStreamer::EmitWin64EHStartChained();
1116 OS << "\t.seh_startchained";
1120 void MCAsmStreamer::EmitWin64EHEndChained() {
1121 MCStreamer::EmitWin64EHEndChained();
1123 OS << "\t.seh_endchained";
1127 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1129 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1131 OS << "\t.seh_handler " << *Sym;
1139 static const MCSection *getWin64EHTableSection(StringRef suffix,
1140 MCContext &context) {
1141 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1142 /// this duplicate code in MCWin64EH.cpp.
1144 return context.getObjectFileInfo()->getXDataSection();
1145 return context.getCOFFSection((".xdata"+suffix).str(),
1146 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1147 COFF::IMAGE_SCN_MEM_READ |
1148 COFF::IMAGE_SCN_MEM_WRITE,
1149 SectionKind::getDataRel());
1152 void MCAsmStreamer::EmitWin64EHHandlerData() {
1153 MCStreamer::EmitWin64EHHandlerData();
1155 // Switch sections. Don't call SwitchSection directly, because that will
1156 // cause the section switch to be visible in the emitted assembly.
1157 // We only do this so the section switch that terminates the handler
1158 // data block is visible.
1159 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1160 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1161 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1163 SwitchSectionNoChange(xdataSect);
1165 OS << "\t.seh_handlerdata";
1169 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1170 MCStreamer::EmitWin64EHPushReg(Register);
1172 OS << "\t.seh_pushreg ";
1173 EmitRegisterName(Register);
1177 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1178 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1180 OS << "\t.seh_setframe ";
1181 EmitRegisterName(Register);
1182 OS << ", " << Offset;
1186 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1187 MCStreamer::EmitWin64EHAllocStack(Size);
1189 OS << "\t.seh_stackalloc " << Size;
1193 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1194 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1196 OS << "\t.seh_savereg ";
1197 EmitRegisterName(Register);
1198 OS << ", " << Offset;
1202 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1203 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1205 OS << "\t.seh_savexmm ";
1206 EmitRegisterName(Register);
1207 OS << ", " << Offset;
1211 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1212 MCStreamer::EmitWin64EHPushFrame(Code);
1214 OS << "\t.seh_pushframe";
1220 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1221 MCStreamer::EmitWin64EHEndProlog();
1223 OS << "\t.seh_endprologue";
1227 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1228 const MCSubtargetInfo &STI) {
1229 raw_ostream &OS = GetCommentOS();
1230 SmallString<256> Code;
1231 SmallVector<MCFixup, 4> Fixups;
1232 raw_svector_ostream VecOS(Code);
1233 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1236 // If we are showing fixups, create symbolic markers in the encoded
1237 // representation. We do this by making a per-bit map to the fixup item index,
1238 // then trying to display it as nicely as possible.
1239 SmallVector<uint8_t, 64> FixupMap;
1240 FixupMap.resize(Code.size() * 8);
1241 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1244 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1245 MCFixup &F = Fixups[i];
1246 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1247 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1248 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1249 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1250 FixupMap[Index] = 1 + i;
1254 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1255 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1256 OS << "encoding: [";
1257 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1261 // See if all bits are the same map entry.
1262 uint8_t MapEntry = FixupMap[i * 8 + 0];
1263 for (unsigned j = 1; j != 8; ++j) {
1264 if (FixupMap[i * 8 + j] == MapEntry)
1267 MapEntry = uint8_t(~0U);
1271 if (MapEntry != uint8_t(~0U)) {
1272 if (MapEntry == 0) {
1273 OS << format("0x%02x", uint8_t(Code[i]));
1276 // FIXME: Some of the 8 bits require fix up.
1277 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1278 << char('A' + MapEntry - 1) << '\'';
1280 OS << char('A' + MapEntry - 1);
1283 // Otherwise, write out in binary.
1285 for (unsigned j = 8; j--;) {
1286 unsigned Bit = (Code[i] >> j) & 1;
1289 if (MAI->isLittleEndian())
1290 FixupBit = i * 8 + j;
1292 FixupBit = i * 8 + (7-j);
1294 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1295 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1296 OS << char('A' + MapEntry - 1);
1304 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1305 MCFixup &F = Fixups[i];
1306 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1307 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1308 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1312 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1313 assert(getCurrentSection().first &&
1314 "Cannot emit contents before setting section!");
1316 // Show the encoding in a comment if we have a code emitter.
1318 AddEncodingComment(Inst, STI);
1320 // Show the MCInst if enabled.
1322 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1323 GetCommentOS() << "\n";
1326 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1328 InstPrinter->printInst(&Inst, OS, "");
1330 Inst.print(OS, MAI);
1334 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1335 OS << "\t.bundle_align_mode " << AlignPow2;
1339 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1340 OS << "\t.bundle_lock";
1342 OS << " align_to_end";
1346 void MCAsmStreamer::EmitBundleUnlock() {
1347 OS << "\t.bundle_unlock";
1351 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1352 /// the specified string in the output .s file. This capability is
1353 /// indicated by the hasRawTextSupport() predicate.
1354 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1355 if (!String.empty() && String.back() == '\n')
1356 String = String.substr(0, String.size()-1);
1361 void MCAsmStreamer::FinishImpl() {
1362 // If we are generating dwarf for assembly source files dump out the sections.
1363 if (getContext().getGenDwarfForAssembly())
1364 MCGenDwarfInfo::Emit(this);
1366 // Emit the label for the line table, if requested - since the rest of the
1367 // line table will be defined by .loc/.file directives, and not emitted
1368 // directly, the label is the only work required here.
1369 auto &Tables = getContext().getMCDwarfLineTables();
1370 if (!Tables.empty()) {
1371 assert(Tables.size() == 1 && "asm output only supports one line table");
1372 if (auto *Label = Tables.begin()->second.getLabel()) {
1373 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1379 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1380 formatted_raw_ostream &OS,
1381 bool isVerboseAsm, bool useDwarfDirectory,
1382 MCInstPrinter *IP, MCCodeEmitter *CE,
1383 MCAsmBackend *MAB, bool ShowInst) {
1384 return new MCAsmStreamer(Context, OS, isVerboseAsm, useDwarfDirectory, IP, CE,