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