ded2b42bd8c1abad2cab888741814dc8e39acef8
[oota-llvm.git] / lib / MC / MCAsmStreamer.cpp
1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
25 using namespace llvm;
26
27 namespace {
28
29 class MCAsmStreamer : public MCStreamer {
30   formatted_raw_ostream &OS;
31   const MCAsmInfo &MAI;
32   bool IsLittleEndian, IsVerboseAsm;
33   MCInstPrinter *InstPrinter;
34   MCCodeEmitter *Emitter;
35   
36   SmallString<128> CommentToEmit;
37   raw_svector_ostream CommentStream;
38 public:
39   MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
40                 const MCAsmInfo &mai,
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) {}
46   ~MCAsmStreamer() {}
47
48   bool isLittleEndian() const { return IsLittleEndian; }
49   
50   
51   inline void EmitEOL() {
52     // If we don't have any comments, just emit a \n.
53     if (!IsVerboseAsm) {
54       OS << '\n';
55       return;
56     }
57     EmitCommentsAndEOL();
58   }
59   void EmitCommentsAndEOL();
60   
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);
66   
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
69   /// use this method.
70   virtual raw_ostream &GetCommentOS() {
71     if (!IsVerboseAsm)
72       return nulls();  // Discard comments unless in verbose asm mode.
73     return CommentStream;
74   }
75   
76   /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
77   virtual void AddBlankLine() {
78     EmitEOL();
79   }
80   
81   /// @name MCStreamer Interface
82   /// @{
83
84   virtual void SwitchSection(const MCSection *Section);
85
86   virtual void EmitLabel(MCSymbol *Symbol);
87
88   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
89
90   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
91
92   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
93
94   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
95
96   virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
97                                 unsigned ByteAlignment);
98
99   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
100                             unsigned Size = 0, unsigned ByteAlignment = 0);
101
102   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
103
104   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
105   virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
106
107   virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
108                         unsigned AddrSpace);
109
110   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
111                                     unsigned ValueSize = 1,
112                                     unsigned MaxBytesToEmit = 0);
113
114   virtual void EmitValueToOffset(const MCExpr *Offset,
115                                  unsigned char Value = 0);
116   
117   virtual void EmitInstruction(const MCInst &Inst);
118
119   virtual void Finish();
120   
121   /// @}
122 };
123
124 } // end anonymous namespace.
125
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;
132   
133   // Make sure that CommentStream is flushed.
134   CommentStream.flush();
135   
136   T.toVector(CommentToEmit);
137   // Each comment goes on its own line.
138   CommentToEmit.push_back('\n');
139   
140   // Tell the comment stream that the vector changed underneath it.
141   CommentStream.resync();
142 }
143
144 void MCAsmStreamer::EmitCommentsAndEOL() {
145   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
146     OS << '\n';
147     return;
148   }
149   
150   CommentStream.flush();
151   StringRef Comments = CommentToEmit.str();
152   
153   assert(Comments.back() == '\n' &&
154          "Comment array not newline terminated");
155   do {
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';
160     
161     Comments = Comments.substr(Position+1);
162   } while (!Comments.empty());
163   
164   CommentToEmit.clear();
165   // Tell the comment stream that the vector changed underneath it.
166   CommentStream.resync();
167 }
168
169
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));
173 }
174
175 static inline const MCExpr *truncateToSize(const MCExpr *Value,
176                                            unsigned Bytes) {
177   // FIXME: Do we really need this routine?
178   return Value;
179 }
180
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);
186   }
187 }
188
189 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
190   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
191   assert(CurSection && "Cannot emit before setting section!");
192
193   OS << *Symbol << ":";
194   EmitEOL();
195   Symbol->setSection(*CurSection);
196 }
197
198 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
199   switch (Flag) {
200   default: assert(0 && "Invalid flag!");
201   case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
202   }
203   EmitEOL();
204 }
205
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!");
210
211   OS << *Symbol << " = " << *Value;
212   EmitEOL();
213
214   // FIXME: Lift context changes into super class.
215   // FIXME: Set associated section.
216   Symbol->setValue(Value);
217 }
218
219 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
220                                         MCSymbolAttr Attribute) {
221   switch (Attribute) {
222   case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
223   case MCSA_Global:         OS << MAI.getGlobalDirective(); break; // .globl
224   case MCSA_Hidden:         OS << ".hidden ";          break;
225   case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
226   case MCSA_Internal:       OS << ".internal ";        break;
227   case MCSA_LazyReference:  OS << ".lazy_reference ";  break;
228   case MCSA_Local:          OS << ".local ";           break;
229   case MCSA_NoDeadStrip:    OS << ".no_dead_strip ";   break;
230   case MCSA_PrivateExtern:  OS << ".private_extern ";  break;
231   case MCSA_Protected:      OS << ".protected ";       break;
232   case MCSA_Reference:      OS << ".reference ";       break;
233   case MCSA_Weak:           OS << ".weak ";            break;
234   case MCSA_WeakDefinition: OS << ".weak_definition "; break;
235       // .weak_reference
236   case MCSA_WeakReference:  OS << MAI.getWeakRefDirective(); break;
237   }
238
239   OS << *Symbol;
240   EmitEOL();
241 }
242
243 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
244   OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
245   EmitEOL();
246 }
247
248 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
249                                      unsigned ByteAlignment) {
250   OS << MAI.getCOMMDirective() << *Symbol << ',' << Size;
251   if (ByteAlignment != 0 && MAI.getCOMMDirectiveTakesAlignment()) {
252     if (MAI.getAlignmentIsInBytes())
253       OS << ',' << ByteAlignment;
254     else
255       OS << ',' << Log2_32(ByteAlignment);
256   }
257   EmitEOL();
258 }
259
260 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
261                                  unsigned Size, unsigned ByteAlignment) {
262   // Note: a .zerofill directive does not switch sections.
263   OS << ".zerofill ";
264   
265   // This is a mach-o specific directive.
266   const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
267   OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
268   
269   if (Symbol != NULL) {
270     OS << ',' << *Symbol << ',' << Size;
271     if (ByteAlignment != 0)
272       OS << ',' << Log2_32(ByteAlignment);
273   }
274   EmitEOL();
275 }
276
277 static inline char toOctal(int X) { return (X&7)+'0'; }
278
279 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
280   assert(CurSection && "Cannot emit contents before setting section!");
281   if (Data.empty()) return;
282   
283   if (Data.size() == 1) {
284     OS << MAI.getData8bitsDirective(AddrSpace);
285     OS << (unsigned)(unsigned char)Data[0];
286     EmitEOL();
287     return;
288   }
289
290   // If the data ends with 0 and the target supports .asciz, use it, otherwise
291   // use .ascii
292   if (MAI.getAscizDirective() && Data.back() == 0) {
293     OS << MAI.getAscizDirective();
294     Data = Data.substr(0, Data.size()-1);
295   } else {
296     OS << MAI.getAsciiDirective();
297   }
298
299   OS << " \"";
300   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
301     unsigned char C = Data[i];
302     if (C == '"' || C == '\\') {
303       OS << '\\' << (char)C;
304       continue;
305     }
306     
307     if (isprint((unsigned char)C)) {
308       OS << (char)C;
309       continue;
310     }
311     
312     switch (C) {
313     case '\b': OS << "\\b"; break;
314     case '\f': OS << "\\f"; break;
315     case '\n': OS << "\\n"; break;
316     case '\r': OS << "\\r"; break;
317     case '\t': OS << "\\t"; break;
318     default:
319       OS << '\\';
320       OS << toOctal(C >> 6);
321       OS << toOctal(C >> 3);
322       OS << toOctal(C >> 0);
323       break;
324     }
325   }
326   OS << '"';
327   EmitEOL();
328 }
329
330 /// EmitIntValue - Special case of EmitValue that avoids the client having
331 /// to pass in a MCExpr for constant integers.
332 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
333                                  unsigned AddrSpace) {
334   assert(CurSection && "Cannot emit contents before setting section!");
335   const char *Directive = 0;
336   switch (Size) {
337   default: break;
338   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
339   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
340   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
341   case 8:
342     Directive = MAI.getData64bitsDirective(AddrSpace);
343     // If the target doesn't support 64-bit data, emit as two 32-bit halves.
344     if (Directive) break;
345     if (isLittleEndian()) {
346       EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
347       EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
348     } else {
349       EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
350       EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
351     }
352     return;
353   }
354   
355   assert(Directive && "Invalid size for machine code value!");
356   OS << Directive << truncateToSize(Value, Size);
357   EmitEOL();
358 }
359
360 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
361                               unsigned AddrSpace) {
362   assert(CurSection && "Cannot emit contents before setting section!");
363   const char *Directive = 0;
364   switch (Size) {
365   default: break;
366   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
367   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
368   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
369   case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
370   }
371   
372   assert(Directive && "Invalid size for machine code value!");
373   OS << Directive << *truncateToSize(Value, Size);
374   EmitEOL();
375 }
376
377 /// EmitFill - Emit NumBytes bytes worth of the value specified by
378 /// FillValue.  This implements directives such as '.space'.
379 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
380                              unsigned AddrSpace) {
381   if (NumBytes == 0) return;
382   
383   if (AddrSpace == 0)
384     if (const char *ZeroDirective = MAI.getZeroDirective()) {
385       OS << ZeroDirective << NumBytes;
386       if (FillValue != 0)
387         OS << ',' << (int)FillValue;
388       EmitEOL();
389       return;
390     }
391
392   // Emit a byte at a time.
393   MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
394 }
395
396 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
397                                          unsigned ValueSize,
398                                          unsigned MaxBytesToEmit) {
399   // Some assemblers don't support non-power of two alignments, so we always
400   // emit alignments as a power of two if possible.
401   if (isPowerOf2_32(ByteAlignment)) {
402     switch (ValueSize) {
403     default: llvm_unreachable("Invalid size for machine code value!");
404     case 1: OS << MAI.getAlignDirective(); break;
405     // FIXME: use MAI for this!
406     case 2: OS << ".p2alignw "; break;
407     case 4: OS << ".p2alignl "; break;
408     case 8: llvm_unreachable("Unsupported alignment size!");
409     }
410     
411     if (MAI.getAlignmentIsInBytes())
412       OS << ByteAlignment;
413     else
414       OS << Log2_32(ByteAlignment);
415
416     if (Value || MaxBytesToEmit) {
417       OS << ", 0x";
418       OS.write_hex(truncateToSize(Value, ValueSize));
419
420       if (MaxBytesToEmit) 
421         OS << ", " << MaxBytesToEmit;
422     }
423     EmitEOL();
424     return;
425   }
426   
427   // Non-power of two alignment.  This is not widely supported by assemblers.
428   // FIXME: Parameterize this based on MAI.
429   switch (ValueSize) {
430   default: llvm_unreachable("Invalid size for machine code value!");
431   case 1: OS << ".balign";  break;
432   case 2: OS << ".balignw"; break;
433   case 4: OS << ".balignl"; break;
434   case 8: llvm_unreachable("Unsupported alignment size!");
435   }
436
437   OS << ' ' << ByteAlignment;
438   OS << ", " << truncateToSize(Value, ValueSize);
439   if (MaxBytesToEmit) 
440     OS << ", " << MaxBytesToEmit;
441   EmitEOL();
442 }
443
444 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
445                                       unsigned char Value) {
446   // FIXME: Verify that Offset is associated with the current section.
447   OS << ".org " << *Offset << ", " << (unsigned) Value;
448   EmitEOL();
449 }
450
451 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
452   assert(CurSection && "Cannot emit contents before setting section!");
453
454   // If we have an AsmPrinter, use that to print.
455   if (InstPrinter) {
456     InstPrinter->printInst(&Inst);
457     EmitEOL();
458
459     // Show the encoding if we have a code emitter.
460     if (Emitter) {
461       SmallString<256> Code;
462       raw_svector_ostream VecOS(Code);
463       Emitter->EncodeInstruction(Inst, VecOS);
464       VecOS.flush();
465   
466       OS.indent(20);
467       OS << " # encoding: [";
468       for (unsigned i = 0, e = Code.size(); i != e; ++i) {
469         if (i)
470           OS << ',';
471         OS << format("%#04x", uint8_t(Code[i]));
472       }
473       OS << "]\n";
474     }
475
476     return;
477   }
478
479   // Otherwise fall back to a structural printing for now. Eventually we should
480   // always have access to the target specific printer.
481   Inst.print(OS, &MAI);
482   EmitEOL();
483 }
484
485 void MCAsmStreamer::Finish() {
486   OS.flush();
487 }
488     
489 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
490                                     formatted_raw_ostream &OS,
491                                     const MCAsmInfo &MAI, bool isLittleEndian,
492                                     bool isVerboseAsm, MCInstPrinter *IP,
493                                     MCCodeEmitter *CE) {
494   return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,
495                            IP, CE);
496 }