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