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/MCInst.h"
16 #include "llvm/MC/MCInstPrinter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/FormattedStream.h"
29 class MCAsmStreamer : public MCStreamer {
30 formatted_raw_ostream &OS;
32 bool IsLittleEndian, IsVerboseAsm;
33 MCInstPrinter *InstPrinter;
34 MCCodeEmitter *Emitter;
36 SmallString<128> CommentToEmit;
37 raw_svector_ostream CommentStream;
39 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
41 bool isLittleEndian, bool isVerboseAsm, MCInstPrinter *printer,
42 MCCodeEmitter *emitter)
43 : MCStreamer(Context), OS(os), MAI(mai), IsLittleEndian(isLittleEndian),
44 IsVerboseAsm(isVerboseAsm), InstPrinter(printer), Emitter(emitter),
45 CommentStream(CommentToEmit) {}
48 bool isLittleEndian() const { return IsLittleEndian; }
51 inline void EmitEOL() {
52 // If we don't have any comments, just emit a \n.
59 void EmitCommentsAndEOL();
61 /// AddComment - Add a comment that can be emitted to the generated .s
62 /// file if applicable as a QoI issue to make the output of the compiler
63 /// more readable. This only affects the MCAsmStreamer, and only when
64 /// verbose assembly output is enabled.
65 virtual void AddComment(const Twine &T);
67 /// GetCommentOS - Return a raw_ostream that comments can be written to.
68 /// Unlike AddComment, you are required to terminate comments with \n if you
70 virtual raw_ostream &GetCommentOS() {
72 return nulls(); // Discard comments unless in verbose asm mode.
76 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
77 virtual void AddBlankLine() {
81 /// @name MCStreamer Interface
84 virtual void SwitchSection(const MCSection *Section);
86 virtual void EmitLabel(MCSymbol *Symbol);
88 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
90 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
92 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
94 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
96 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
97 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
98 unsigned ByteAlignment);
100 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
102 /// @param Symbol - The common symbol to emit.
103 /// @param Size - The size of the common symbol.
104 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
106 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
107 unsigned Size = 0, unsigned ByteAlignment = 0);
109 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
111 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
112 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
114 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
117 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
118 unsigned ValueSize = 1,
119 unsigned MaxBytesToEmit = 0);
121 virtual void EmitValueToOffset(const MCExpr *Offset,
122 unsigned char Value = 0);
124 virtual void EmitInstruction(const MCInst &Inst);
126 virtual void Finish();
131 } // end anonymous namespace.
133 /// AddComment - Add a comment that can be emitted to the generated .s
134 /// file if applicable as a QoI issue to make the output of the compiler
135 /// more readable. This only affects the MCAsmStreamer, and only when
136 /// verbose assembly output is enabled.
137 void MCAsmStreamer::AddComment(const Twine &T) {
138 if (!IsVerboseAsm) return;
140 // Make sure that CommentStream is flushed.
141 CommentStream.flush();
143 T.toVector(CommentToEmit);
144 // Each comment goes on its own line.
145 CommentToEmit.push_back('\n');
147 // Tell the comment stream that the vector changed underneath it.
148 CommentStream.resync();
151 void MCAsmStreamer::EmitCommentsAndEOL() {
152 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
157 CommentStream.flush();
158 StringRef Comments = CommentToEmit.str();
160 assert(Comments.back() == '\n' &&
161 "Comment array not newline terminated");
163 // Emit a line of comments.
164 OS.PadToColumn(MAI.getCommentColumn());
165 size_t Position = Comments.find('\n');
166 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
168 Comments = Comments.substr(Position+1);
169 } while (!Comments.empty());
171 CommentToEmit.clear();
172 // Tell the comment stream that the vector changed underneath it.
173 CommentStream.resync();
177 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
178 assert(Bytes && "Invalid size!");
179 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
182 static inline const MCExpr *truncateToSize(const MCExpr *Value,
184 // FIXME: Do we really need this routine?
188 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
189 assert(Section && "Cannot switch to a null section!");
190 if (Section != CurSection) {
191 CurSection = Section;
192 Section->PrintSwitchToSection(MAI, OS);
196 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
197 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
198 assert(CurSection && "Cannot emit before setting section!");
200 OS << *Symbol << ":";
202 Symbol->setSection(*CurSection);
205 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
207 default: assert(0 && "Invalid flag!");
208 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
213 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
214 // Only absolute symbols can be redefined.
215 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
216 "Cannot define a symbol twice!");
218 OS << *Symbol << " = " << *Value;
221 // FIXME: Lift context changes into super class.
222 // FIXME: Set associated section.
223 Symbol->setValue(Value);
226 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
227 MCSymbolAttr Attribute) {
229 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
230 case MCSA_Global: OS << MAI.getGlobalDirective(); break; // .globl
231 case MCSA_Hidden: OS << ".hidden "; break;
232 case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
233 case MCSA_Internal: OS << ".internal "; break;
234 case MCSA_LazyReference: OS << ".lazy_reference "; break;
235 case MCSA_Local: OS << ".local "; break;
236 case MCSA_NoDeadStrip: OS << ".no_dead_strip "; break;
237 case MCSA_PrivateExtern: OS << ".private_extern "; break;
238 case MCSA_Protected: OS << ".protected "; break;
239 case MCSA_Reference: OS << ".reference "; break;
240 case MCSA_Weak: OS << ".weak "; break;
241 case MCSA_WeakDefinition: OS << ".weak_definition "; break;
243 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
250 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
251 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
255 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
256 assert(MAI.hasDotTypeDotSizeDirective());
257 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
260 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
261 unsigned ByteAlignment) {
262 OS << "\t.comm\t" << *Symbol << ',' << Size;
263 if (ByteAlignment != 0) {
264 if (MAI.getAlignmentIsInBytes())
265 OS << ',' << ByteAlignment;
267 OS << ',' << Log2_32(ByteAlignment);
272 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
274 /// @param Symbol - The common symbol to emit.
275 /// @param Size - The size of the common symbol.
276 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
277 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
278 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
282 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
283 unsigned Size, unsigned ByteAlignment) {
284 // Note: a .zerofill directive does not switch sections.
287 // This is a mach-o specific directive.
288 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
289 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
291 if (Symbol != NULL) {
292 OS << ',' << *Symbol << ',' << Size;
293 if (ByteAlignment != 0)
294 OS << ',' << Log2_32(ByteAlignment);
299 static inline char toOctal(int X) { return (X&7)+'0'; }
301 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
302 assert(CurSection && "Cannot emit contents before setting section!");
303 if (Data.empty()) return;
305 if (Data.size() == 1) {
306 OS << MAI.getData8bitsDirective(AddrSpace);
307 OS << (unsigned)(unsigned char)Data[0];
312 // If the data ends with 0 and the target supports .asciz, use it, otherwise
314 if (MAI.getAscizDirective() && Data.back() == 0) {
315 OS << MAI.getAscizDirective();
316 Data = Data.substr(0, Data.size()-1);
318 OS << MAI.getAsciiDirective();
322 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
323 unsigned char C = Data[i];
324 if (C == '"' || C == '\\') {
325 OS << '\\' << (char)C;
329 if (isprint((unsigned char)C)) {
335 case '\b': OS << "\\b"; break;
336 case '\f': OS << "\\f"; break;
337 case '\n': OS << "\\n"; break;
338 case '\r': OS << "\\r"; break;
339 case '\t': OS << "\\t"; break;
342 OS << toOctal(C >> 6);
343 OS << toOctal(C >> 3);
344 OS << toOctal(C >> 0);
352 /// EmitIntValue - Special case of EmitValue that avoids the client having
353 /// to pass in a MCExpr for constant integers.
354 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
355 unsigned AddrSpace) {
356 assert(CurSection && "Cannot emit contents before setting section!");
357 const char *Directive = 0;
360 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
361 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
362 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
364 Directive = MAI.getData64bitsDirective(AddrSpace);
365 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
366 if (Directive) break;
367 if (isLittleEndian()) {
368 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
369 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
371 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
372 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
377 assert(Directive && "Invalid size for machine code value!");
378 OS << Directive << truncateToSize(Value, Size);
382 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
383 unsigned AddrSpace) {
384 assert(CurSection && "Cannot emit contents before setting section!");
385 const char *Directive = 0;
388 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
389 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
390 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
391 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
394 assert(Directive && "Invalid size for machine code value!");
395 OS << Directive << *truncateToSize(Value, Size);
399 /// EmitFill - Emit NumBytes bytes worth of the value specified by
400 /// FillValue. This implements directives such as '.space'.
401 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
402 unsigned AddrSpace) {
403 if (NumBytes == 0) return;
406 if (const char *ZeroDirective = MAI.getZeroDirective()) {
407 OS << ZeroDirective << NumBytes;
409 OS << ',' << (int)FillValue;
414 // Emit a byte at a time.
415 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
418 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
420 unsigned MaxBytesToEmit) {
421 // Some assemblers don't support non-power of two alignments, so we always
422 // emit alignments as a power of two if possible.
423 if (isPowerOf2_32(ByteAlignment)) {
425 default: llvm_unreachable("Invalid size for machine code value!");
426 case 1: OS << MAI.getAlignDirective(); break;
427 // FIXME: use MAI for this!
428 case 2: OS << ".p2alignw "; break;
429 case 4: OS << ".p2alignl "; break;
430 case 8: llvm_unreachable("Unsupported alignment size!");
433 if (MAI.getAlignmentIsInBytes())
436 OS << Log2_32(ByteAlignment);
438 if (Value || MaxBytesToEmit) {
440 OS.write_hex(truncateToSize(Value, ValueSize));
443 OS << ", " << MaxBytesToEmit;
449 // Non-power of two alignment. This is not widely supported by assemblers.
450 // FIXME: Parameterize this based on MAI.
452 default: llvm_unreachable("Invalid size for machine code value!");
453 case 1: OS << ".balign"; break;
454 case 2: OS << ".balignw"; break;
455 case 4: OS << ".balignl"; break;
456 case 8: llvm_unreachable("Unsupported alignment size!");
459 OS << ' ' << ByteAlignment;
460 OS << ", " << truncateToSize(Value, ValueSize);
462 OS << ", " << MaxBytesToEmit;
466 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
467 unsigned char Value) {
468 // FIXME: Verify that Offset is associated with the current section.
469 OS << ".org " << *Offset << ", " << (unsigned) Value;
473 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
474 assert(CurSection && "Cannot emit contents before setting section!");
476 // If we have an AsmPrinter, use that to print.
478 InstPrinter->printInst(&Inst);
481 // Show the encoding if we have a code emitter.
483 SmallString<256> Code;
484 raw_svector_ostream VecOS(Code);
485 Emitter->EncodeInstruction(Inst, VecOS);
489 OS << " # encoding: [";
490 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
493 OS << format("%#04x", uint8_t(Code[i]));
501 // Otherwise fall back to a structural printing for now. Eventually we should
502 // always have access to the target specific printer.
503 Inst.print(OS, &MAI);
507 void MCAsmStreamer::Finish() {
511 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
512 formatted_raw_ostream &OS,
513 const MCAsmInfo &MAI, bool isLittleEndian,
514 bool isVerboseAsm, MCInstPrinter *IP,
516 return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,