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