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