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/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCCodeEmitter.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCFixupKindInfo.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstPrinter.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCSectionCOFF.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Path.h"
38 class MCAsmStreamer : public MCStreamer {
40 formatted_raw_ostream &OS;
43 std::unique_ptr<MCInstPrinter> InstPrinter;
44 std::unique_ptr<MCCodeEmitter> Emitter;
45 std::unique_ptr<MCAsmBackend> AsmBackend;
47 SmallString<128> CommentToEmit;
48 raw_svector_ostream CommentStream;
50 unsigned IsVerboseAsm : 1;
51 unsigned ShowInst : 1;
53 unsigned UseDwarfDirectory : 1;
55 enum EHSymbolFlags { EHGlobal = 1,
56 EHWeakDefinition = 1 << 1,
57 EHPrivateExtern = 1 << 2 };
58 DenseMap<const MCSymbol*, unsigned> FlagMap;
60 bool needsSet(const MCExpr *Value);
62 void EmitRegisterName(int64_t Register);
63 virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
64 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame);
67 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
68 bool isVerboseAsm, bool useCFI, bool useDwarfDirectory,
69 MCInstPrinter *printer, MCCodeEmitter *emitter,
70 MCAsmBackend *asmbackend, bool showInst)
71 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
72 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
73 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
74 ShowInst(showInst), UseCFI(useCFI),
75 UseDwarfDirectory(useDwarfDirectory) {
76 if (InstPrinter && IsVerboseAsm)
77 InstPrinter->setCommentStream(CommentStream);
81 inline void EmitEOL() {
82 // If we don't have any comments, just emit a \n.
89 void EmitCommentsAndEOL();
91 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
93 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
95 /// hasRawTextSupport - We support EmitRawText.
96 virtual bool hasRawTextSupport() const { return true; }
98 /// AddComment - Add a comment that can be emitted to the generated .s
99 /// file if applicable as a QoI issue to make the output of the compiler
100 /// more readable. This only affects the MCAsmStreamer, and only when
101 /// verbose assembly output is enabled.
102 virtual void AddComment(const Twine &T);
104 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
105 virtual void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
107 /// GetCommentOS - Return a raw_ostream that comments can be written to.
108 /// Unlike AddComment, you are required to terminate comments with \n if you
110 virtual raw_ostream &GetCommentOS() {
112 return nulls(); // Discard comments unless in verbose asm mode.
113 return CommentStream;
116 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
118 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
119 virtual void AddBlankLine() {
123 /// @name MCStreamer Interface
126 virtual void ChangeSection(const MCSection *Section,
127 const MCExpr *Subsection);
129 virtual void EmitLabel(MCSymbol *Symbol);
130 virtual void EmitDebugLabel(MCSymbol *Symbol);
132 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
134 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
135 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
136 virtual void EmitDataRegion(MCDataRegionType Kind);
137 virtual void EmitThumbFunc(MCSymbol *Func);
139 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
140 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
141 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
142 const MCSymbol *LastLabel,
143 const MCSymbol *Label,
144 unsigned PointerSize);
145 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
146 const MCSymbol *Label);
148 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
150 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
151 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
152 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
153 virtual void EmitCOFFSymbolType(int Type);
154 virtual void EndCOFFSymbolDef();
155 virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
156 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
157 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
158 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
159 unsigned ByteAlignment);
161 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
163 /// @param Symbol - The common symbol to emit.
164 /// @param Size - The size of the common symbol.
165 /// @param ByteAlignment - The alignment of the common symbol in bytes.
166 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
167 unsigned ByteAlignment);
169 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
170 uint64_t Size = 0, unsigned ByteAlignment = 0);
172 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
173 uint64_t Size, unsigned ByteAlignment = 0);
175 virtual void EmitBytes(StringRef Data);
177 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size);
178 virtual void EmitIntValue(uint64_t Value, unsigned Size);
180 virtual void EmitULEB128Value(const MCExpr *Value);
182 virtual void EmitSLEB128Value(const MCExpr *Value);
184 virtual void EmitGPRel64Value(const MCExpr *Value);
186 virtual void EmitGPRel32Value(const MCExpr *Value);
189 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue);
191 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
192 unsigned ValueSize = 1,
193 unsigned MaxBytesToEmit = 0);
195 virtual void EmitCodeAlignment(unsigned ByteAlignment,
196 unsigned MaxBytesToEmit = 0);
198 virtual bool EmitValueToOffset(const MCExpr *Offset,
199 unsigned char Value = 0);
201 virtual void EmitFileDirective(StringRef Filename);
202 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
203 StringRef Filename, unsigned CUID = 0);
204 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
205 unsigned Column, unsigned Flags,
206 unsigned Isa, unsigned Discriminator,
209 virtual void EmitIdent(StringRef IdentString);
210 virtual void EmitCFISections(bool EH, bool Debug);
211 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
212 virtual void EmitCFIDefCfaOffset(int64_t Offset);
213 virtual void EmitCFIDefCfaRegister(int64_t Register);
214 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
215 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
216 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
217 virtual void EmitCFIRememberState();
218 virtual void EmitCFIRestoreState();
219 virtual void EmitCFISameValue(int64_t Register);
220 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
221 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
222 virtual void EmitCFISignalFrame();
223 virtual void EmitCFIUndefined(int64_t Register);
224 virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
225 virtual void EmitCFIWindowSave();
227 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
228 virtual void EmitWin64EHEndProc();
229 virtual void EmitWin64EHStartChained();
230 virtual void EmitWin64EHEndChained();
231 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
233 virtual void EmitWin64EHHandlerData();
234 virtual void EmitWin64EHPushReg(unsigned Register);
235 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
236 virtual void EmitWin64EHAllocStack(unsigned Size);
237 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
238 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
239 virtual void EmitWin64EHPushFrame(bool Code);
240 virtual void EmitWin64EHEndProlog();
242 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI);
244 virtual void EmitBundleAlignMode(unsigned AlignPow2);
245 virtual void EmitBundleLock(bool AlignToEnd);
246 virtual void EmitBundleUnlock();
248 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
249 /// the specified string in the output .s file. This capability is
250 /// indicated by the hasRawTextSupport() predicate.
251 virtual void EmitRawTextImpl(StringRef String);
253 virtual void FinishImpl();
256 } // end anonymous namespace.
258 /// AddComment - Add a comment that can be emitted to the generated .s
259 /// file if applicable as a QoI issue to make the output of the compiler
260 /// more readable. This only affects the MCAsmStreamer, and only when
261 /// verbose assembly output is enabled.
262 void MCAsmStreamer::AddComment(const Twine &T) {
263 if (!IsVerboseAsm) return;
265 // Make sure that CommentStream is flushed.
266 CommentStream.flush();
268 T.toVector(CommentToEmit);
269 // Each comment goes on its own line.
270 CommentToEmit.push_back('\n');
272 // Tell the comment stream that the vector changed underneath it.
273 CommentStream.resync();
276 void MCAsmStreamer::EmitCommentsAndEOL() {
277 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
282 CommentStream.flush();
283 StringRef Comments = CommentToEmit.str();
285 assert(Comments.back() == '\n' &&
286 "Comment array not newline terminated");
288 // Emit a line of comments.
289 OS.PadToColumn(MAI->getCommentColumn());
290 size_t Position = Comments.find('\n');
291 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
293 Comments = Comments.substr(Position+1);
294 } while (!Comments.empty());
296 CommentToEmit.clear();
297 // Tell the comment stream that the vector changed underneath it.
298 CommentStream.resync();
301 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
302 assert(Bytes && "Invalid size!");
303 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
306 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
309 OS << MAI->getCommentString() << T;
313 void MCAsmStreamer::ChangeSection(const MCSection *Section,
314 const MCExpr *Subsection) {
315 assert(Section && "Cannot switch to a null section!");
316 Section->PrintSwitchToSection(*MAI, OS, Subsection);
319 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
320 MCSymbol *EHSymbol) {
324 unsigned Flags = FlagMap.lookup(Symbol);
326 if (Flags & EHGlobal)
327 EmitSymbolAttribute(EHSymbol, MCSA_Global);
328 if (Flags & EHWeakDefinition)
329 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
330 if (Flags & EHPrivateExtern)
331 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
334 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
335 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
336 MCStreamer::EmitLabel(Symbol);
338 OS << *Symbol << MAI->getLabelSuffix();
342 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
343 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
344 MCStreamer::EmitDebugLabel(Symbol);
346 OS << *Symbol << MAI->getDebugLabelSuffix();
350 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
352 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
353 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
354 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
355 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
356 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
361 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
362 assert(!Options.empty() && "At least one option is required!");
363 OS << "\t.linker_option \"" << Options[0] << '"';
364 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
365 ie = Options.end(); it != ie; ++it) {
366 OS << ", " << '"' << *it << '"';
371 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
372 if (!MAI->doesSupportDataRegionDirectives())
375 case MCDR_DataRegion: OS << "\t.data_region"; break;
376 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
377 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
378 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
379 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
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())
394 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
395 OS << *Symbol << " = " << *Value;
398 // FIXME: Lift context changes into super class.
399 Symbol->setVariableValue(Value);
402 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
403 OS << ".weakref " << *Alias << ", " << *Symbol;
407 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
408 const MCSymbol *LastLabel,
409 const MCSymbol *Label,
410 unsigned PointerSize) {
411 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
414 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
415 const MCSymbol *Label) {
416 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
417 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
418 AddrDelta = ForceExpAbs(AddrDelta);
419 EmitValue(AddrDelta, 4);
423 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
424 MCSymbolAttr Attribute) {
426 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
427 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
428 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
429 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
430 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
431 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
432 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
433 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
434 if (!MAI->hasDotTypeDotSizeDirective())
435 return false; // Symbol attribute not supported
436 OS << "\t.type\t" << *Symbol << ','
437 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
439 default: return false;
440 case MCSA_ELF_TypeFunction: OS << "function"; break;
441 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
442 case MCSA_ELF_TypeObject: OS << "object"; break;
443 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
444 case MCSA_ELF_TypeCommon: OS << "common"; break;
445 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
446 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
450 case MCSA_Global: // .globl/.global
451 OS << MAI->getGlobalDirective();
452 FlagMap[Symbol] |= EHGlobal;
454 case MCSA_Hidden: OS << "\t.hidden\t"; break;
455 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
456 case MCSA_Internal: OS << "\t.internal\t"; break;
457 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
458 case MCSA_Local: OS << "\t.local\t"; break;
459 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
460 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
461 case MCSA_PrivateExtern:
462 OS << "\t.private_extern\t";
463 FlagMap[Symbol] |= EHPrivateExtern;
465 case MCSA_Protected: OS << "\t.protected\t"; break;
466 case MCSA_Reference: OS << "\t.reference\t"; break;
467 case MCSA_Weak: OS << "\t.weak\t"; break;
468 case MCSA_WeakDefinition:
469 OS << "\t.weak_definition\t";
470 FlagMap[Symbol] |= EHWeakDefinition;
473 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
474 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
483 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
484 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
488 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
489 OS << "\t.def\t " << *Symbol << ';';
493 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
494 OS << "\t.scl\t" << StorageClass << ';';
498 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
499 OS << "\t.type\t" << Type << ';';
503 void MCAsmStreamer::EndCOFFSymbolDef() {
508 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
509 OS << "\t.secidx\t" << *Symbol;
513 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
514 OS << "\t.secrel32\t" << *Symbol;
518 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
519 assert(MAI->hasDotTypeDotSizeDirective());
520 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
523 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
524 unsigned ByteAlignment) {
525 // Common symbols do not belong to any actual section.
526 AssignSection(Symbol, NULL);
528 OS << "\t.comm\t" << *Symbol << ',' << Size;
529 if (ByteAlignment != 0) {
530 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
531 OS << ',' << ByteAlignment;
533 OS << ',' << Log2_32(ByteAlignment);
538 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
540 /// @param Symbol - The common symbol to emit.
541 /// @param Size - The size of the common symbol.
542 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
543 unsigned ByteAlign) {
544 // Common symbols do not belong to any actual section.
545 AssignSection(Symbol, NULL);
547 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
549 switch (MAI->getLCOMMDirectiveAlignmentType()) {
550 case LCOMM::NoAlignment:
551 llvm_unreachable("alignment not supported on .lcomm!");
552 case LCOMM::ByteAlignment:
553 OS << ',' << ByteAlign;
555 case LCOMM::Log2Alignment:
556 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
557 OS << ',' << Log2_32(ByteAlign);
564 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
565 uint64_t Size, unsigned ByteAlignment) {
567 AssignSection(Symbol, Section);
569 // Note: a .zerofill directive does not switch sections.
572 // This is a mach-o specific directive.
573 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
574 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
576 if (Symbol != NULL) {
577 OS << ',' << *Symbol << ',' << Size;
578 if (ByteAlignment != 0)
579 OS << ',' << Log2_32(ByteAlignment);
584 // .tbss sym, size, align
585 // This depends that the symbol has already been mangled from the original,
587 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
588 uint64_t Size, unsigned ByteAlignment) {
589 AssignSection(Symbol, Section);
591 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
592 // Instead of using the Section we'll just use the shortcut.
593 // This is a mach-o specific directive and section.
594 OS << ".tbss " << *Symbol << ", " << Size;
596 // Output align if we have it. We default to 1 so don't bother printing
598 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
603 static inline char toOctal(int X) { return (X&7)+'0'; }
605 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
608 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
609 unsigned char C = Data[i];
610 if (C == '"' || C == '\\') {
611 OS << '\\' << (char)C;
615 if (isprint((unsigned char)C)) {
621 case '\b': OS << "\\b"; break;
622 case '\f': OS << "\\f"; break;
623 case '\n': OS << "\\n"; break;
624 case '\r': OS << "\\r"; break;
625 case '\t': OS << "\\t"; break;
628 OS << toOctal(C >> 6);
629 OS << toOctal(C >> 3);
630 OS << toOctal(C >> 0);
639 void MCAsmStreamer::EmitBytes(StringRef Data) {
640 assert(getCurrentSection().first &&
641 "Cannot emit contents before setting section!");
642 if (Data.empty()) return;
644 if (Data.size() == 1) {
645 OS << MAI->getData8bitsDirective();
646 OS << (unsigned)(unsigned char)Data[0];
651 // If the data ends with 0 and the target supports .asciz, use it, otherwise
653 if (MAI->getAscizDirective() && Data.back() == 0) {
654 OS << MAI->getAscizDirective();
655 Data = Data.substr(0, Data.size()-1);
657 OS << MAI->getAsciiDirective();
660 PrintQuotedString(Data, OS);
664 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
665 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
668 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
669 assert(Size <= 8 && "Invalid size");
670 assert(getCurrentSection().first &&
671 "Cannot emit contents before setting section!");
672 const char *Directive = 0;
675 case 1: Directive = MAI->getData8bitsDirective(); break;
676 case 2: Directive = MAI->getData16bitsDirective(); break;
677 case 4: Directive = MAI->getData32bitsDirective(); break;
678 case 8: Directive = MAI->getData64bitsDirective(); break;
683 if (!Value->EvaluateAsAbsolute(IntValue))
684 report_fatal_error("Don't know how to emit this value.");
686 // We couldn't handle the requested integer size so we fallback by breaking
687 // the request down into several, smaller, integers. Since sizes greater
688 // than eight are invalid and size equivalent to eight should have been
689 // handled earlier, we use four bytes as our largest piece of granularity.
690 bool IsLittleEndian = MAI->isLittleEndian();
691 for (unsigned Emitted = 0; Emitted != Size;) {
692 unsigned Remaining = Size - Emitted;
693 // The size of our partial emission must be a power of two less than
695 unsigned EmissionSize = PowerOf2Floor(Remaining);
696 if (EmissionSize > 4)
698 // Calculate the byte offset of our partial emission taking into account
699 // the endianness of the target.
700 unsigned ByteOffset =
701 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
702 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
703 // We truncate our partial emission to fit within the bounds of the
704 // emission domain. This produces nicer output and silences potential
705 // truncation warnings when round tripping through another assembler.
706 ValueToEmit &= ~0ULL >> (64 - EmissionSize * 8);
707 EmitIntValue(ValueToEmit, EmissionSize);
708 Emitted += EmissionSize;
713 assert(Directive && "Invalid size for machine code value!");
714 OS << Directive << *Value;
718 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
720 if (Value->EvaluateAsAbsolute(IntValue)) {
721 EmitULEB128IntValue(IntValue);
724 assert(MAI->hasLEB128() && "Cannot print a .uleb");
725 OS << ".uleb128 " << *Value;
729 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
731 if (Value->EvaluateAsAbsolute(IntValue)) {
732 EmitSLEB128IntValue(IntValue);
735 assert(MAI->hasLEB128() && "Cannot print a .sleb");
736 OS << ".sleb128 " << *Value;
740 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
741 assert(MAI->getGPRel64Directive() != 0);
742 OS << MAI->getGPRel64Directive() << *Value;
746 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
747 assert(MAI->getGPRel32Directive() != 0);
748 OS << MAI->getGPRel32Directive() << *Value;
753 /// EmitFill - Emit NumBytes bytes worth of the value specified by
754 /// FillValue. This implements directives such as '.space'.
755 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
756 if (NumBytes == 0) return;
758 if (const char *ZeroDirective = MAI->getZeroDirective()) {
759 OS << ZeroDirective << NumBytes;
761 OS << ',' << (int)FillValue;
766 // Emit a byte at a time.
767 MCStreamer::EmitFill(NumBytes, FillValue);
770 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
772 unsigned MaxBytesToEmit) {
773 // Some assemblers don't support non-power of two alignments, so we always
774 // emit alignments as a power of two if possible.
775 if (isPowerOf2_32(ByteAlignment)) {
778 llvm_unreachable("Invalid size for machine code value!");
789 llvm_unreachable("Unsupported alignment size!");
792 if (MAI->getAlignmentIsInBytes())
795 OS << Log2_32(ByteAlignment);
797 if (Value || MaxBytesToEmit) {
799 OS.write_hex(truncateToSize(Value, ValueSize));
802 OS << ", " << MaxBytesToEmit;
808 // Non-power of two alignment. This is not widely supported by assemblers.
809 // FIXME: Parameterize this based on MAI.
811 default: llvm_unreachable("Invalid size for machine code value!");
812 case 1: OS << ".balign"; break;
813 case 2: OS << ".balignw"; break;
814 case 4: OS << ".balignl"; break;
815 case 8: llvm_unreachable("Unsupported alignment size!");
818 OS << ' ' << ByteAlignment;
819 OS << ", " << truncateToSize(Value, ValueSize);
821 OS << ", " << MaxBytesToEmit;
825 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
826 unsigned MaxBytesToEmit) {
827 // Emit with a text fill value.
828 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
832 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
833 unsigned char Value) {
834 // FIXME: Verify that Offset is associated with the current section.
835 OS << ".org " << *Offset << ", " << (unsigned) Value;
841 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
842 assert(MAI->hasSingleParameterDotFile());
844 PrintQuotedString(Filename, OS);
848 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
849 StringRef Filename, unsigned CUID) {
850 if (!UseDwarfDirectory && !Directory.empty()) {
851 if (sys::path::is_absolute(Filename))
852 return EmitDwarfFileDirective(FileNo, "", Filename, CUID);
854 SmallString<128> FullPathName = Directory;
855 sys::path::append(FullPathName, Filename);
856 return EmitDwarfFileDirective(FileNo, "", FullPathName, CUID);
859 OS << "\t.file\t" << FileNo << ' ';
860 if (!Directory.empty()) {
861 PrintQuotedString(Directory, OS);
864 PrintQuotedString(Filename, OS);
866 // All .file will belong to a single CUID.
869 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Directory, Filename,
873 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
874 unsigned Column, unsigned Flags,
876 unsigned Discriminator,
877 StringRef FileName) {
878 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
879 Isa, Discriminator, FileName);
880 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
881 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
882 OS << " basic_block";
883 if (Flags & DWARF2_FLAG_PROLOGUE_END)
884 OS << " prologue_end";
885 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
886 OS << " epilogue_begin";
888 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
889 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
892 if (Flags & DWARF2_FLAG_IS_STMT)
899 OS << " isa " << Isa;
901 OS << " discriminator " << Discriminator;
904 OS.PadToColumn(MAI->getCommentColumn());
905 OS << MAI->getCommentString() << ' ' << FileName << ':'
906 << Line << ':' << Column;
911 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
912 assert(MAI->hasIdentDirective() && ".ident directive not supported");
914 PrintQuotedString(IdentString, OS);
918 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
919 MCStreamer::EmitCFISections(EH, Debug);
924 OS << "\t.cfi_sections ";
928 OS << ", .debug_frame";
930 OS << ".debug_frame";
936 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
938 RecordProcStart(Frame);
942 OS << "\t.cfi_startproc";
948 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
950 RecordProcEnd(Frame);
954 // Put a dummy non-null value in Frame.End to mark that this frame has been
956 Frame.End = (MCSymbol *) 1;
958 OS << "\t.cfi_endproc";
962 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
963 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
964 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
965 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
966 InstPrinter->printRegName(OS, LLVMRegister);
972 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
973 MCStreamer::EmitCFIDefCfa(Register, Offset);
978 OS << "\t.cfi_def_cfa ";
979 EmitRegisterName(Register);
980 OS << ", " << Offset;
984 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
985 MCStreamer::EmitCFIDefCfaOffset(Offset);
990 OS << "\t.cfi_def_cfa_offset " << Offset;
994 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
995 MCStreamer::EmitCFIDefCfaRegister(Register);
1000 OS << "\t.cfi_def_cfa_register ";
1001 EmitRegisterName(Register);
1005 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1006 this->MCStreamer::EmitCFIOffset(Register, Offset);
1011 OS << "\t.cfi_offset ";
1012 EmitRegisterName(Register);
1013 OS << ", " << Offset;
1017 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1018 unsigned Encoding) {
1019 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1024 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1028 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1029 MCStreamer::EmitCFILsda(Sym, Encoding);
1034 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1038 void MCAsmStreamer::EmitCFIRememberState() {
1039 MCStreamer::EmitCFIRememberState();
1044 OS << "\t.cfi_remember_state";
1048 void MCAsmStreamer::EmitCFIRestoreState() {
1049 MCStreamer::EmitCFIRestoreState();
1054 OS << "\t.cfi_restore_state";
1058 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1059 MCStreamer::EmitCFISameValue(Register);
1064 OS << "\t.cfi_same_value ";
1065 EmitRegisterName(Register);
1069 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1070 MCStreamer::EmitCFIRelOffset(Register, Offset);
1075 OS << "\t.cfi_rel_offset ";
1076 EmitRegisterName(Register);
1077 OS << ", " << Offset;
1081 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1082 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1087 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1091 void MCAsmStreamer::EmitCFISignalFrame() {
1092 MCStreamer::EmitCFISignalFrame();
1097 OS << "\t.cfi_signal_frame";
1101 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1102 MCStreamer::EmitCFIUndefined(Register);
1107 OS << "\t.cfi_undefined " << Register;
1111 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1112 MCStreamer::EmitCFIRegister(Register1, Register2);
1117 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1121 void MCAsmStreamer::EmitCFIWindowSave() {
1122 MCStreamer::EmitCFIWindowSave();
1127 OS << "\t.cfi_window_save";
1131 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1132 MCStreamer::EmitWin64EHStartProc(Symbol);
1134 OS << ".seh_proc " << *Symbol;
1138 void MCAsmStreamer::EmitWin64EHEndProc() {
1139 MCStreamer::EmitWin64EHEndProc();
1141 OS << "\t.seh_endproc";
1145 void MCAsmStreamer::EmitWin64EHStartChained() {
1146 MCStreamer::EmitWin64EHStartChained();
1148 OS << "\t.seh_startchained";
1152 void MCAsmStreamer::EmitWin64EHEndChained() {
1153 MCStreamer::EmitWin64EHEndChained();
1155 OS << "\t.seh_endchained";
1159 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1161 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1163 OS << "\t.seh_handler " << *Sym;
1171 static const MCSection *getWin64EHTableSection(StringRef suffix,
1172 MCContext &context) {
1173 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1174 /// this duplicate code in MCWin64EH.cpp.
1176 return context.getObjectFileInfo()->getXDataSection();
1177 return context.getCOFFSection((".xdata"+suffix).str(),
1178 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1179 COFF::IMAGE_SCN_MEM_READ |
1180 COFF::IMAGE_SCN_MEM_WRITE,
1181 SectionKind::getDataRel());
1184 void MCAsmStreamer::EmitWin64EHHandlerData() {
1185 MCStreamer::EmitWin64EHHandlerData();
1187 // Switch sections. Don't call SwitchSection directly, because that will
1188 // cause the section switch to be visible in the emitted assembly.
1189 // We only do this so the section switch that terminates the handler
1190 // data block is visible.
1191 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1192 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1193 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1195 SwitchSectionNoChange(xdataSect);
1197 OS << "\t.seh_handlerdata";
1201 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1202 MCStreamer::EmitWin64EHPushReg(Register);
1204 OS << "\t.seh_pushreg " << Register;
1208 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1209 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1211 OS << "\t.seh_setframe " << Register << ", " << Offset;
1215 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1216 MCStreamer::EmitWin64EHAllocStack(Size);
1218 OS << "\t.seh_stackalloc " << Size;
1222 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1223 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1225 OS << "\t.seh_savereg " << Register << ", " << Offset;
1229 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1230 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1232 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1236 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1237 MCStreamer::EmitWin64EHPushFrame(Code);
1239 OS << "\t.seh_pushframe";
1245 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1246 MCStreamer::EmitWin64EHEndProlog();
1248 OS << "\t.seh_endprologue";
1252 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1253 const MCSubtargetInfo &STI) {
1254 raw_ostream &OS = GetCommentOS();
1255 SmallString<256> Code;
1256 SmallVector<MCFixup, 4> Fixups;
1257 raw_svector_ostream VecOS(Code);
1258 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1261 // If we are showing fixups, create symbolic markers in the encoded
1262 // representation. We do this by making a per-bit map to the fixup item index,
1263 // then trying to display it as nicely as possible.
1264 SmallVector<uint8_t, 64> FixupMap;
1265 FixupMap.resize(Code.size() * 8);
1266 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1269 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1270 MCFixup &F = Fixups[i];
1271 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1272 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1273 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1274 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1275 FixupMap[Index] = 1 + i;
1279 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1280 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1281 OS << "encoding: [";
1282 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1286 // See if all bits are the same map entry.
1287 uint8_t MapEntry = FixupMap[i * 8 + 0];
1288 for (unsigned j = 1; j != 8; ++j) {
1289 if (FixupMap[i * 8 + j] == MapEntry)
1292 MapEntry = uint8_t(~0U);
1296 if (MapEntry != uint8_t(~0U)) {
1297 if (MapEntry == 0) {
1298 OS << format("0x%02x", uint8_t(Code[i]));
1301 // FIXME: Some of the 8 bits require fix up.
1302 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1303 << char('A' + MapEntry - 1) << '\'';
1305 OS << char('A' + MapEntry - 1);
1308 // Otherwise, write out in binary.
1310 for (unsigned j = 8; j--;) {
1311 unsigned Bit = (Code[i] >> j) & 1;
1314 if (MAI->isLittleEndian())
1315 FixupBit = i * 8 + j;
1317 FixupBit = i * 8 + (7-j);
1319 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1320 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1321 OS << char('A' + MapEntry - 1);
1329 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1330 MCFixup &F = Fixups[i];
1331 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1332 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1333 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1337 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1338 assert(getCurrentSection().first &&
1339 "Cannot emit contents before setting section!");
1341 // Show the encoding in a comment if we have a code emitter.
1343 AddEncodingComment(Inst, STI);
1345 // Show the MCInst if enabled.
1347 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1348 GetCommentOS() << "\n";
1351 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1353 InstPrinter->printInst(&Inst, OS, "");
1355 Inst.print(OS, MAI);
1359 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1360 OS << "\t.bundle_align_mode " << AlignPow2;
1364 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1365 OS << "\t.bundle_lock";
1367 OS << " align_to_end";
1371 void MCAsmStreamer::EmitBundleUnlock() {
1372 OS << "\t.bundle_unlock";
1376 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1377 /// the specified string in the output .s file. This capability is
1378 /// indicated by the hasRawTextSupport() predicate.
1379 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1380 if (!String.empty() && String.back() == '\n')
1381 String = String.substr(0, String.size()-1);
1386 void MCAsmStreamer::FinishImpl() {
1387 // If we are generating dwarf for assembly source files dump out the sections.
1388 if (getContext().getGenDwarfForAssembly())
1389 MCGenDwarfInfo::Emit(this, NULL);
1392 EmitFrames(AsmBackend.get(), false);
1395 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1396 formatted_raw_ostream &OS,
1397 bool isVerboseAsm, bool useCFI,
1398 bool useDwarfDirectory, MCInstPrinter *IP,
1399 MCCodeEmitter *CE, MCAsmBackend *MAB,
1401 return new MCAsmStreamer(Context, OS, isVerboseAsm, useCFI, useDwarfDirectory,
1402 IP, CE, MAB, ShowInst);