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