add symbol attribute support for the ELF .type directive.
[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 EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
97   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
98                                 unsigned ByteAlignment);
99
100   /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
101   ///
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);
105   
106   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
107                             unsigned Size = 0, unsigned ByteAlignment = 0);
108
109   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
110
111   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
112   virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
113
114   virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
115                         unsigned AddrSpace);
116
117   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
118                                     unsigned ValueSize = 1,
119                                     unsigned MaxBytesToEmit = 0);
120
121   virtual void EmitValueToOffset(const MCExpr *Offset,
122                                  unsigned char Value = 0);
123   
124   virtual void EmitInstruction(const MCInst &Inst);
125
126   virtual void Finish();
127   
128   /// @}
129 };
130
131 } // end anonymous namespace.
132
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;
139   
140   // Make sure that CommentStream is flushed.
141   CommentStream.flush();
142   
143   T.toVector(CommentToEmit);
144   // Each comment goes on its own line.
145   CommentToEmit.push_back('\n');
146   
147   // Tell the comment stream that the vector changed underneath it.
148   CommentStream.resync();
149 }
150
151 void MCAsmStreamer::EmitCommentsAndEOL() {
152   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
153     OS << '\n';
154     return;
155   }
156   
157   CommentStream.flush();
158   StringRef Comments = CommentToEmit.str();
159   
160   assert(Comments.back() == '\n' &&
161          "Comment array not newline terminated");
162   do {
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';
167     
168     Comments = Comments.substr(Position+1);
169   } while (!Comments.empty());
170   
171   CommentToEmit.clear();
172   // Tell the comment stream that the vector changed underneath it.
173   CommentStream.resync();
174 }
175
176
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));
180 }
181
182 static inline const MCExpr *truncateToSize(const MCExpr *Value,
183                                            unsigned Bytes) {
184   // FIXME: Do we really need this routine?
185   return Value;
186 }
187
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);
193   }
194 }
195
196 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
197   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
198   assert(CurSection && "Cannot emit before setting section!");
199
200   OS << *Symbol << ":";
201   EmitEOL();
202   Symbol->setSection(*CurSection);
203 }
204
205 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
206   switch (Flag) {
207   default: assert(0 && "Invalid flag!");
208   case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
209   }
210   EmitEOL();
211 }
212
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!");
217
218   OS << *Symbol << " = " << *Value;
219   EmitEOL();
220
221   // FIXME: Lift context changes into super class.
222   // FIXME: Set associated section.
223   Symbol->setValue(Value);
224 }
225
226 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
227                                         MCSymbolAttr Attribute) {
228   switch (Attribute) {
229   case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
230   case MCSA_ELF_TypeFunction:    /// .type _foo, STT_FUNC  # aka @function
231   case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
232   case MCSA_ELF_TypeObject:      /// .type _foo, STT_OBJECT  # aka @object
233   case MCSA_ELF_TypeTLS:         /// .type _foo, STT_TLS     # aka @tls_object
234   case MCSA_ELF_TypeCommon:      /// .type _foo, STT_COMMON  # aka @common
235   case MCSA_ELF_TypeNoType:      /// .type _foo, STT_NOTYPE  # aka @notype
236     assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
237     OS << ".type " << *Symbol << ','
238        << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
239     switch (Attribute) {
240     default: assert(0 && "Unknown ELF .type");
241     case MCSA_ELF_TypeFunction:    OS << "function"; break;
242     case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
243     case MCSA_ELF_TypeObject:      OS << "object"; break;
244     case MCSA_ELF_TypeTLS:         OS << "tls_object"; break;
245     case MCSA_ELF_TypeCommon:      OS << "common"; break;
246     case MCSA_ELF_TypeNoType:      OS << "no_type"; break;
247     }
248     EmitEOL();
249     return;
250   case MCSA_Global: // .globl/.global
251     OS << MAI.getGlobalDirective();
252     break;
253   case MCSA_Hidden:         OS << ".hidden ";          break;
254   case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
255   case MCSA_Internal:       OS << ".internal ";        break;
256   case MCSA_LazyReference:  OS << ".lazy_reference ";  break;
257   case MCSA_Local:          OS << ".local ";           break;
258   case MCSA_NoDeadStrip:    OS << ".no_dead_strip ";   break;
259   case MCSA_PrivateExtern:  OS << ".private_extern ";  break;
260   case MCSA_Protected:      OS << ".protected ";       break;
261   case MCSA_Reference:      OS << ".reference ";       break;
262   case MCSA_Weak:           OS << ".weak ";            break;
263   case MCSA_WeakDefinition: OS << ".weak_definition "; break;
264       // .weak_reference
265   case MCSA_WeakReference:  OS << MAI.getWeakRefDirective(); break;
266   }
267
268   OS << *Symbol;
269   EmitEOL();
270 }
271
272 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
273   OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
274   EmitEOL();
275 }
276
277 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
278   assert(MAI.hasDotTypeDotSizeDirective());
279   OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
280 }
281
282 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
283                                      unsigned ByteAlignment) {
284   OS << "\t.comm\t" << *Symbol << ',' << Size;
285   if (ByteAlignment != 0) {
286     if (MAI.getAlignmentIsInBytes())
287       OS << ',' << ByteAlignment;
288     else
289       OS << ',' << Log2_32(ByteAlignment);
290   }
291   EmitEOL();
292 }
293
294 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
295 ///
296 /// @param Symbol - The common symbol to emit.
297 /// @param Size - The size of the common symbol.
298 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
299   assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
300   OS << "\t.lcomm\t" << *Symbol << ',' << Size;
301   EmitEOL();
302 }
303
304 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
305                                  unsigned Size, unsigned ByteAlignment) {
306   // Note: a .zerofill directive does not switch sections.
307   OS << ".zerofill ";
308   
309   // This is a mach-o specific directive.
310   const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
311   OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
312   
313   if (Symbol != NULL) {
314     OS << ',' << *Symbol << ',' << Size;
315     if (ByteAlignment != 0)
316       OS << ',' << Log2_32(ByteAlignment);
317   }
318   EmitEOL();
319 }
320
321 static inline char toOctal(int X) { return (X&7)+'0'; }
322
323 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
324   assert(CurSection && "Cannot emit contents before setting section!");
325   if (Data.empty()) return;
326   
327   if (Data.size() == 1) {
328     OS << MAI.getData8bitsDirective(AddrSpace);
329     OS << (unsigned)(unsigned char)Data[0];
330     EmitEOL();
331     return;
332   }
333
334   // If the data ends with 0 and the target supports .asciz, use it, otherwise
335   // use .ascii
336   if (MAI.getAscizDirective() && Data.back() == 0) {
337     OS << MAI.getAscizDirective();
338     Data = Data.substr(0, Data.size()-1);
339   } else {
340     OS << MAI.getAsciiDirective();
341   }
342
343   OS << " \"";
344   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
345     unsigned char C = Data[i];
346     if (C == '"' || C == '\\') {
347       OS << '\\' << (char)C;
348       continue;
349     }
350     
351     if (isprint((unsigned char)C)) {
352       OS << (char)C;
353       continue;
354     }
355     
356     switch (C) {
357     case '\b': OS << "\\b"; break;
358     case '\f': OS << "\\f"; break;
359     case '\n': OS << "\\n"; break;
360     case '\r': OS << "\\r"; break;
361     case '\t': OS << "\\t"; break;
362     default:
363       OS << '\\';
364       OS << toOctal(C >> 6);
365       OS << toOctal(C >> 3);
366       OS << toOctal(C >> 0);
367       break;
368     }
369   }
370   OS << '"';
371   EmitEOL();
372 }
373
374 /// EmitIntValue - Special case of EmitValue that avoids the client having
375 /// to pass in a MCExpr for constant integers.
376 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
377                                  unsigned AddrSpace) {
378   assert(CurSection && "Cannot emit contents before setting section!");
379   const char *Directive = 0;
380   switch (Size) {
381   default: break;
382   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
383   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
384   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
385   case 8:
386     Directive = MAI.getData64bitsDirective(AddrSpace);
387     // If the target doesn't support 64-bit data, emit as two 32-bit halves.
388     if (Directive) break;
389     if (isLittleEndian()) {
390       EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
391       EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
392     } else {
393       EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
394       EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
395     }
396     return;
397   }
398   
399   assert(Directive && "Invalid size for machine code value!");
400   OS << Directive << truncateToSize(Value, Size);
401   EmitEOL();
402 }
403
404 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
405                               unsigned AddrSpace) {
406   assert(CurSection && "Cannot emit contents before setting section!");
407   const char *Directive = 0;
408   switch (Size) {
409   default: break;
410   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
411   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
412   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
413   case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
414   }
415   
416   assert(Directive && "Invalid size for machine code value!");
417   OS << Directive << *truncateToSize(Value, Size);
418   EmitEOL();
419 }
420
421 /// EmitFill - Emit NumBytes bytes worth of the value specified by
422 /// FillValue.  This implements directives such as '.space'.
423 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
424                              unsigned AddrSpace) {
425   if (NumBytes == 0) return;
426   
427   if (AddrSpace == 0)
428     if (const char *ZeroDirective = MAI.getZeroDirective()) {
429       OS << ZeroDirective << NumBytes;
430       if (FillValue != 0)
431         OS << ',' << (int)FillValue;
432       EmitEOL();
433       return;
434     }
435
436   // Emit a byte at a time.
437   MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
438 }
439
440 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
441                                          unsigned ValueSize,
442                                          unsigned MaxBytesToEmit) {
443   // Some assemblers don't support non-power of two alignments, so we always
444   // emit alignments as a power of two if possible.
445   if (isPowerOf2_32(ByteAlignment)) {
446     switch (ValueSize) {
447     default: llvm_unreachable("Invalid size for machine code value!");
448     case 1: OS << MAI.getAlignDirective(); break;
449     // FIXME: use MAI for this!
450     case 2: OS << ".p2alignw "; break;
451     case 4: OS << ".p2alignl "; break;
452     case 8: llvm_unreachable("Unsupported alignment size!");
453     }
454     
455     if (MAI.getAlignmentIsInBytes())
456       OS << ByteAlignment;
457     else
458       OS << Log2_32(ByteAlignment);
459
460     if (Value || MaxBytesToEmit) {
461       OS << ", 0x";
462       OS.write_hex(truncateToSize(Value, ValueSize));
463
464       if (MaxBytesToEmit) 
465         OS << ", " << MaxBytesToEmit;
466     }
467     EmitEOL();
468     return;
469   }
470   
471   // Non-power of two alignment.  This is not widely supported by assemblers.
472   // FIXME: Parameterize this based on MAI.
473   switch (ValueSize) {
474   default: llvm_unreachable("Invalid size for machine code value!");
475   case 1: OS << ".balign";  break;
476   case 2: OS << ".balignw"; break;
477   case 4: OS << ".balignl"; break;
478   case 8: llvm_unreachable("Unsupported alignment size!");
479   }
480
481   OS << ' ' << ByteAlignment;
482   OS << ", " << truncateToSize(Value, ValueSize);
483   if (MaxBytesToEmit) 
484     OS << ", " << MaxBytesToEmit;
485   EmitEOL();
486 }
487
488 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
489                                       unsigned char Value) {
490   // FIXME: Verify that Offset is associated with the current section.
491   OS << ".org " << *Offset << ", " << (unsigned) Value;
492   EmitEOL();
493 }
494
495 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
496   assert(CurSection && "Cannot emit contents before setting section!");
497
498   // If we have an AsmPrinter, use that to print.
499   if (InstPrinter) {
500     InstPrinter->printInst(&Inst);
501     EmitEOL();
502
503     // Show the encoding if we have a code emitter.
504     if (Emitter) {
505       SmallString<256> Code;
506       raw_svector_ostream VecOS(Code);
507       Emitter->EncodeInstruction(Inst, VecOS);
508       VecOS.flush();
509   
510       OS.indent(20);
511       OS << " # encoding: [";
512       for (unsigned i = 0, e = Code.size(); i != e; ++i) {
513         if (i)
514           OS << ',';
515         OS << format("%#04x", uint8_t(Code[i]));
516       }
517       OS << "]\n";
518     }
519
520     return;
521   }
522
523   // Otherwise fall back to a structural printing for now. Eventually we should
524   // always have access to the target specific printer.
525   Inst.print(OS, &MAI);
526   EmitEOL();
527 }
528
529 void MCAsmStreamer::Finish() {
530   OS.flush();
531 }
532     
533 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
534                                     formatted_raw_ostream &OS,
535                                     const MCAsmInfo &MAI, bool isLittleEndian,
536                                     bool isVerboseAsm, MCInstPrinter *IP,
537                                     MCCodeEmitter *CE) {
538   return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,
539                            IP, CE);
540 }