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