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(AssemblerFlag Flag);
90 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
92 virtual void EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute);
94 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
96 virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
97 unsigned ByteAlignment);
99 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
100 unsigned Size = 0, unsigned ByteAlignment = 0);
102 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
104 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
105 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
107 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
110 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
111 unsigned ValueSize = 1,
112 unsigned MaxBytesToEmit = 0);
114 virtual void EmitValueToOffset(const MCExpr *Offset,
115 unsigned char Value = 0);
117 virtual void EmitInstruction(const MCInst &Inst);
119 virtual void Finish();
124 } // end anonymous namespace.
126 /// AddComment - Add a comment that can be emitted to the generated .s
127 /// file if applicable as a QoI issue to make the output of the compiler
128 /// more readable. This only affects the MCAsmStreamer, and only when
129 /// verbose assembly output is enabled.
130 void MCAsmStreamer::AddComment(const Twine &T) {
131 if (!IsVerboseAsm) return;
133 // Make sure that CommentStream is flushed.
134 CommentStream.flush();
136 T.toVector(CommentToEmit);
137 // Each comment goes on its own line.
138 CommentToEmit.push_back('\n');
140 // Tell the comment stream that the vector changed underneath it.
141 CommentStream.resync();
144 void MCAsmStreamer::EmitCommentsAndEOL() {
145 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
150 CommentStream.flush();
151 StringRef Comments = CommentToEmit.str();
153 assert(Comments.back() == '\n' &&
154 "Comment array not newline terminated");
156 // Emit a line of comments.
157 OS.PadToColumn(MAI.getCommentColumn());
158 size_t Position = Comments.find('\n');
159 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
161 Comments = Comments.substr(Position+1);
162 } while (!Comments.empty());
164 CommentToEmit.clear();
165 // Tell the comment stream that the vector changed underneath it.
166 CommentStream.resync();
170 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
171 assert(Bytes && "Invalid size!");
172 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
175 static inline const MCExpr *truncateToSize(const MCExpr *Value,
177 // FIXME: Do we really need this routine?
181 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
182 assert(Section && "Cannot switch to a null section!");
183 if (Section != CurSection) {
184 CurSection = Section;
185 Section->PrintSwitchToSection(MAI, OS);
189 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
190 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
191 assert(CurSection && "Cannot emit before setting section!");
193 OS << *Symbol << ":";
195 Symbol->setSection(*CurSection);
198 void MCAsmStreamer::EmitAssemblerFlag(AssemblerFlag Flag) {
200 default: assert(0 && "Invalid flag!");
201 case SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
206 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
207 // Only absolute symbols can be redefined.
208 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
209 "Cannot define a symbol twice!");
211 OS << *Symbol << " = " << *Value;
214 // FIXME: Lift context changes into super class.
215 // FIXME: Set associated section.
216 Symbol->setValue(Value);
219 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
220 SymbolAttr Attribute) {
222 case Global: OS << MAI.getGlobalDirective(); break; // .globl
223 case Hidden: OS << ".hidden "; break;
224 case IndirectSymbol: OS << ".indirect_symbol "; break;
225 case Internal: OS << ".internal "; break;
226 case LazyReference: OS << ".lazy_reference "; break;
227 case Local: OS << ".local "; break;
228 case NoDeadStrip: OS << ".no_dead_strip "; break;
229 case PrivateExtern: OS << ".private_extern "; break;
230 case Protected: OS << ".protected "; break;
231 case Reference: OS << ".reference "; break;
232 case Weak: OS << ".weak "; break;
233 case WeakDefinition: OS << ".weak_definition "; break;
234 case WeakReference: OS << MAI.getWeakRefDirective(); break;// .weak_reference
241 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
242 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
246 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
247 unsigned ByteAlignment) {
248 OS << MAI.getCOMMDirective() << *Symbol << ',' << Size;
249 if (ByteAlignment != 0 && MAI.getCOMMDirectiveTakesAlignment()) {
250 if (MAI.getAlignmentIsInBytes())
251 OS << ',' << ByteAlignment;
253 OS << ',' << Log2_32(ByteAlignment);
258 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
259 unsigned Size, unsigned ByteAlignment) {
260 // Note: a .zerofill directive does not switch sections.
263 // This is a mach-o specific directive.
264 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
265 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
267 if (Symbol != NULL) {
268 OS << ',' << *Symbol << ',' << Size;
269 if (ByteAlignment != 0)
270 OS << ',' << Log2_32(ByteAlignment);
275 static inline char toOctal(int X) { return (X&7)+'0'; }
277 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
278 assert(CurSection && "Cannot emit contents before setting section!");
279 if (Data.empty()) return;
281 if (Data.size() == 1) {
282 OS << MAI.getData8bitsDirective(AddrSpace);
283 OS << (unsigned)(unsigned char)Data[0];
288 // If the data ends with 0 and the target supports .asciz, use it, otherwise
290 if (MAI.getAscizDirective() && Data.back() == 0) {
291 OS << MAI.getAscizDirective();
292 Data = Data.substr(0, Data.size()-1);
294 OS << MAI.getAsciiDirective();
298 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
299 unsigned char C = Data[i];
300 if (C == '"' || C == '\\') {
301 OS << '\\' << (char)C;
305 if (isprint((unsigned char)C)) {
311 case '\b': OS << "\\b"; break;
312 case '\f': OS << "\\f"; break;
313 case '\n': OS << "\\n"; break;
314 case '\r': OS << "\\r"; break;
315 case '\t': OS << "\\t"; break;
318 OS << toOctal(C >> 6);
319 OS << toOctal(C >> 3);
320 OS << toOctal(C >> 0);
328 /// EmitIntValue - Special case of EmitValue that avoids the client having
329 /// to pass in a MCExpr for constant integers.
330 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
331 unsigned AddrSpace) {
332 assert(CurSection && "Cannot emit contents before setting section!");
333 const char *Directive = 0;
336 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
337 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
338 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
340 Directive = MAI.getData64bitsDirective(AddrSpace);
341 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
342 if (Directive) break;
343 if (isLittleEndian()) {
344 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
345 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
347 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
348 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
353 assert(Directive && "Invalid size for machine code value!");
354 OS << Directive << truncateToSize(Value, Size);
358 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
359 unsigned AddrSpace) {
360 assert(CurSection && "Cannot emit contents before setting section!");
361 const char *Directive = 0;
364 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
365 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
366 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
367 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
370 assert(Directive && "Invalid size for machine code value!");
371 OS << Directive << *truncateToSize(Value, Size);
375 /// EmitFill - Emit NumBytes bytes worth of the value specified by
376 /// FillValue. This implements directives such as '.space'.
377 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
378 unsigned AddrSpace) {
379 if (NumBytes == 0) return;
382 if (const char *ZeroDirective = MAI.getZeroDirective()) {
383 OS << ZeroDirective << NumBytes;
385 OS << ',' << (int)FillValue;
390 // Emit a byte at a time.
391 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
394 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
396 unsigned MaxBytesToEmit) {
397 // Some assemblers don't support non-power of two alignments, so we always
398 // emit alignments as a power of two if possible.
399 if (isPowerOf2_32(ByteAlignment)) {
401 default: llvm_unreachable("Invalid size for machine code value!");
402 case 1: OS << MAI.getAlignDirective(); break;
403 // FIXME: use MAI for this!
404 case 2: OS << ".p2alignw "; break;
405 case 4: OS << ".p2alignl "; break;
406 case 8: llvm_unreachable("Unsupported alignment size!");
409 if (MAI.getAlignmentIsInBytes())
412 OS << Log2_32(ByteAlignment);
414 if (Value || MaxBytesToEmit) {
416 OS.write_hex(truncateToSize(Value, ValueSize));
419 OS << ", " << MaxBytesToEmit;
425 // Non-power of two alignment. This is not widely supported by assemblers.
426 // FIXME: Parameterize this based on MAI.
428 default: llvm_unreachable("Invalid size for machine code value!");
429 case 1: OS << ".balign"; break;
430 case 2: OS << ".balignw"; break;
431 case 4: OS << ".balignl"; break;
432 case 8: llvm_unreachable("Unsupported alignment size!");
435 OS << ' ' << ByteAlignment;
436 OS << ", " << truncateToSize(Value, ValueSize);
438 OS << ", " << MaxBytesToEmit;
442 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
443 unsigned char Value) {
444 // FIXME: Verify that Offset is associated with the current section.
445 OS << ".org " << *Offset << ", " << (unsigned) Value;
449 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
450 assert(CurSection && "Cannot emit contents before setting section!");
452 // If we have an AsmPrinter, use that to print.
454 InstPrinter->printInst(&Inst);
457 // Show the encoding if we have a code emitter.
459 SmallString<256> Code;
460 raw_svector_ostream VecOS(Code);
461 Emitter->EncodeInstruction(Inst, VecOS);
465 OS << " # encoding: [";
466 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
469 OS << format("%#04x", uint8_t(Code[i]));
477 // Otherwise fall back to a structural printing for now. Eventually we should
478 // always have access to the target specific printer.
479 Inst.print(OS, &MAI);
483 void MCAsmStreamer::Finish() {
487 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
488 formatted_raw_ostream &OS,
489 const MCAsmInfo &MAI, bool isLittleEndian,
490 bool isVerboseAsm, MCInstPrinter *IP,
492 return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,