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