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/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCCodeEmitter.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCFixupKindInfo.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCInstPrinter.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Target/TargetAsmBackend.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
35 class MCAsmStreamer : public MCStreamer {
36 formatted_raw_ostream &OS;
38 OwningPtr<MCInstPrinter> InstPrinter;
39 OwningPtr<MCCodeEmitter> Emitter;
40 OwningPtr<TargetAsmBackend> AsmBackend;
42 SmallString<128> CommentToEmit;
43 raw_svector_ostream CommentStream;
45 unsigned IsVerboseAsm : 1;
46 unsigned ShowInst : 1;
49 bool needsSet(const MCExpr *Value);
52 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
55 MCInstPrinter *printer, MCCodeEmitter *emitter,
56 TargetAsmBackend *asmbackend,
58 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
59 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
60 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
61 ShowInst(showInst), UseLoc(useLoc) {
62 if (InstPrinter && IsVerboseAsm)
63 InstPrinter->setCommentStream(CommentStream);
67 inline void EmitEOL() {
68 // If we don't have any comments, just emit a \n.
75 void EmitCommentsAndEOL();
77 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
79 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
81 /// hasRawTextSupport - We support EmitRawText.
82 virtual bool hasRawTextSupport() const { return true; }
84 /// AddComment - Add a comment that can be emitted to the generated .s
85 /// file if applicable as a QoI issue to make the output of the compiler
86 /// more readable. This only affects the MCAsmStreamer, and only when
87 /// verbose assembly output is enabled.
88 virtual void AddComment(const Twine &T);
90 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
91 virtual void AddEncodingComment(const MCInst &Inst);
93 /// GetCommentOS - Return a raw_ostream that comments can be written to.
94 /// Unlike AddComment, you are required to terminate comments with \n if you
96 virtual raw_ostream &GetCommentOS() {
98 return nulls(); // Discard comments unless in verbose asm mode.
102 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
103 virtual void AddBlankLine() {
107 /// @name MCStreamer Interface
110 virtual void ChangeSection(const MCSection *Section);
112 virtual void InitSections() {
113 // FIXME, this is MachO specific, but the testsuite
115 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
116 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
117 0, SectionKind::getText()));
120 virtual void EmitLabel(MCSymbol *Symbol);
122 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
123 virtual void EmitThumbFunc(MCSymbol *Func);
125 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
126 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
127 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
128 const MCSymbol *LastLabel,
129 const MCSymbol *Label);
131 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
133 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
134 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
135 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
136 virtual void EmitCOFFSymbolType(int Type);
137 virtual void EndCOFFSymbolDef();
138 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
139 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
140 unsigned ByteAlignment);
142 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
144 /// @param Symbol - The common symbol to emit.
145 /// @param Size - The size of the common symbol.
146 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
148 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
149 unsigned Size = 0, unsigned ByteAlignment = 0);
151 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
152 uint64_t Size, unsigned ByteAlignment = 0);
154 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
156 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
157 bool isPCRel, unsigned AddrSpace);
158 virtual void EmitIntValue(uint64_t Value, unsigned Size,
159 unsigned AddrSpace = 0);
161 virtual void EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
163 virtual void EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
165 virtual void EmitGPRel32Value(const MCExpr *Value);
168 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
171 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
172 unsigned ValueSize = 1,
173 unsigned MaxBytesToEmit = 0);
175 virtual void EmitCodeAlignment(unsigned ByteAlignment,
176 unsigned MaxBytesToEmit = 0);
178 virtual void EmitValueToOffset(const MCExpr *Offset,
179 unsigned char Value = 0);
181 virtual void EmitFileDirective(StringRef Filename);
182 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
183 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
184 unsigned Column, unsigned Flags,
185 unsigned Isa, unsigned Discriminator,
188 virtual void EmitCFIStartProc();
189 virtual void EmitCFIEndProc();
190 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
191 virtual void EmitCFIDefCfaOffset(int64_t Offset);
192 virtual void EmitCFIDefCfaRegister(int64_t Register);
193 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
194 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
195 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
196 virtual void EmitCFIRememberState();
197 virtual void EmitCFIRestoreState();
198 virtual void EmitCFISameValue(int64_t Register);
199 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
200 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
202 virtual void EmitFnStart();
203 virtual void EmitFnEnd();
204 virtual void EmitCantUnwind();
205 virtual void EmitPersonality(const MCSymbol *Personality);
206 virtual void EmitHandlerData();
207 virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
208 virtual void EmitPad(int64_t Offset);
209 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList, bool);
212 virtual void EmitInstruction(const MCInst &Inst);
214 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
215 /// the specified string in the output .s file. This capability is
216 /// indicated by the hasRawTextSupport() predicate.
217 virtual void EmitRawText(StringRef String);
219 virtual void Finish();
224 } // end anonymous namespace.
226 /// AddComment - Add a comment that can be emitted to the generated .s
227 /// file if applicable as a QoI issue to make the output of the compiler
228 /// more readable. This only affects the MCAsmStreamer, and only when
229 /// verbose assembly output is enabled.
230 void MCAsmStreamer::AddComment(const Twine &T) {
231 if (!IsVerboseAsm) return;
233 // Make sure that CommentStream is flushed.
234 CommentStream.flush();
236 T.toVector(CommentToEmit);
237 // Each comment goes on its own line.
238 CommentToEmit.push_back('\n');
240 // Tell the comment stream that the vector changed underneath it.
241 CommentStream.resync();
244 void MCAsmStreamer::EmitCommentsAndEOL() {
245 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
250 CommentStream.flush();
251 StringRef Comments = CommentToEmit.str();
253 assert(Comments.back() == '\n' &&
254 "Comment array not newline terminated");
256 // Emit a line of comments.
257 OS.PadToColumn(MAI.getCommentColumn());
258 size_t Position = Comments.find('\n');
259 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
261 Comments = Comments.substr(Position+1);
262 } while (!Comments.empty());
264 CommentToEmit.clear();
265 // Tell the comment stream that the vector changed underneath it.
266 CommentStream.resync();
269 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
270 assert(Bytes && "Invalid size!");
271 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
274 void MCAsmStreamer::ChangeSection(const MCSection *Section) {
275 assert(Section && "Cannot switch to a null section!");
276 Section->PrintSwitchToSection(MAI, OS);
279 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
280 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
281 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
282 assert(getCurrentSection() && "Cannot emit before setting section!");
284 OS << *Symbol << MAI.getLabelSuffix();
286 Symbol->setSection(*getCurrentSection());
289 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
291 default: assert(0 && "Invalid flag!");
292 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
293 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
294 case MCAF_Code16: OS << "\t.code\t16"; break;
295 case MCAF_Code32: OS << "\t.code\t32"; break;
300 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
301 // This needs to emit to a temporary string to get properly quoted
302 // MCSymbols when they have spaces in them.
303 OS << "\t.thumb_func";
309 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
310 OS << *Symbol << " = " << *Value;
313 // FIXME: Lift context changes into super class.
314 Symbol->setVariableValue(Value);
317 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
318 OS << ".weakref " << *Alias << ", " << *Symbol;
322 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
323 const MCSymbol *LastLabel,
324 const MCSymbol *Label) {
325 EmitDwarfSetLineAddr(LineDelta, Label,
326 getContext().getTargetAsmInfo().getPointerSize());
329 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
330 MCSymbolAttr Attribute) {
332 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
333 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
334 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
335 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
336 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
337 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
338 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
339 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
340 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
341 OS << "\t.type\t" << *Symbol << ','
342 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
344 default: assert(0 && "Unknown ELF .type");
345 case MCSA_ELF_TypeFunction: OS << "function"; break;
346 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
347 case MCSA_ELF_TypeObject: OS << "object"; break;
348 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
349 case MCSA_ELF_TypeCommon: OS << "common"; break;
350 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
351 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
355 case MCSA_Global: // .globl/.global
356 OS << MAI.getGlobalDirective();
358 case MCSA_Hidden: OS << "\t.hidden\t"; break;
359 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
360 case MCSA_Internal: OS << "\t.internal\t"; break;
361 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
362 case MCSA_Local: OS << "\t.local\t"; break;
363 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
364 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
365 case MCSA_PrivateExtern: OS << "\t.private_extern\t"; break;
366 case MCSA_Protected: OS << "\t.protected\t"; break;
367 case MCSA_Reference: OS << "\t.reference\t"; break;
368 case MCSA_Weak: OS << "\t.weak\t"; break;
369 case MCSA_WeakDefinition: OS << "\t.weak_definition\t"; break;
371 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
372 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
379 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
380 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
384 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
385 OS << "\t.def\t " << *Symbol << ';';
389 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
390 OS << "\t.scl\t" << StorageClass << ';';
394 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
395 OS << "\t.type\t" << Type << ';';
399 void MCAsmStreamer::EndCOFFSymbolDef() {
404 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
405 assert(MAI.hasDotTypeDotSizeDirective());
406 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
409 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
410 unsigned ByteAlignment) {
411 OS << "\t.comm\t" << *Symbol << ',' << Size;
412 if (ByteAlignment != 0) {
413 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
414 OS << ',' << ByteAlignment;
416 OS << ',' << Log2_32(ByteAlignment);
421 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
423 /// @param Symbol - The common symbol to emit.
424 /// @param Size - The size of the common symbol.
425 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
426 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
427 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
431 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
432 unsigned Size, unsigned ByteAlignment) {
433 // Note: a .zerofill directive does not switch sections.
436 // This is a mach-o specific directive.
437 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
438 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
440 if (Symbol != NULL) {
441 OS << ',' << *Symbol << ',' << Size;
442 if (ByteAlignment != 0)
443 OS << ',' << Log2_32(ByteAlignment);
448 // .tbss sym, size, align
449 // This depends that the symbol has already been mangled from the original,
451 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
452 uint64_t Size, unsigned ByteAlignment) {
453 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
454 // Instead of using the Section we'll just use the shortcut.
455 // This is a mach-o specific directive and section.
456 OS << ".tbss " << *Symbol << ", " << Size;
458 // Output align if we have it. We default to 1 so don't bother printing
460 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
465 static inline char toOctal(int X) { return (X&7)+'0'; }
467 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
470 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
471 unsigned char C = Data[i];
472 if (C == '"' || C == '\\') {
473 OS << '\\' << (char)C;
477 if (isprint((unsigned char)C)) {
483 case '\b': OS << "\\b"; break;
484 case '\f': OS << "\\f"; break;
485 case '\n': OS << "\\n"; break;
486 case '\r': OS << "\\r"; break;
487 case '\t': OS << "\\t"; break;
490 OS << toOctal(C >> 6);
491 OS << toOctal(C >> 3);
492 OS << toOctal(C >> 0);
501 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
502 assert(getCurrentSection() && "Cannot emit contents before setting section!");
503 if (Data.empty()) return;
505 if (Data.size() == 1) {
506 OS << MAI.getData8bitsDirective(AddrSpace);
507 OS << (unsigned)(unsigned char)Data[0];
512 // If the data ends with 0 and the target supports .asciz, use it, otherwise
514 if (MAI.getAscizDirective() && Data.back() == 0) {
515 OS << MAI.getAscizDirective();
516 Data = Data.substr(0, Data.size()-1);
518 OS << MAI.getAsciiDirective();
522 PrintQuotedString(Data, OS);
526 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
527 unsigned AddrSpace) {
528 EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
531 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
532 bool isPCRel, unsigned AddrSpace) {
533 assert(getCurrentSection() && "Cannot emit contents before setting section!");
534 assert(!isPCRel && "Cannot emit pc relative relocations!");
535 const char *Directive = 0;
538 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
539 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
540 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
542 Directive = MAI.getData64bitsDirective(AddrSpace);
543 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
544 if (Directive) break;
546 if (!Value->EvaluateAsAbsolute(IntValue))
547 report_fatal_error("Don't know how to emit this value.");
548 if (getContext().getTargetAsmInfo().isLittleEndian()) {
549 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
550 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
552 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
553 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
558 assert(Directive && "Invalid size for machine code value!");
559 OS << Directive << *Value;
563 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace) {
565 if (Value->EvaluateAsAbsolute(IntValue)) {
566 EmitULEB128IntValue(IntValue, AddrSpace);
569 assert(MAI.hasLEB128() && "Cannot print a .uleb");
570 OS << ".uleb128 " << *Value;
574 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace) {
576 if (Value->EvaluateAsAbsolute(IntValue)) {
577 EmitSLEB128IntValue(IntValue, AddrSpace);
580 assert(MAI.hasLEB128() && "Cannot print a .sleb");
581 OS << ".sleb128 " << *Value;
585 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
586 assert(MAI.getGPRel32Directive() != 0);
587 OS << MAI.getGPRel32Directive() << *Value;
592 /// EmitFill - Emit NumBytes bytes worth of the value specified by
593 /// FillValue. This implements directives such as '.space'.
594 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
595 unsigned AddrSpace) {
596 if (NumBytes == 0) return;
599 if (const char *ZeroDirective = MAI.getZeroDirective()) {
600 OS << ZeroDirective << NumBytes;
602 OS << ',' << (int)FillValue;
607 // Emit a byte at a time.
608 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
611 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
613 unsigned MaxBytesToEmit) {
614 // Some assemblers don't support non-power of two alignments, so we always
615 // emit alignments as a power of two if possible.
616 if (isPowerOf2_32(ByteAlignment)) {
618 default: llvm_unreachable("Invalid size for machine code value!");
619 case 1: OS << MAI.getAlignDirective(); break;
620 // FIXME: use MAI for this!
621 case 2: OS << ".p2alignw "; break;
622 case 4: OS << ".p2alignl "; break;
623 case 8: llvm_unreachable("Unsupported alignment size!");
626 if (MAI.getAlignmentIsInBytes())
629 OS << Log2_32(ByteAlignment);
631 if (Value || MaxBytesToEmit) {
633 OS.write_hex(truncateToSize(Value, ValueSize));
636 OS << ", " << MaxBytesToEmit;
642 // Non-power of two alignment. This is not widely supported by assemblers.
643 // FIXME: Parameterize this based on MAI.
645 default: llvm_unreachable("Invalid size for machine code value!");
646 case 1: OS << ".balign"; break;
647 case 2: OS << ".balignw"; break;
648 case 4: OS << ".balignl"; break;
649 case 8: llvm_unreachable("Unsupported alignment size!");
652 OS << ' ' << ByteAlignment;
653 OS << ", " << truncateToSize(Value, ValueSize);
655 OS << ", " << MaxBytesToEmit;
659 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
660 unsigned MaxBytesToEmit) {
661 // Emit with a text fill value.
662 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
666 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
667 unsigned char Value) {
668 // FIXME: Verify that Offset is associated with the current section.
669 OS << ".org " << *Offset << ", " << (unsigned) Value;
674 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
675 assert(MAI.hasSingleParameterDotFile());
677 PrintQuotedString(Filename, OS);
681 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
683 OS << "\t.file\t" << FileNo << ' ';
684 PrintQuotedString(Filename, OS);
687 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
690 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
691 unsigned Column, unsigned Flags,
693 unsigned Discriminator,
694 StringRef FileName) {
695 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
696 Isa, Discriminator, FileName);
700 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
701 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
702 OS << " basic_block";
703 if (Flags & DWARF2_FLAG_PROLOGUE_END)
704 OS << " prologue_end";
705 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
706 OS << " epilogue_begin";
708 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
709 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
712 if (Flags & DWARF2_FLAG_IS_STMT)
721 OS << "discriminator " << Discriminator;
724 OS.PadToColumn(MAI.getCommentColumn());
725 OS << MAI.getCommentString() << ' ' << FileName << ':'
726 << Line << ':' << Column;
731 void MCAsmStreamer::EmitCFIStartProc() {
732 MCStreamer::EmitCFIStartProc();
734 OS << "\t.cfi_startproc";
738 void MCAsmStreamer::EmitCFIEndProc() {
739 MCStreamer::EmitCFIEndProc();
741 OS << "\t.cfi_endproc";
745 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
749 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
750 MCStreamer::EmitCFIDefCfaOffset(Offset);
752 OS << "\t.cfi_def_cfa_offset " << Offset;
756 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
757 MCStreamer::EmitCFIDefCfaRegister(Register);
759 OS << "\t.cfi_def_cfa_register " << Register;
763 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
764 this->MCStreamer::EmitCFIOffset(Register, Offset);
766 OS << "\t.cfi_offset " << Register << ", " << Offset;
770 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
772 MCStreamer::EmitCFIPersonality(Sym, Encoding);
774 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
778 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
779 MCStreamer::EmitCFILsda(Sym, Encoding);
781 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
785 void MCAsmStreamer::EmitCFIRememberState() {
786 MCStreamer::EmitCFIRememberState();
788 OS << "\t.cfi_remember_state";
792 void MCAsmStreamer::EmitCFIRestoreState() {
793 MCStreamer::EmitCFIRestoreState();
795 OS << "\t.cfi_restore_state";
799 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
800 MCStreamer::EmitCFISameValue(Register);
802 OS << "\t.cfi_same_value " << Register;
806 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
807 MCStreamer::EmitCFIRelOffset(Register, Offset);
809 OS << "\t.cfi_rel_offset " << Register << ", " << Offset;
813 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
814 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
816 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
820 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
821 raw_ostream &OS = GetCommentOS();
822 SmallString<256> Code;
823 SmallVector<MCFixup, 4> Fixups;
824 raw_svector_ostream VecOS(Code);
825 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
828 // If we are showing fixups, create symbolic markers in the encoded
829 // representation. We do this by making a per-bit map to the fixup item index,
830 // then trying to display it as nicely as possible.
831 SmallVector<uint8_t, 64> FixupMap;
832 FixupMap.resize(Code.size() * 8);
833 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
836 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
837 MCFixup &F = Fixups[i];
838 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
839 for (unsigned j = 0; j != Info.TargetSize; ++j) {
840 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
841 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
842 FixupMap[Index] = 1 + i;
846 // FIXME: Node the fixup comments for Thumb2 are completely bogus since the
847 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
849 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
853 // See if all bits are the same map entry.
854 uint8_t MapEntry = FixupMap[i * 8 + 0];
855 for (unsigned j = 1; j != 8; ++j) {
856 if (FixupMap[i * 8 + j] == MapEntry)
859 MapEntry = uint8_t(~0U);
863 if (MapEntry != uint8_t(~0U)) {
865 OS << format("0x%02x", uint8_t(Code[i]));
868 // FIXME: Some of the 8 bits require fix up.
869 OS << format("0x%02x", uint8_t(Code[i])) << '\''
870 << char('A' + MapEntry - 1) << '\'';
872 OS << char('A' + MapEntry - 1);
875 // Otherwise, write out in binary.
877 for (unsigned j = 8; j--;) {
878 unsigned Bit = (Code[i] >> j) & 1;
881 if (getContext().getTargetAsmInfo().isLittleEndian())
882 FixupBit = i * 8 + j;
884 FixupBit = i * 8 + (7-j);
886 if (uint8_t MapEntry = FixupMap[FixupBit]) {
887 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
888 OS << char('A' + MapEntry - 1);
896 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
897 MCFixup &F = Fixups[i];
898 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
899 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
900 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
904 void MCAsmStreamer::EmitFnStart() {
909 void MCAsmStreamer::EmitFnEnd() {
914 void MCAsmStreamer::EmitCantUnwind() {
915 OS << "\t.cantunwind";
919 void MCAsmStreamer::EmitHandlerData() {
920 OS << "\t.handlerdata";
924 void MCAsmStreamer::EmitPersonality(const MCSymbol *Personality) {
925 OS << "\t.personality " << Personality->getName();
929 void MCAsmStreamer::EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset) {
930 OS << "\t.setfp\t" << InstPrinter->getRegName(FpReg)
931 << ", " << InstPrinter->getRegName(SpReg);
933 OS << ", #" << Offset;
937 void MCAsmStreamer::EmitPad(int64_t Offset) {
938 OS << "\t.pad\t#" << Offset;
942 void MCAsmStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
944 assert(RegList.size() && "RegList should not be empty");
950 OS << InstPrinter->getRegName(RegList[0]);
952 for (unsigned i = 1, e = RegList.size(); i != e; ++i)
953 OS << ", " << InstPrinter->getRegName(RegList[i]);
959 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
960 assert(getCurrentSection() && "Cannot emit contents before setting section!");
963 MCLineEntry::Make(this, getCurrentSection());
965 // Show the encoding in a comment if we have a code emitter.
967 AddEncodingComment(Inst);
969 // Show the MCInst if enabled.
971 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
972 GetCommentOS() << "\n";
975 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
977 InstPrinter->printInst(&Inst, OS);
979 Inst.print(OS, &MAI);
983 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
984 /// the specified string in the output .s file. This capability is
985 /// indicated by the hasRawTextSupport() predicate.
986 void MCAsmStreamer::EmitRawText(StringRef String) {
987 if (!String.empty() && String.back() == '\n')
988 String = String.substr(0, String.size()-1);
993 void MCAsmStreamer::Finish() {
994 // Dump out the dwarf file & directory tables and line tables.
995 if (getContext().hasDwarfFiles() && !UseLoc)
996 MCDwarfFileTable::Emit(this);
999 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1000 formatted_raw_ostream &OS,
1001 bool isVerboseAsm, bool useLoc,
1002 MCInstPrinter *IP, MCCodeEmitter *CE,
1003 TargetAsmBackend *TAB, bool ShowInst) {
1004 return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc,
1005 IP, CE, TAB, ShowInst);