MCAsmStreamer.cpp revision ba21957cbd7b25e3d25a3e9befe6151000242853
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/OwningPtr.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Support/ErrorHandling.h"
23#include "llvm/Support/MathExtras.h"
24#include "llvm/Support/Format.h"
25#include "llvm/Support/FormattedStream.h"
26using namespace llvm;
27
28namespace {
29
30class MCAsmStreamer : public MCStreamer {
31  formatted_raw_ostream &OS;
32  const MCAsmInfo &MAI;
33  OwningPtr<MCInstPrinter> InstPrinter;
34  OwningPtr<MCCodeEmitter> Emitter;
35
36  SmallString<128> CommentToEmit;
37  raw_svector_ostream CommentStream;
38
39  unsigned IsLittleEndian : 1;
40  unsigned IsVerboseAsm : 1;
41  unsigned ShowInst : 1;
42
43public:
44  MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
45                bool isLittleEndian, bool isVerboseAsm, MCInstPrinter *printer,
46                MCCodeEmitter *emitter, bool showInst)
47    : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
48      InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit),
49      IsLittleEndian(isLittleEndian), IsVerboseAsm(isVerboseAsm),
50      ShowInst(showInst) {
51    if (InstPrinter && IsVerboseAsm)
52      InstPrinter->setCommentStream(CommentStream);
53  }
54  ~MCAsmStreamer() {}
55
56  bool isLittleEndian() const { return IsLittleEndian; }
57
58  inline void EmitEOL() {
59    // If we don't have any comments, just emit a \n.
60    if (!IsVerboseAsm) {
61      OS << '\n';
62      return;
63    }
64    EmitCommentsAndEOL();
65  }
66  void EmitCommentsAndEOL();
67
68  /// isVerboseAsm - Return true if this streamer supports verbose assembly at
69  /// all.
70  virtual bool isVerboseAsm() const { return IsVerboseAsm; }
71
72  /// hasRawTextSupport - We support EmitRawText.
73  virtual bool hasRawTextSupport() const { return true; }
74
75  /// AddComment - Add a comment that can be emitted to the generated .s
76  /// file if applicable as a QoI issue to make the output of the compiler
77  /// more readable.  This only affects the MCAsmStreamer, and only when
78  /// verbose assembly output is enabled.
79  virtual void AddComment(const Twine &T);
80
81  /// AddEncodingComment - Add a comment showing the encoding of an instruction.
82  virtual void AddEncodingComment(const MCInst &Inst);
83
84  /// GetCommentOS - Return a raw_ostream that comments can be written to.
85  /// Unlike AddComment, you are required to terminate comments with \n if you
86  /// use this method.
87  virtual raw_ostream &GetCommentOS() {
88    if (!IsVerboseAsm)
89      return nulls();  // Discard comments unless in verbose asm mode.
90    return CommentStream;
91  }
92
93  /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
94  virtual void AddBlankLine() {
95    EmitEOL();
96  }
97
98  /// @name MCStreamer Interface
99  /// @{
100
101  virtual void SwitchSection(const MCSection *Section);
102
103  virtual void InitSections() {
104    // FIXME, this is MachO specific, but the testsuite
105    // expects this.
106    SwitchSection(getContext().getMachOSection("__TEXT", "__text",
107                         MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
108                         0, SectionKind::getText()));
109  }
110
111  virtual void EmitLabel(MCSymbol *Symbol);
112
113  virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
114  virtual void EmitThumbFunc(MCSymbol *Func);
115
116  virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
117  virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
118
119  virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
120
121  virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
122  virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
123  virtual void EmitCOFFSymbolStorageClass(int StorageClass);
124  virtual void EmitCOFFSymbolType(int Type);
125  virtual void EndCOFFSymbolDef();
126  virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
127  virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
128                                unsigned ByteAlignment);
129
130  /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
131  ///
132  /// @param Symbol - The common symbol to emit.
133  /// @param Size - The size of the common symbol.
134  virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
135
136  virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
137                            unsigned Size = 0, unsigned ByteAlignment = 0);
138
139  virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
140                               uint64_t Size, unsigned ByteAlignment = 0);
141
142  virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
143
144  virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
145
146  virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
147
148  virtual void EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
149
150  virtual void EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
151
152  virtual void EmitGPRel32Value(const MCExpr *Value);
153
154
155  virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
156                        unsigned AddrSpace);
157
158  virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
159                                    unsigned ValueSize = 1,
160                                    unsigned MaxBytesToEmit = 0);
161
162  virtual void EmitCodeAlignment(unsigned ByteAlignment,
163                                 unsigned MaxBytesToEmit = 0);
164
165  virtual void EmitValueToOffset(const MCExpr *Offset,
166                                 unsigned char Value = 0);
167
168  virtual void EmitFileDirective(StringRef Filename);
169  virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
170
171  virtual void EmitInstruction(const MCInst &Inst);
172
173  /// EmitRawText - If this file is backed by an assembly streamer, this dumps
174  /// the specified string in the output .s file.  This capability is
175  /// indicated by the hasRawTextSupport() predicate.
176  virtual void EmitRawText(StringRef String);
177
178  virtual void Finish();
179
180  /// @}
181};
182
183} // end anonymous namespace.
184
185/// AddComment - Add a comment that can be emitted to the generated .s
186/// file if applicable as a QoI issue to make the output of the compiler
187/// more readable.  This only affects the MCAsmStreamer, and only when
188/// verbose assembly output is enabled.
189void MCAsmStreamer::AddComment(const Twine &T) {
190  if (!IsVerboseAsm) return;
191
192  // Make sure that CommentStream is flushed.
193  CommentStream.flush();
194
195  T.toVector(CommentToEmit);
196  // Each comment goes on its own line.
197  CommentToEmit.push_back('\n');
198
199  // Tell the comment stream that the vector changed underneath it.
200  CommentStream.resync();
201}
202
203void MCAsmStreamer::EmitCommentsAndEOL() {
204  if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
205    OS << '\n';
206    return;
207  }
208
209  CommentStream.flush();
210  StringRef Comments = CommentToEmit.str();
211
212  assert(Comments.back() == '\n' &&
213         "Comment array not newline terminated");
214  do {
215    // Emit a line of comments.
216    OS.PadToColumn(MAI.getCommentColumn());
217    size_t Position = Comments.find('\n');
218    OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
219
220    Comments = Comments.substr(Position+1);
221  } while (!Comments.empty());
222
223  CommentToEmit.clear();
224  // Tell the comment stream that the vector changed underneath it.
225  CommentStream.resync();
226}
227
228static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
229  assert(Bytes && "Invalid size!");
230  return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
231}
232
233void MCAsmStreamer::SwitchSection(const MCSection *Section) {
234  assert(Section && "Cannot switch to a null section!");
235  if (Section != CurSection) {
236    PrevSection = CurSection;
237    CurSection = Section;
238    Section->PrintSwitchToSection(MAI, OS);
239  }
240}
241
242void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
243  assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
244  assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
245  assert(CurSection && "Cannot emit before setting section!");
246
247  OS << *Symbol << MAI.getLabelSuffix();
248  EmitEOL();
249  Symbol->setSection(*CurSection);
250}
251
252void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
253  switch (Flag) {
254  default: assert(0 && "Invalid flag!");
255  case MCAF_SyntaxUnified:         OS << "\t.syntax unified"; break;
256  case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
257  case MCAF_Code16:                OS << "\t.code\t16"; break;
258  case MCAF_Code32:                OS << "\t.code\t32"; break;
259  }
260  EmitEOL();
261}
262
263void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
264  // This needs to emit to a temporary string to get properly quoted
265  // MCSymbols when they have spaces in them.
266  OS << "\t.thumb_func";
267  if (Func)
268    OS << '\t' << *Func;
269  EmitEOL();
270}
271
272void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
273  OS << *Symbol << " = " << *Value;
274  EmitEOL();
275
276  // FIXME: Lift context changes into super class.
277  Symbol->setVariableValue(Value);
278}
279
280void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
281  OS << ".weakref " << *Alias << ", " << *Symbol;
282  EmitEOL();
283}
284
285void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
286                                        MCSymbolAttr Attribute) {
287  switch (Attribute) {
288  case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
289  case MCSA_ELF_TypeFunction:    /// .type _foo, STT_FUNC  # aka @function
290  case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
291  case MCSA_ELF_TypeObject:      /// .type _foo, STT_OBJECT  # aka @object
292  case MCSA_ELF_TypeTLS:         /// .type _foo, STT_TLS     # aka @tls_object
293  case MCSA_ELF_TypeCommon:      /// .type _foo, STT_COMMON  # aka @common
294  case MCSA_ELF_TypeNoType:      /// .type _foo, STT_NOTYPE  # aka @notype
295    assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
296    OS << "\t.type\t" << *Symbol << ','
297       << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
298    switch (Attribute) {
299    default: assert(0 && "Unknown ELF .type");
300    case MCSA_ELF_TypeFunction:    OS << "function"; break;
301    case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
302    case MCSA_ELF_TypeObject:      OS << "object"; break;
303    case MCSA_ELF_TypeTLS:         OS << "tls_object"; break;
304    case MCSA_ELF_TypeCommon:      OS << "common"; break;
305    case MCSA_ELF_TypeNoType:      OS << "no_type"; break;
306    }
307    EmitEOL();
308    return;
309  case MCSA_Global: // .globl/.global
310    OS << MAI.getGlobalDirective();
311    break;
312  case MCSA_Hidden:         OS << "\t.hidden\t";          break;
313  case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
314  case MCSA_Internal:       OS << "\t.internal\t";        break;
315  case MCSA_LazyReference:  OS << "\t.lazy_reference\t";  break;
316  case MCSA_Local:          OS << "\t.local\t";           break;
317  case MCSA_NoDeadStrip:    OS << "\t.no_dead_strip\t";   break;
318  case MCSA_PrivateExtern:  OS << "\t.private_extern\t";  break;
319  case MCSA_Protected:      OS << "\t.protected\t";       break;
320  case MCSA_Reference:      OS << "\t.reference\t";       break;
321  case MCSA_Weak:           OS << "\t.weak\t";            break;
322  case MCSA_WeakDefinition: OS << "\t.weak_definition\t"; break;
323      // .weak_reference
324  case MCSA_WeakReference:  OS << MAI.getWeakRefDirective(); break;
325  case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
326  }
327
328  OS << *Symbol;
329  EmitEOL();
330}
331
332void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
333  OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
334  EmitEOL();
335}
336
337void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
338  OS << "\t.def\t " << *Symbol << ';';
339  EmitEOL();
340}
341
342void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
343  OS << "\t.scl\t" << StorageClass << ';';
344  EmitEOL();
345}
346
347void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
348  OS << "\t.type\t" << Type << ';';
349  EmitEOL();
350}
351
352void MCAsmStreamer::EndCOFFSymbolDef() {
353  OS << "\t.endef";
354  EmitEOL();
355}
356
357void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
358  assert(MAI.hasDotTypeDotSizeDirective());
359  OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
360}
361
362void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
363                                     unsigned ByteAlignment) {
364  OS << "\t.comm\t" << *Symbol << ',' << Size;
365  if (ByteAlignment != 0) {
366    if (MAI.getCOMMDirectiveAlignmentIsInBytes())
367      OS << ',' << ByteAlignment;
368    else
369      OS << ',' << Log2_32(ByteAlignment);
370  }
371  EmitEOL();
372}
373
374/// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
375///
376/// @param Symbol - The common symbol to emit.
377/// @param Size - The size of the common symbol.
378void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
379  assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
380  OS << "\t.lcomm\t" << *Symbol << ',' << Size;
381  EmitEOL();
382}
383
384void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
385                                 unsigned Size, unsigned ByteAlignment) {
386  // Note: a .zerofill directive does not switch sections.
387  OS << ".zerofill ";
388
389  // This is a mach-o specific directive.
390  const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
391  OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
392
393  if (Symbol != NULL) {
394    OS << ',' << *Symbol << ',' << Size;
395    if (ByteAlignment != 0)
396      OS << ',' << Log2_32(ByteAlignment);
397  }
398  EmitEOL();
399}
400
401// .tbss sym, size, align
402// This depends that the symbol has already been mangled from the original,
403// e.g. _a.
404void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
405                                   uint64_t Size, unsigned ByteAlignment) {
406  assert(Symbol != NULL && "Symbol shouldn't be NULL!");
407  // Instead of using the Section we'll just use the shortcut.
408  // This is a mach-o specific directive and section.
409  OS << ".tbss " << *Symbol << ", " << Size;
410
411  // Output align if we have it.  We default to 1 so don't bother printing
412  // that.
413  if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
414
415  EmitEOL();
416}
417
418static inline char toOctal(int X) { return (X&7)+'0'; }
419
420static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
421  OS << '"';
422
423  for (unsigned i = 0, e = Data.size(); i != e; ++i) {
424    unsigned char C = Data[i];
425    if (C == '"' || C == '\\') {
426      OS << '\\' << (char)C;
427      continue;
428    }
429
430    if (isprint((unsigned char)C)) {
431      OS << (char)C;
432      continue;
433    }
434
435    switch (C) {
436      case '\b': OS << "\\b"; break;
437      case '\f': OS << "\\f"; break;
438      case '\n': OS << "\\n"; break;
439      case '\r': OS << "\\r"; break;
440      case '\t': OS << "\\t"; break;
441      default:
442        OS << '\\';
443        OS << toOctal(C >> 6);
444        OS << toOctal(C >> 3);
445        OS << toOctal(C >> 0);
446        break;
447    }
448  }
449
450  OS << '"';
451}
452
453
454void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
455  assert(CurSection && "Cannot emit contents before setting section!");
456  if (Data.empty()) return;
457
458  if (Data.size() == 1) {
459    OS << MAI.getData8bitsDirective(AddrSpace);
460    OS << (unsigned)(unsigned char)Data[0];
461    EmitEOL();
462    return;
463  }
464
465  // If the data ends with 0 and the target supports .asciz, use it, otherwise
466  // use .ascii
467  if (MAI.getAscizDirective() && Data.back() == 0) {
468    OS << MAI.getAscizDirective();
469    Data = Data.substr(0, Data.size()-1);
470  } else {
471    OS << MAI.getAsciiDirective();
472  }
473
474  OS << ' ';
475  PrintQuotedString(Data, OS);
476  EmitEOL();
477}
478
479/// EmitIntValue - Special case of EmitValue that avoids the client having
480/// to pass in a MCExpr for constant integers.
481void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
482                                 unsigned AddrSpace) {
483  assert(CurSection && "Cannot emit contents before setting section!");
484  const char *Directive = 0;
485  switch (Size) {
486  default: break;
487  case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
488  case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
489  case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
490  case 8:
491    Directive = MAI.getData64bitsDirective(AddrSpace);
492    // If the target doesn't support 64-bit data, emit as two 32-bit halves.
493    if (Directive) break;
494    if (isLittleEndian()) {
495      EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
496      EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
497    } else {
498      EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
499      EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
500    }
501    return;
502  }
503
504  assert(Directive && "Invalid size for machine code value!");
505  OS << Directive << truncateToSize(Value, Size);
506  EmitEOL();
507}
508
509void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
510                              unsigned AddrSpace) {
511  assert(CurSection && "Cannot emit contents before setting section!");
512  const char *Directive = 0;
513  switch (Size) {
514  default: break;
515  case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
516  case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
517  case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
518  case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
519  }
520
521  assert(Directive && "Invalid size for machine code value!");
522  OS << Directive << *Value;
523  EmitEOL();
524}
525
526void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace) {
527  assert(MAI.hasLEB128() && "Cannot print a .uleb");
528  OS << ".uleb128 " << *Value;
529  EmitEOL();
530}
531
532void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace) {
533  assert(MAI.hasLEB128() && "Cannot print a .sleb");
534  OS << ".sleb128 " << *Value;
535  EmitEOL();
536}
537
538void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
539  assert(MAI.getGPRel32Directive() != 0);
540  OS << MAI.getGPRel32Directive() << *Value;
541  EmitEOL();
542}
543
544
545/// EmitFill - Emit NumBytes bytes worth of the value specified by
546/// FillValue.  This implements directives such as '.space'.
547void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
548                             unsigned AddrSpace) {
549  if (NumBytes == 0) return;
550
551  if (AddrSpace == 0)
552    if (const char *ZeroDirective = MAI.getZeroDirective()) {
553      OS << ZeroDirective << NumBytes;
554      if (FillValue != 0)
555        OS << ',' << (int)FillValue;
556      EmitEOL();
557      return;
558    }
559
560  // Emit a byte at a time.
561  MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
562}
563
564void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
565                                         unsigned ValueSize,
566                                         unsigned MaxBytesToEmit) {
567  // Some assemblers don't support non-power of two alignments, so we always
568  // emit alignments as a power of two if possible.
569  if (isPowerOf2_32(ByteAlignment)) {
570    switch (ValueSize) {
571    default: llvm_unreachable("Invalid size for machine code value!");
572    case 1: OS << MAI.getAlignDirective(); break;
573    // FIXME: use MAI for this!
574    case 2: OS << ".p2alignw "; break;
575    case 4: OS << ".p2alignl "; break;
576    case 8: llvm_unreachable("Unsupported alignment size!");
577    }
578
579    if (MAI.getAlignmentIsInBytes())
580      OS << ByteAlignment;
581    else
582      OS << Log2_32(ByteAlignment);
583
584    if (Value || MaxBytesToEmit) {
585      OS << ", 0x";
586      OS.write_hex(truncateToSize(Value, ValueSize));
587
588      if (MaxBytesToEmit)
589        OS << ", " << MaxBytesToEmit;
590    }
591    EmitEOL();
592    return;
593  }
594
595  // Non-power of two alignment.  This is not widely supported by assemblers.
596  // FIXME: Parameterize this based on MAI.
597  switch (ValueSize) {
598  default: llvm_unreachable("Invalid size for machine code value!");
599  case 1: OS << ".balign";  break;
600  case 2: OS << ".balignw"; break;
601  case 4: OS << ".balignl"; break;
602  case 8: llvm_unreachable("Unsupported alignment size!");
603  }
604
605  OS << ' ' << ByteAlignment;
606  OS << ", " << truncateToSize(Value, ValueSize);
607  if (MaxBytesToEmit)
608    OS << ", " << MaxBytesToEmit;
609  EmitEOL();
610}
611
612void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
613                                      unsigned MaxBytesToEmit) {
614  // Emit with a text fill value.
615  EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
616                       1, MaxBytesToEmit);
617}
618
619void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
620                                      unsigned char Value) {
621  // FIXME: Verify that Offset is associated with the current section.
622  OS << ".org " << *Offset << ", " << (unsigned) Value;
623  EmitEOL();
624}
625
626
627void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
628  assert(MAI.hasSingleParameterDotFile());
629  OS << "\t.file\t";
630  PrintQuotedString(Filename, OS);
631  EmitEOL();
632}
633
634void MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
635  OS << "\t.file\t" << FileNo << ' ';
636  PrintQuotedString(Filename, OS);
637  EmitEOL();
638}
639
640void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
641  raw_ostream &OS = GetCommentOS();
642  SmallString<256> Code;
643  SmallVector<MCFixup, 4> Fixups;
644  raw_svector_ostream VecOS(Code);
645  Emitter->EncodeInstruction(Inst, VecOS, Fixups);
646  VecOS.flush();
647
648  // If we are showing fixups, create symbolic markers in the encoded
649  // representation. We do this by making a per-bit map to the fixup item index,
650  // then trying to display it as nicely as possible.
651  SmallVector<uint8_t, 64> FixupMap;
652  FixupMap.resize(Code.size() * 8);
653  for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
654    FixupMap[i] = 0;
655
656  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
657    MCFixup &F = Fixups[i];
658    const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
659    for (unsigned j = 0; j != Info.TargetSize; ++j) {
660      unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
661      assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
662      FixupMap[Index] = 1 + i;
663    }
664  }
665
666  OS << "encoding: [";
667  for (unsigned i = 0, e = Code.size(); i != e; ++i) {
668    if (i)
669      OS << ',';
670
671    // See if all bits are the same map entry.
672    uint8_t MapEntry = FixupMap[i * 8 + 0];
673    for (unsigned j = 1; j != 8; ++j) {
674      if (FixupMap[i * 8 + j] == MapEntry)
675        continue;
676
677      MapEntry = uint8_t(~0U);
678      break;
679    }
680
681    if (MapEntry != uint8_t(~0U)) {
682      if (MapEntry == 0) {
683        OS << format("0x%02x", uint8_t(Code[i]));
684      } else {
685        assert(Code[i] == 0 && "Encoder wrote into fixed up bit!");
686        OS << char('A' + MapEntry - 1);
687      }
688    } else {
689      // Otherwise, write out in binary.
690      OS << "0b";
691      for (unsigned j = 8; j--;) {
692        unsigned Bit = (Code[i] >> j) & 1;
693        if (uint8_t MapEntry = FixupMap[i * 8 + j]) {
694          assert(Bit == 0 && "Encoder wrote into fixed up bit!");
695          OS << char('A' + MapEntry - 1);
696        } else
697          OS << Bit;
698      }
699    }
700  }
701  OS << "]\n";
702
703  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
704    MCFixup &F = Fixups[i];
705    const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
706    OS << "  fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
707       << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
708  }
709}
710
711void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
712  assert(CurSection && "Cannot emit contents before setting section!");
713
714  // Show the encoding in a comment if we have a code emitter.
715  if (Emitter)
716    AddEncodingComment(Inst);
717
718  // Show the MCInst if enabled.
719  if (ShowInst) {
720    Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
721    GetCommentOS() << "\n";
722  }
723
724  // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
725  if (InstPrinter)
726    InstPrinter->printInst(&Inst, OS);
727  else
728    Inst.print(OS, &MAI);
729  EmitEOL();
730}
731
732/// EmitRawText - If this file is backed by an assembly streamer, this dumps
733/// the specified string in the output .s file.  This capability is
734/// indicated by the hasRawTextSupport() predicate.
735void MCAsmStreamer::EmitRawText(StringRef String) {
736  if (!String.empty() && String.back() == '\n')
737    String = String.substr(0, String.size()-1);
738  OS << String;
739  EmitEOL();
740}
741
742void MCAsmStreamer::Finish() {
743}
744
745MCStreamer *llvm::createAsmStreamer(MCContext &Context,
746                                    formatted_raw_ostream &OS,
747                                    bool isLittleEndian,
748                                    bool isVerboseAsm, MCInstPrinter *IP,
749                                    MCCodeEmitter *CE, bool ShowInst) {
750  return new MCAsmStreamer(Context, OS, isLittleEndian, isVerboseAsm,
751                           IP, CE, ShowInst);
752}
753