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