MC: Make TargetAsmBackend available to the AsmStreamer.
[oota-llvm.git] / lib / Target / PTX / PTXMCAsmStreamer.cpp
1 //===- lib/Target/PTX/PTXMCAsmStreamer.cpp - PTX 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/ADT/OwningPtr.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCCodeEmitter.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCInstPrinter.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCSymbol.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 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetAsmInfo.h"
27
28 using namespace llvm;
29
30 namespace {
31 class PTXMCAsmStreamer : public MCStreamer {
32   formatted_raw_ostream &OS;
33   const MCAsmInfo &MAI;
34   OwningPtr<MCInstPrinter> InstPrinter;
35   OwningPtr<MCCodeEmitter> Emitter;
36
37   SmallString<128> CommentToEmit;
38   raw_svector_ostream CommentStream;
39
40   unsigned IsVerboseAsm : 1;
41   unsigned ShowInst : 1;
42
43 public:
44   PTXMCAsmStreamer(MCContext &Context,
45                    formatted_raw_ostream &os,
46                    bool isVerboseAsm, bool useLoc,
47                    MCInstPrinter *printer,
48                    MCCodeEmitter *emitter,
49                    bool showInst)
50     : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
51       InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit),
52       IsVerboseAsm(isVerboseAsm),
53       ShowInst(showInst) {
54     if (InstPrinter && IsVerboseAsm)
55       InstPrinter->setCommentStream(CommentStream);
56   }
57
58   ~PTXMCAsmStreamer() {}
59
60   inline void EmitEOL() {
61     // If we don't have any comments, just emit a \n.
62     if (!IsVerboseAsm) {
63       OS << '\n';
64       return;
65     }
66     EmitCommentsAndEOL();
67   }
68   void EmitCommentsAndEOL();
69
70   /// isVerboseAsm - Return true if this streamer supports verbose assembly at
71   /// all.
72   virtual bool isVerboseAsm() const { return IsVerboseAsm; }
73
74   /// hasRawTextSupport - We support EmitRawText.
75   virtual bool hasRawTextSupport() const { return true; }
76
77   /// AddComment - Add a comment that can be emitted to the generated .s
78   /// file if applicable as a QoI issue to make the output of the compiler
79   /// more readable.  This only affects the MCAsmStreamer, and only when
80   /// verbose assembly output is enabled.
81   virtual void AddComment(const Twine &T);
82
83   /// AddEncodingComment - Add a comment showing the encoding of an instruction.
84   virtual void AddEncodingComment(const MCInst &Inst);
85
86   /// GetCommentOS - Return a raw_ostream that comments can be written to.
87   /// Unlike AddComment, you are required to terminate comments with \n if you
88   /// use this method.
89   virtual raw_ostream &GetCommentOS() {
90     if (!IsVerboseAsm)
91       return nulls();  // Discard comments unless in verbose asm mode.
92     return CommentStream;
93   }
94
95   /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
96   virtual void AddBlankLine() {
97     EmitEOL();
98   }
99
100   /// @name MCStreamer Interface
101   /// @{
102
103   virtual void SwitchSection(const MCSection *Section);
104
105   virtual void InitSections() {
106   }
107
108   virtual void EmitLabel(MCSymbol *Symbol);
109
110   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
111
112   virtual void EmitThumbFunc(MCSymbol *Func);
113
114   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
115
116   virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
117
118   virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
119                                         const MCSymbol *LastLabel,
120                                         const MCSymbol *Label);
121
122   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
123
124   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
125   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
126   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
127   virtual void EmitCOFFSymbolType(int Type);
128   virtual void EndCOFFSymbolDef();
129   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
130   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
131                                 unsigned ByteAlignment);
132
133   /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
134   ///
135   /// @param Symbol - The common symbol to emit.
136   /// @param Size - The size of the common symbol.
137   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
138
139   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
140                             unsigned Size = 0, unsigned ByteAlignment = 0);
141
142   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
143                               uint64_t Size, unsigned ByteAlignment = 0);
144
145   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
146
147   virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
148                              bool isPCRel, unsigned AddrSpace);
149   virtual void EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
150   virtual void EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
151   virtual void EmitGPRel32Value(const MCExpr *Value);
152
153
154   virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
155                         unsigned AddrSpace);
156
157   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
158                                     unsigned ValueSize = 1,
159                                     unsigned MaxBytesToEmit = 0);
160
161   virtual void EmitCodeAlignment(unsigned ByteAlignment,
162                                  unsigned MaxBytesToEmit = 0);
163
164   virtual void EmitValueToOffset(const MCExpr *Offset,
165                                  unsigned char Value = 0);
166
167   virtual void EmitFileDirective(StringRef Filename);
168   virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
169
170   virtual void EmitInstruction(const MCInst &Inst);
171
172   /// EmitRawText - If this file is backed by an assembly streamer, this dumps
173   /// the specified string in the output .s file.  This capability is
174   /// indicated by the hasRawTextSupport() predicate.
175   virtual void EmitRawText(StringRef String);
176
177   virtual void Finish();
178
179   /// @}
180
181 }; // class PTXMCAsmStreamer
182
183 }
184
185 /// TODO: Add appropriate implementation of Emit*() methods when needed
186
187 void PTXMCAsmStreamer::AddComment(const Twine &T) {
188   if (!IsVerboseAsm) return;
189
190   // Make sure that CommentStream is flushed.
191   CommentStream.flush();
192
193   T.toVector(CommentToEmit);
194   // Each comment goes on its own line.
195   CommentToEmit.push_back('\n');
196
197   // Tell the comment stream that the vector changed underneath it.
198   CommentStream.resync();
199 }
200
201 void PTXMCAsmStreamer::EmitCommentsAndEOL() {
202   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
203     OS << '\n';
204     return;
205   }
206
207   CommentStream.flush();
208   StringRef Comments = CommentToEmit.str();
209
210   assert(Comments.back() == '\n' &&
211          "Comment array not newline terminated");
212   do {
213     // Emit a line of comments.
214     OS.PadToColumn(MAI.getCommentColumn());
215     size_t Position = Comments.find('\n');
216     OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
217
218     Comments = Comments.substr(Position+1);
219   } while (!Comments.empty());
220
221   CommentToEmit.clear();
222   // Tell the comment stream that the vector changed underneath it.
223   CommentStream.resync();
224 }
225
226 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
227   assert(Bytes && "Invalid size!");
228   return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
229 }
230
231 void PTXMCAsmStreamer::SwitchSection(const MCSection *Section) {
232   assert(Section && "Cannot switch to a null section!");
233   if (Section != CurSection) {
234     PrevSection = CurSection;
235     CurSection = Section;
236   }
237 }
238
239 void PTXMCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
240   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
241   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
242   assert(CurSection && "Cannot emit before setting section!");
243
244   OS << *Symbol << MAI.getLabelSuffix();
245   EmitEOL();
246   Symbol->setSection(*CurSection);
247 }
248
249 void PTXMCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {}
250
251 void PTXMCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {}
252
253 void PTXMCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
254   OS << *Symbol << " = " << *Value;
255   EmitEOL();
256
257   // FIXME: Lift context changes into super class.
258   Symbol->setVariableValue(Value);
259 }
260
261 void PTXMCAsmStreamer::EmitWeakReference(MCSymbol *Alias,
262                                          const MCSymbol *Symbol) {
263   OS << ".weakref " << *Alias << ", " << *Symbol;
264   EmitEOL();
265 }
266
267 void PTXMCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
268                                                 const MCSymbol *LastLabel,
269                                                 const MCSymbol *Label) {
270   report_fatal_error("Unimplemented.");
271 }
272
273 void PTXMCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
274                                            MCSymbolAttr Attribute) {}
275
276 void PTXMCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
277
278 void PTXMCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
279
280 void PTXMCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {}
281
282 void PTXMCAsmStreamer::EmitCOFFSymbolType (int Type) {}
283
284 void PTXMCAsmStreamer::EndCOFFSymbolDef() {}
285
286 void PTXMCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
287
288 void PTXMCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
289                                         unsigned ByteAlignment) {}
290
291 void PTXMCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
292
293 void PTXMCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
294                                     unsigned Size, unsigned ByteAlignment) {}
295
296 void PTXMCAsmStreamer::EmitTBSSSymbol(const MCSection *Section,
297                                       MCSymbol *Symbol,
298                                       uint64_t Size, unsigned ByteAlignment) {}
299
300 static inline char toOctal(int X) { return (X&7)+'0'; }
301
302 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
303   OS << '"';
304
305   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
306     unsigned char C = Data[i];
307     if (C == '"' || C == '\\') {
308       OS << '\\' << (char)C;
309       continue;
310     }
311
312     if (isprint((unsigned char)C)) {
313       OS << (char)C;
314       continue;
315     }
316
317     switch (C) {
318       case '\b': OS << "\\b"; break;
319       case '\f': OS << "\\f"; break;
320       case '\n': OS << "\\n"; break;
321       case '\r': OS << "\\r"; break;
322       case '\t': OS << "\\t"; break;
323       default:
324         OS << '\\';
325         OS << toOctal(C >> 6);
326         OS << toOctal(C >> 3);
327         OS << toOctal(C >> 0);
328         break;
329     }
330   }
331
332   OS << '"';
333 }
334
335 void PTXMCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
336   assert(CurSection && "Cannot emit contents before setting section!");
337   if (Data.empty()) return;
338
339   if (Data.size() == 1) {
340     OS << MAI.getData8bitsDirective(AddrSpace);
341     OS << (unsigned)(unsigned char)Data[0];
342     EmitEOL();
343     return;
344   }
345
346   // If the data ends with 0 and the target supports .asciz, use it, otherwise
347   // use .ascii
348   if (MAI.getAscizDirective() && Data.back() == 0) {
349     OS << MAI.getAscizDirective();
350     Data = Data.substr(0, Data.size()-1);
351   } else {
352     OS << MAI.getAsciiDirective();
353   }
354
355   OS << ' ';
356   PrintQuotedString(Data, OS);
357   EmitEOL();
358 }
359
360 void PTXMCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
361                                      bool isPCRel, unsigned AddrSpace) {
362   assert(CurSection && "Cannot emit contents before setting section!");
363   assert(!isPCRel && "Cannot emit pc relative relocations!");
364   const char *Directive = 0;
365   switch (Size) {
366   default: break;
367   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
368   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
369   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
370   case 8:
371     Directive = MAI.getData64bitsDirective(AddrSpace);
372     // If the target doesn't support 64-bit data, emit as two 32-bit halves.
373     if (Directive) break;
374     int64_t IntValue;
375     if (!Value->EvaluateAsAbsolute(IntValue))
376       report_fatal_error("Don't know how to emit this value.");
377     if (getContext().getTargetAsmInfo().isLittleEndian()) {
378       EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
379       EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
380     } else {
381       EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
382       EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
383     }
384     return;
385   }
386
387   assert(Directive && "Invalid size for machine code value!");
388   OS << Directive << *Value;
389   EmitEOL();
390 }
391
392 void PTXMCAsmStreamer::EmitULEB128Value(const MCExpr *Value,
393                                         unsigned AddrSpace) {
394   assert(MAI.hasLEB128() && "Cannot print a .uleb");
395   OS << ".uleb128 " << *Value;
396   EmitEOL();
397 }
398
399 void PTXMCAsmStreamer::EmitSLEB128Value(const MCExpr *Value,
400                                         unsigned AddrSpace) {
401   assert(MAI.hasLEB128() && "Cannot print a .sleb");
402   OS << ".sleb128 " << *Value;
403   EmitEOL();
404 }
405
406 void PTXMCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
407   assert(MAI.getGPRel32Directive() != 0);
408   OS << MAI.getGPRel32Directive() << *Value;
409   EmitEOL();
410 }
411
412
413 /// EmitFill - Emit NumBytes bytes worth of the value specified by
414 /// FillValue.  This implements directives such as '.space'.
415 void PTXMCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
416                                 unsigned AddrSpace) {
417   if (NumBytes == 0) return;
418
419   if (AddrSpace == 0)
420     if (const char *ZeroDirective = MAI.getZeroDirective()) {
421       OS << ZeroDirective << NumBytes;
422       if (FillValue != 0)
423         OS << ',' << (int)FillValue;
424       EmitEOL();
425       return;
426     }
427
428   // Emit a byte at a time.
429   MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
430 }
431
432 void PTXMCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
433                                             unsigned ValueSize,
434                                             unsigned MaxBytesToEmit) {
435   // Some assemblers don't support non-power of two alignments, so we always
436   // emit alignments as a power of two if possible.
437   if (isPowerOf2_32(ByteAlignment)) {
438     switch (ValueSize) {
439     default: llvm_unreachable("Invalid size for machine code value!");
440     case 1: OS << MAI.getAlignDirective(); break;
441     // FIXME: use MAI for this!
442     case 2: OS << ".p2alignw "; break;
443     case 4: OS << ".p2alignl "; break;
444     case 8: llvm_unreachable("Unsupported alignment size!");
445     }
446
447     if (MAI.getAlignmentIsInBytes())
448       OS << ByteAlignment;
449     else
450       OS << Log2_32(ByteAlignment);
451
452     if (Value || MaxBytesToEmit) {
453       OS << ", 0x";
454       OS.write_hex(truncateToSize(Value, ValueSize));
455
456       if (MaxBytesToEmit)
457         OS << ", " << MaxBytesToEmit;
458     }
459     EmitEOL();
460     return;
461   }
462
463   // Non-power of two alignment.  This is not widely supported by assemblers.
464   // FIXME: Parameterize this based on MAI.
465   switch (ValueSize) {
466   default: llvm_unreachable("Invalid size for machine code value!");
467   case 1: OS << ".balign";  break;
468   case 2: OS << ".balignw"; break;
469   case 4: OS << ".balignl"; break;
470   case 8: llvm_unreachable("Unsupported alignment size!");
471   }
472
473   OS << ' ' << ByteAlignment;
474   OS << ", " << truncateToSize(Value, ValueSize);
475   if (MaxBytesToEmit)
476     OS << ", " << MaxBytesToEmit;
477   EmitEOL();
478 }
479
480 void PTXMCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
481                                          unsigned MaxBytesToEmit) {}
482
483 void PTXMCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
484                                          unsigned char Value) {}
485
486
487 void PTXMCAsmStreamer::EmitFileDirective(StringRef Filename) {
488   assert(MAI.hasSingleParameterDotFile());
489   OS << "\t.file\t";
490   PrintQuotedString(Filename, OS);
491   EmitEOL();
492 }
493
494 // FIXME: should we inherit from MCAsmStreamer?
495 bool PTXMCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
496                                               StringRef Filename){
497   OS << "\t.file\t" << FileNo << ' ';
498   PrintQuotedString(Filename, OS);
499   EmitEOL();
500   return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
501 }
502
503 void PTXMCAsmStreamer::AddEncodingComment(const MCInst &Inst) {}
504
505 void PTXMCAsmStreamer::EmitInstruction(const MCInst &Inst) {
506   assert(CurSection && "Cannot emit contents before setting section!");
507
508   // Show the encoding in a comment if we have a code emitter.
509   if (Emitter)
510     AddEncodingComment(Inst);
511
512   // Show the MCInst if enabled.
513   if (ShowInst) {
514     Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
515     GetCommentOS() << "\n";
516   }
517
518   // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
519   if (InstPrinter)
520     InstPrinter->printInst(&Inst, OS);
521   else
522     Inst.print(OS, &MAI);
523   EmitEOL();
524 }
525
526 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
527 /// the specified string in the output .s file.  This capability is
528 /// indicated by the hasRawTextSupport() predicate.
529 void PTXMCAsmStreamer::EmitRawText(StringRef String) {
530   if (!String.empty() && String.back() == '\n')
531     String = String.substr(0, String.size()-1);
532   OS << String;
533   EmitEOL();
534 }
535
536 void PTXMCAsmStreamer::Finish() {}
537
538 namespace llvm {
539   MCStreamer *createPTXAsmStreamer(MCContext &Context,
540                                    formatted_raw_ostream &OS,
541                                    bool isVerboseAsm, bool useLoc,
542                                    MCInstPrinter *IP,
543                                    MCCodeEmitter *CE, TargetAsmBackend *TAB,
544                                    bool ShowInst) {
545     return new PTXMCAsmStreamer(Context, OS, isVerboseAsm, useLoc,
546                                 IP, CE, ShowInst);
547   }
548 }