Remove raw_svector_ostream::resync and users. It's no-op after r244870.
[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/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCSymbolELF.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Path.h"
34 #include <cctype>
35 using namespace llvm;
36
37 namespace {
38
39 class MCAsmStreamer final : public MCStreamer {
40   std::unique_ptr<formatted_raw_ostream> OSOwner;
41   formatted_raw_ostream &OS;
42   const MCAsmInfo *MAI;
43   std::unique_ptr<MCInstPrinter> InstPrinter;
44   std::unique_ptr<MCCodeEmitter> Emitter;
45   std::unique_ptr<MCAsmBackend> AsmBackend;
46
47   SmallString<128> CommentToEmit;
48   raw_svector_ostream CommentStream;
49
50   unsigned IsVerboseAsm : 1;
51   unsigned ShowInst : 1;
52   unsigned UseDwarfDirectory : 1;
53
54   void EmitRegisterName(int64_t Register);
55   void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
56   void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
57
58 public:
59   MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
60                 bool isVerboseAsm, bool useDwarfDirectory,
61                 MCInstPrinter *printer, MCCodeEmitter *emitter,
62                 MCAsmBackend *asmbackend, bool showInst)
63       : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
64         MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
65         AsmBackend(asmbackend), CommentStream(CommentToEmit),
66         IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
67         UseDwarfDirectory(useDwarfDirectory) {
68     assert(InstPrinter);
69     if (IsVerboseAsm)
70         InstPrinter->setCommentStream(CommentStream);
71   }
72
73   inline void EmitEOL() {
74     // If we don't have any comments, just emit a \n.
75     if (!IsVerboseAsm) {
76       OS << '\n';
77       return;
78     }
79     EmitCommentsAndEOL();
80   }
81
82   void EmitSyntaxDirective() override;
83
84   void EmitCommentsAndEOL();
85
86   /// isVerboseAsm - Return true if this streamer supports verbose assembly at
87   /// all.
88   bool isVerboseAsm() const override { return IsVerboseAsm; }
89
90   /// hasRawTextSupport - We support EmitRawText.
91   bool hasRawTextSupport() const override { return true; }
92
93   /// AddComment - Add a comment that can be emitted to the generated .s
94   /// file if applicable as a QoI issue to make the output of the compiler
95   /// more readable.  This only affects the MCAsmStreamer, and only when
96   /// verbose assembly output is enabled.
97   void AddComment(const Twine &T) override;
98
99   /// AddEncodingComment - Add a comment showing the encoding of an instruction.
100   void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
101
102   /// GetCommentOS - Return a raw_ostream that comments can be written to.
103   /// Unlike AddComment, you are required to terminate comments with \n if you
104   /// use this method.
105   raw_ostream &GetCommentOS() override {
106     if (!IsVerboseAsm)
107       return nulls();  // Discard comments unless in verbose asm mode.
108     return CommentStream;
109   }
110
111   void emitRawComment(const Twine &T, bool TabPrefix = true) override;
112
113   /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
114   void AddBlankLine() override {
115     EmitEOL();
116   }
117
118   /// @name MCStreamer Interface
119   /// @{
120
121   void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
122
123   void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
124   void EmitLabel(MCSymbol *Symbol) override;
125
126   void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
127   void EmitLinkerOptions(ArrayRef<std::string> Options) override;
128   void EmitDataRegion(MCDataRegionType Kind) override;
129   void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
130                       unsigned Update) override;
131   void EmitThumbFunc(MCSymbol *Func) override;
132
133   void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
134   void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
135   bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
136
137   void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
138   void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
139   void EmitCOFFSymbolStorageClass(int StorageClass) override;
140   void EmitCOFFSymbolType(int Type) override;
141   void EndCOFFSymbolDef() override;
142   void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
143   void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
144   void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
145   void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) override;
146   void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
147                         unsigned ByteAlignment) override;
148
149   /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
150   ///
151   /// @param Symbol - The common symbol to emit.
152   /// @param Size - The size of the common symbol.
153   /// @param ByteAlignment - The alignment of the common symbol in bytes.
154   void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
155                              unsigned ByteAlignment) override;
156
157   void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
158                     uint64_t Size = 0, unsigned ByteAlignment = 0) override;
159
160   void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
161                       unsigned ByteAlignment = 0) override;
162
163   void EmitBytes(StringRef Data) override;
164
165   void EmitValueImpl(const MCExpr *Value, unsigned Size,
166                      const SMLoc &Loc = SMLoc()) override;
167   void EmitIntValue(uint64_t Value, unsigned Size) override;
168
169   void EmitULEB128Value(const MCExpr *Value) override;
170
171   void EmitSLEB128Value(const MCExpr *Value) override;
172
173   void EmitGPRel64Value(const MCExpr *Value) override;
174
175   void EmitGPRel32Value(const MCExpr *Value) override;
176
177
178   void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
179
180   void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
181                             unsigned ValueSize = 1,
182                             unsigned MaxBytesToEmit = 0) override;
183
184   void EmitCodeAlignment(unsigned ByteAlignment,
185                          unsigned MaxBytesToEmit = 0) override;
186
187   bool EmitValueToOffset(const MCExpr *Offset,
188                          unsigned char Value = 0) override;
189
190   void EmitFileDirective(StringRef Filename) override;
191   unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
192                                   StringRef Filename,
193                                   unsigned CUID = 0) override;
194   void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
195                              unsigned Column, unsigned Flags,
196                              unsigned Isa, unsigned Discriminator,
197                              StringRef FileName) override;
198   MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
199
200   void EmitIdent(StringRef IdentString) override;
201   void EmitCFISections(bool EH, bool Debug) override;
202   void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
203   void EmitCFIDefCfaOffset(int64_t Offset) override;
204   void EmitCFIDefCfaRegister(int64_t Register) override;
205   void EmitCFIOffset(int64_t Register, int64_t Offset) override;
206   void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
207   void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
208   void EmitCFIRememberState() override;
209   void EmitCFIRestoreState() override;
210   void EmitCFISameValue(int64_t Register) override;
211   void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
212   void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
213   void EmitCFISignalFrame() override;
214   void EmitCFIUndefined(int64_t Register) override;
215   void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
216   void EmitCFIWindowSave() override;
217
218   void EmitWinCFIStartProc(const MCSymbol *Symbol) override;
219   void EmitWinCFIEndProc() override;
220   void EmitWinCFIStartChained() override;
221   void EmitWinCFIEndChained() override;
222   void EmitWinCFIPushReg(unsigned Register) override;
223   void EmitWinCFISetFrame(unsigned Register, unsigned Offset) override;
224   void EmitWinCFIAllocStack(unsigned Size) override;
225   void EmitWinCFISaveReg(unsigned Register, unsigned Offset) override;
226   void EmitWinCFISaveXMM(unsigned Register, unsigned Offset) override;
227   void EmitWinCFIPushFrame(bool Code) override;
228   void EmitWinCFIEndProlog() override;
229
230   void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) override;
231   void EmitWinEHHandlerData() override;
232
233   void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
234
235   void EmitBundleAlignMode(unsigned AlignPow2) override;
236   void EmitBundleLock(bool AlignToEnd) override;
237   void EmitBundleUnlock() override;
238
239   /// EmitRawText - If this file is backed by an assembly streamer, this dumps
240   /// the specified string in the output .s file.  This capability is
241   /// indicated by the hasRawTextSupport() predicate.
242   void EmitRawTextImpl(StringRef String) override;
243
244   void FinishImpl() override;
245 };
246
247 } // end anonymous namespace.
248
249 /// AddComment - Add a comment that can be emitted to the generated .s
250 /// file if applicable as a QoI issue to make the output of the compiler
251 /// more readable.  This only affects the MCAsmStreamer, and only when
252 /// verbose assembly output is enabled.
253 void MCAsmStreamer::AddComment(const Twine &T) {
254   if (!IsVerboseAsm) return;
255
256   // Make sure that CommentStream is flushed.
257   CommentStream.flush();
258
259   T.toVector(CommentToEmit);
260   // Each comment goes on its own line.
261   CommentToEmit.push_back('\n');
262 }
263
264 void MCAsmStreamer::EmitCommentsAndEOL() {
265   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
266     OS << '\n';
267     return;
268   }
269
270   CommentStream.flush();
271   StringRef Comments = CommentToEmit;
272
273   assert(Comments.back() == '\n' &&
274          "Comment array not newline terminated");
275   do {
276     // Emit a line of comments.
277     OS.PadToColumn(MAI->getCommentColumn());
278     size_t Position = Comments.find('\n');
279     OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
280
281     Comments = Comments.substr(Position+1);
282   } while (!Comments.empty());
283
284   CommentToEmit.clear();
285 }
286
287 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
288   assert(Bytes && "Invalid size!");
289   return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
290 }
291
292 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
293   if (TabPrefix)
294     OS << '\t';
295   OS << MAI->getCommentString() << T;
296   EmitEOL();
297 }
298
299 void MCAsmStreamer::ChangeSection(MCSection *Section,
300                                   const MCExpr *Subsection) {
301   assert(Section && "Cannot switch to a null section!");
302   Section->PrintSwitchToSection(*MAI, OS, Subsection);
303 }
304
305 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
306   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
307   MCStreamer::EmitLabel(Symbol);
308
309   Symbol->print(OS, MAI);
310   OS << MAI->getLabelSuffix();
311
312   EmitEOL();
313 }
314
315 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
316   StringRef str = MCLOHIdToName(Kind);
317
318 #ifndef NDEBUG
319   int NbArgs = MCLOHIdToNbArgs(Kind);
320   assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
321   assert(str != "" && "Invalid LOH name");
322 #endif
323
324   OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
325   bool IsFirst = true;
326   for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
327        It != EndIt; ++It) {
328     if (!IsFirst)
329       OS << ", ";
330     IsFirst = false;
331     (*It)->print(OS, MAI);
332   }
333   EmitEOL();
334 }
335
336 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
337   switch (Flag) {
338   case MCAF_SyntaxUnified:         OS << "\t.syntax unified"; break;
339   case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
340   case MCAF_Code16:                OS << '\t'<< MAI->getCode16Directive();break;
341   case MCAF_Code32:                OS << '\t'<< MAI->getCode32Directive();break;
342   case MCAF_Code64:                OS << '\t'<< MAI->getCode64Directive();break;
343   }
344   EmitEOL();
345 }
346
347 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
348   assert(!Options.empty() && "At least one option is required!");
349   OS << "\t.linker_option \"" << Options[0] << '"';
350   for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
351          ie = Options.end(); it != ie; ++it) {
352     OS << ", " << '"' << *it << '"';
353   }
354   OS << "\n";
355 }
356
357 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
358   if (!MAI->doesSupportDataRegionDirectives())
359     return;
360   switch (Kind) {
361   case MCDR_DataRegion:            OS << "\t.data_region"; break;
362   case MCDR_DataRegionJT8:         OS << "\t.data_region jt8"; break;
363   case MCDR_DataRegionJT16:        OS << "\t.data_region jt16"; break;
364   case MCDR_DataRegionJT32:        OS << "\t.data_region jt32"; break;
365   case MCDR_DataRegionEnd:         OS << "\t.end_data_region"; break;
366   }
367   EmitEOL();
368 }
369
370 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
371                                    unsigned Minor, unsigned Update) {
372   switch (Kind) {
373   case MCVM_IOSVersionMin:        OS << "\t.ios_version_min"; break;
374   case MCVM_OSXVersionMin:        OS << "\t.macosx_version_min"; break;
375   }
376   OS << " " << Major << ", " << Minor;
377   if (Update)
378     OS << ", " << Update;
379   EmitEOL();
380 }
381
382 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
383   // This needs to emit to a temporary string to get properly quoted
384   // MCSymbols when they have spaces in them.
385   OS << "\t.thumb_func";
386   // Only Mach-O hasSubsectionsViaSymbols()
387   if (MAI->hasSubsectionsViaSymbols()) {
388     OS << '\t';
389     Func->print(OS, MAI);
390   }
391   EmitEOL();
392 }
393
394 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
395   Symbol->print(OS, MAI);
396   OS << " = ";
397   Value->print(OS, MAI);
398
399   EmitEOL();
400
401   MCStreamer::EmitAssignment(Symbol, Value);
402 }
403
404 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
405   OS << ".weakref ";
406   Alias->print(OS, MAI);
407   OS << ", ";
408   Symbol->print(OS, MAI);
409   EmitEOL();
410 }
411
412 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
413                                         MCSymbolAttr Attribute) {
414   switch (Attribute) {
415   case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
416   case MCSA_ELF_TypeFunction:    /// .type _foo, STT_FUNC  # aka @function
417   case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
418   case MCSA_ELF_TypeObject:      /// .type _foo, STT_OBJECT  # aka @object
419   case MCSA_ELF_TypeTLS:         /// .type _foo, STT_TLS     # aka @tls_object
420   case MCSA_ELF_TypeCommon:      /// .type _foo, STT_COMMON  # aka @common
421   case MCSA_ELF_TypeNoType:      /// .type _foo, STT_NOTYPE  # aka @notype
422   case MCSA_ELF_TypeGnuUniqueObject:  /// .type _foo, @gnu_unique_object
423     if (!MAI->hasDotTypeDotSizeDirective())
424       return false; // Symbol attribute not supported
425     OS << "\t.type\t";
426     Symbol->print(OS, MAI);
427     OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
428     switch (Attribute) {
429     default: return false;
430     case MCSA_ELF_TypeFunction:    OS << "function"; break;
431     case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
432     case MCSA_ELF_TypeObject:      OS << "object"; break;
433     case MCSA_ELF_TypeTLS:         OS << "tls_object"; break;
434     case MCSA_ELF_TypeCommon:      OS << "common"; break;
435     case MCSA_ELF_TypeNoType:      OS << "no_type"; break;
436     case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
437     }
438     EmitEOL();
439     return true;
440   case MCSA_Global: // .globl/.global
441     OS << MAI->getGlobalDirective();
442     break;
443   case MCSA_Hidden:         OS << "\t.hidden\t";          break;
444   case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
445   case MCSA_Internal:       OS << "\t.internal\t";        break;
446   case MCSA_LazyReference:  OS << "\t.lazy_reference\t";  break;
447   case MCSA_Local:          OS << "\t.local\t";           break;
448   case MCSA_NoDeadStrip:
449     if (!MAI->hasNoDeadStrip())
450       return false;
451     OS << "\t.no_dead_strip\t";
452     break;
453   case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
454   case MCSA_PrivateExtern:
455     OS << "\t.private_extern\t";
456     break;
457   case MCSA_Protected:      OS << "\t.protected\t";       break;
458   case MCSA_Reference:      OS << "\t.reference\t";       break;
459   case MCSA_Weak:           OS << MAI->getWeakDirective(); break;
460   case MCSA_WeakDefinition:
461     OS << "\t.weak_definition\t";
462     break;
463       // .weak_reference
464   case MCSA_WeakReference:  OS << MAI->getWeakRefDirective(); break;
465   case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
466   }
467
468   Symbol->print(OS, MAI);
469   EmitEOL();
470
471   return true;
472 }
473
474 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
475   OS << ".desc" << ' ';
476   Symbol->print(OS, MAI);
477   OS << ',' << DescValue;
478   EmitEOL();
479 }
480
481 void MCAsmStreamer::EmitSyntaxDirective() {
482   if (MAI->getAssemblerDialect() == 1)
483     OS << "\t.intel_syntax noprefix\n";
484   // FIXME: Currently emit unprefix'ed registers.
485   // The intel_syntax directive has one optional argument 
486   // with may have a value of prefix or noprefix.
487 }
488
489 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
490   OS << "\t.def\t ";
491   Symbol->print(OS, MAI);
492   OS << ';';
493   EmitEOL();
494 }
495
496 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
497   OS << "\t.scl\t" << StorageClass << ';';
498   EmitEOL();
499 }
500
501 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
502   OS << "\t.type\t" << Type << ';';
503   EmitEOL();
504 }
505
506 void MCAsmStreamer::EndCOFFSymbolDef() {
507   OS << "\t.endef";
508   EmitEOL();
509 }
510
511 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
512   OS << "\t.safeseh\t";
513   Symbol->print(OS, MAI);
514   EmitEOL();
515 }
516
517 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
518   OS << "\t.secidx\t";
519   Symbol->print(OS, MAI);
520   EmitEOL();
521 }
522
523 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
524   OS << "\t.secrel32\t";
525   Symbol->print(OS, MAI);
526   EmitEOL();
527 }
528
529 void MCAsmStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {
530   assert(MAI->hasDotTypeDotSizeDirective());
531   OS << "\t.size\t";
532   Symbol->print(OS, MAI);
533   OS << ", ";
534   Value->print(OS, MAI);
535   OS << '\n';
536 }
537
538 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
539                                      unsigned ByteAlignment) {
540   // Common symbols do not belong to any actual section.
541   AssignSection(Symbol, nullptr);
542
543   OS << "\t.comm\t";
544   Symbol->print(OS, MAI);
545   OS << ',' << Size;
546
547   if (ByteAlignment != 0) {
548     if (MAI->getCOMMDirectiveAlignmentIsInBytes())
549       OS << ',' << ByteAlignment;
550     else
551       OS << ',' << Log2_32(ByteAlignment);
552   }
553   EmitEOL();
554 }
555
556 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
557 ///
558 /// @param Symbol - The common symbol to emit.
559 /// @param Size - The size of the common symbol.
560 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
561                                           unsigned ByteAlign) {
562   // Common symbols do not belong to any actual section.
563   AssignSection(Symbol, nullptr);
564
565   OS << "\t.lcomm\t";
566   Symbol->print(OS, MAI);
567   OS << ',' << Size;
568
569   if (ByteAlign > 1) {
570     switch (MAI->getLCOMMDirectiveAlignmentType()) {
571     case LCOMM::NoAlignment:
572       llvm_unreachable("alignment not supported on .lcomm!");
573     case LCOMM::ByteAlignment:
574       OS << ',' << ByteAlign;
575       break;
576     case LCOMM::Log2Alignment:
577       assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
578       OS << ',' << Log2_32(ByteAlign);
579       break;
580     }
581   }
582   EmitEOL();
583 }
584
585 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
586                                  uint64_t Size, unsigned ByteAlignment) {
587   if (Symbol)
588     AssignSection(Symbol, Section);
589
590   // Note: a .zerofill directive does not switch sections.
591   OS << ".zerofill ";
592
593   // This is a mach-o specific directive.
594   const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
595   OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
596
597   if (Symbol) {
598     OS << ',';
599     Symbol->print(OS, MAI);
600     OS << ',' << Size;
601     if (ByteAlignment != 0)
602       OS << ',' << Log2_32(ByteAlignment);
603   }
604   EmitEOL();
605 }
606
607 // .tbss sym, size, align
608 // This depends that the symbol has already been mangled from the original,
609 // e.g. _a.
610 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
611                                    uint64_t Size, unsigned ByteAlignment) {
612   AssignSection(Symbol, Section);
613
614   assert(Symbol && "Symbol shouldn't be NULL!");
615   // Instead of using the Section we'll just use the shortcut.
616   // This is a mach-o specific directive and section.
617   OS << ".tbss ";
618   Symbol->print(OS, MAI);
619   OS << ", " << Size;
620
621   // Output align if we have it.  We default to 1 so don't bother printing
622   // that.
623   if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
624
625   EmitEOL();
626 }
627
628 static inline char toOctal(int X) { return (X&7)+'0'; }
629
630 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
631   OS << '"';
632
633   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
634     unsigned char C = Data[i];
635     if (C == '"' || C == '\\') {
636       OS << '\\' << (char)C;
637       continue;
638     }
639
640     if (isprint((unsigned char)C)) {
641       OS << (char)C;
642       continue;
643     }
644
645     switch (C) {
646       case '\b': OS << "\\b"; break;
647       case '\f': OS << "\\f"; break;
648       case '\n': OS << "\\n"; break;
649       case '\r': OS << "\\r"; break;
650       case '\t': OS << "\\t"; break;
651       default:
652         OS << '\\';
653         OS << toOctal(C >> 6);
654         OS << toOctal(C >> 3);
655         OS << toOctal(C >> 0);
656         break;
657     }
658   }
659
660   OS << '"';
661 }
662
663
664 void MCAsmStreamer::EmitBytes(StringRef Data) {
665   assert(getCurrentSection().first &&
666          "Cannot emit contents before setting section!");
667   if (Data.empty()) return;
668
669   if (Data.size() == 1) {
670     OS << MAI->getData8bitsDirective();
671     OS << (unsigned)(unsigned char)Data[0];
672     EmitEOL();
673     return;
674   }
675
676   // If the data ends with 0 and the target supports .asciz, use it, otherwise
677   // use .ascii
678   if (MAI->getAscizDirective() && Data.back() == 0) {
679     OS << MAI->getAscizDirective();
680     Data = Data.substr(0, Data.size()-1);
681   } else {
682     OS << MAI->getAsciiDirective();
683   }
684
685   PrintQuotedString(Data, OS);
686   EmitEOL();
687 }
688
689 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
690   EmitValue(MCConstantExpr::create(Value, getContext()), Size);
691 }
692
693 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
694                                   const SMLoc &Loc) {
695   assert(Size <= 8 && "Invalid size");
696   assert(getCurrentSection().first &&
697          "Cannot emit contents before setting section!");
698   const char *Directive = nullptr;
699   switch (Size) {
700   default: break;
701   case 1: Directive = MAI->getData8bitsDirective();  break;
702   case 2: Directive = MAI->getData16bitsDirective(); break;
703   case 4: Directive = MAI->getData32bitsDirective(); break;
704   case 8: Directive = MAI->getData64bitsDirective(); break;
705   }
706
707   if (!Directive) {
708     int64_t IntValue;
709     if (!Value->evaluateAsAbsolute(IntValue))
710       report_fatal_error("Don't know how to emit this value.");
711
712     // We couldn't handle the requested integer size so we fallback by breaking
713     // the request down into several, smaller, integers.  Since sizes greater
714     // than eight are invalid and size equivalent to eight should have been
715     // handled earlier, we use four bytes as our largest piece of granularity.
716     bool IsLittleEndian = MAI->isLittleEndian();
717     for (unsigned Emitted = 0; Emitted != Size;) {
718       unsigned Remaining = Size - Emitted;
719       // The size of our partial emission must be a power of two less than
720       // eight.
721       unsigned EmissionSize = PowerOf2Floor(Remaining);
722       if (EmissionSize > 4)
723         EmissionSize = 4;
724       // Calculate the byte offset of our partial emission taking into account
725       // the endianness of the target.
726       unsigned ByteOffset =
727           IsLittleEndian ? Emitted : (Remaining - EmissionSize);
728       uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
729       // We truncate our partial emission to fit within the bounds of the
730       // emission domain.  This produces nicer output and silences potential
731       // truncation warnings when round tripping through another assembler.
732       uint64_t Shift = 64 - EmissionSize * 8;
733       assert(Shift < static_cast<uint64_t>(
734                          std::numeric_limits<unsigned long long>::digits) &&
735              "undefined behavior");
736       ValueToEmit &= ~0ULL >> Shift;
737       EmitIntValue(ValueToEmit, EmissionSize);
738       Emitted += EmissionSize;
739     }
740     return;
741   }
742
743   assert(Directive && "Invalid size for machine code value!");
744   OS << Directive;
745   Value->print(OS, MAI);
746   EmitEOL();
747 }
748
749 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
750   int64_t IntValue;
751   if (Value->evaluateAsAbsolute(IntValue)) {
752     EmitULEB128IntValue(IntValue);
753     return;
754   }
755   OS << ".uleb128 ";
756   Value->print(OS, MAI);
757   EmitEOL();
758 }
759
760 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
761   int64_t IntValue;
762   if (Value->evaluateAsAbsolute(IntValue)) {
763     EmitSLEB128IntValue(IntValue);
764     return;
765   }
766   OS << ".sleb128 ";
767   Value->print(OS, MAI);
768   EmitEOL();
769 }
770
771 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
772   assert(MAI->getGPRel64Directive() != nullptr);
773   OS << MAI->getGPRel64Directive();
774   Value->print(OS, MAI);
775   EmitEOL();
776 }
777
778 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
779   assert(MAI->getGPRel32Directive() != nullptr);
780   OS << MAI->getGPRel32Directive();
781   Value->print(OS, MAI);
782   EmitEOL();
783 }
784
785
786 /// EmitFill - Emit NumBytes bytes worth of the value specified by
787 /// FillValue.  This implements directives such as '.space'.
788 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
789   if (NumBytes == 0) return;
790
791   if (const char *ZeroDirective = MAI->getZeroDirective()) {
792     OS << ZeroDirective << NumBytes;
793     if (FillValue != 0)
794       OS << ',' << (int)FillValue;
795     EmitEOL();
796     return;
797   }
798
799   // Emit a byte at a time.
800   MCStreamer::EmitFill(NumBytes, FillValue);
801 }
802
803 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
804                                          unsigned ValueSize,
805                                          unsigned MaxBytesToEmit) {
806   // Some assemblers don't support non-power of two alignments, so we always
807   // emit alignments as a power of two if possible.
808   if (isPowerOf2_32(ByteAlignment)) {
809     switch (ValueSize) {
810     default:
811       llvm_unreachable("Invalid size for machine code value!");
812     case 1:
813       OS << "\t.align\t";
814       break;
815     case 2:
816       OS << ".p2alignw ";
817       break;
818     case 4:
819       OS << ".p2alignl ";
820       break;
821     case 8:
822       llvm_unreachable("Unsupported alignment size!");
823     }
824
825     if (MAI->getAlignmentIsInBytes())
826       OS << ByteAlignment;
827     else
828       OS << Log2_32(ByteAlignment);
829
830     if (Value || MaxBytesToEmit) {
831       OS << ", 0x";
832       OS.write_hex(truncateToSize(Value, ValueSize));
833
834       if (MaxBytesToEmit)
835         OS << ", " << MaxBytesToEmit;
836     }
837     EmitEOL();
838     return;
839   }
840
841   // Non-power of two alignment.  This is not widely supported by assemblers.
842   // FIXME: Parameterize this based on MAI.
843   switch (ValueSize) {
844   default: llvm_unreachable("Invalid size for machine code value!");
845   case 1: OS << ".balign";  break;
846   case 2: OS << ".balignw"; break;
847   case 4: OS << ".balignl"; break;
848   case 8: llvm_unreachable("Unsupported alignment size!");
849   }
850
851   OS << ' ' << ByteAlignment;
852   OS << ", " << truncateToSize(Value, ValueSize);
853   if (MaxBytesToEmit)
854     OS << ", " << MaxBytesToEmit;
855   EmitEOL();
856 }
857
858 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
859                                       unsigned MaxBytesToEmit) {
860   // Emit with a text fill value.
861   EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
862                        1, MaxBytesToEmit);
863 }
864
865 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
866                                       unsigned char Value) {
867   // FIXME: Verify that Offset is associated with the current section.
868   OS << ".org ";
869   Offset->print(OS, MAI);
870   OS << ", " << (unsigned)Value;
871   EmitEOL();
872   return false;
873 }
874
875
876 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
877   assert(MAI->hasSingleParameterDotFile());
878   OS << "\t.file\t";
879   PrintQuotedString(Filename, OS);
880   EmitEOL();
881 }
882
883 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
884                                                StringRef Directory,
885                                                StringRef Filename,
886                                                unsigned CUID) {
887   assert(CUID == 0);
888
889   MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
890   unsigned NumFiles = Table.getMCDwarfFiles().size();
891   FileNo = Table.getFile(Directory, Filename, FileNo);
892   if (FileNo == 0)
893     return 0;
894   if (NumFiles == Table.getMCDwarfFiles().size())
895     return FileNo;
896
897   SmallString<128> FullPathName;
898
899   if (!UseDwarfDirectory && !Directory.empty()) {
900     if (sys::path::is_absolute(Filename))
901       Directory = "";
902     else {
903       FullPathName = Directory;
904       sys::path::append(FullPathName, Filename);
905       Directory = "";
906       Filename = FullPathName;
907     }
908   }
909
910   OS << "\t.file\t" << FileNo << ' ';
911   if (!Directory.empty()) {
912     PrintQuotedString(Directory, OS);
913     OS << ' ';
914   }
915   PrintQuotedString(Filename, OS);
916   EmitEOL();
917
918   return FileNo;
919 }
920
921 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
922                                           unsigned Column, unsigned Flags,
923                                           unsigned Isa,
924                                           unsigned Discriminator,
925                                           StringRef FileName) {
926   OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
927   if (Flags & DWARF2_FLAG_BASIC_BLOCK)
928     OS << " basic_block";
929   if (Flags & DWARF2_FLAG_PROLOGUE_END)
930     OS << " prologue_end";
931   if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
932     OS << " epilogue_begin";
933
934   unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
935   if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
936     OS << " is_stmt ";
937
938     if (Flags & DWARF2_FLAG_IS_STMT)
939       OS << "1";
940     else
941       OS << "0";
942   }
943
944   if (Isa)
945     OS << " isa " << Isa;
946   if (Discriminator)
947     OS << " discriminator " << Discriminator;
948
949   if (IsVerboseAsm) {
950     OS.PadToColumn(MAI->getCommentColumn());
951     OS << MAI->getCommentString() << ' ' << FileName << ':'
952        << Line << ':' << Column;
953   }
954   EmitEOL();
955   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
956                                           Isa, Discriminator, FileName);
957 }
958
959 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
960   // Always use the zeroth line table, since asm syntax only supports one line
961   // table for now.
962   return MCStreamer::getDwarfLineTableSymbol(0);
963 }
964
965 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
966   assert(MAI->hasIdentDirective() && ".ident directive not supported");
967   OS << "\t.ident\t";
968   PrintQuotedString(IdentString, OS);
969   EmitEOL();
970 }
971
972 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
973   MCStreamer::EmitCFISections(EH, Debug);
974   OS << "\t.cfi_sections ";
975   if (EH) {
976     OS << ".eh_frame";
977     if (Debug)
978       OS << ", .debug_frame";
979   } else if (Debug) {
980     OS << ".debug_frame";
981   }
982
983   EmitEOL();
984 }
985
986 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
987   OS << "\t.cfi_startproc";
988   if (Frame.IsSimple)
989     OS << " simple";
990   EmitEOL();
991 }
992
993 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
994   MCStreamer::EmitCFIEndProcImpl(Frame);
995   OS << "\t.cfi_endproc";
996   EmitEOL();
997 }
998
999 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1000   if (!MAI->useDwarfRegNumForCFI()) {
1001     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1002     unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
1003     InstPrinter->printRegName(OS, LLVMRegister);
1004   } else {
1005     OS << Register;
1006   }
1007 }
1008
1009 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1010   MCStreamer::EmitCFIDefCfa(Register, Offset);
1011   OS << "\t.cfi_def_cfa ";
1012   EmitRegisterName(Register);
1013   OS << ", " << Offset;
1014   EmitEOL();
1015 }
1016
1017 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1018   MCStreamer::EmitCFIDefCfaOffset(Offset);
1019   OS << "\t.cfi_def_cfa_offset " << Offset;
1020   EmitEOL();
1021 }
1022
1023 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1024   MCStreamer::EmitCFIDefCfaRegister(Register);
1025   OS << "\t.cfi_def_cfa_register ";
1026   EmitRegisterName(Register);
1027   EmitEOL();
1028 }
1029
1030 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1031   this->MCStreamer::EmitCFIOffset(Register, Offset);
1032   OS << "\t.cfi_offset ";
1033   EmitRegisterName(Register);
1034   OS << ", " << Offset;
1035   EmitEOL();
1036 }
1037
1038 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1039                                        unsigned Encoding) {
1040   MCStreamer::EmitCFIPersonality(Sym, Encoding);
1041   OS << "\t.cfi_personality " << Encoding << ", ";
1042   Sym->print(OS, MAI);
1043   EmitEOL();
1044 }
1045
1046 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1047   MCStreamer::EmitCFILsda(Sym, Encoding);
1048   OS << "\t.cfi_lsda " << Encoding << ", ";
1049   Sym->print(OS, MAI);
1050   EmitEOL();
1051 }
1052
1053 void MCAsmStreamer::EmitCFIRememberState() {
1054   MCStreamer::EmitCFIRememberState();
1055   OS << "\t.cfi_remember_state";
1056   EmitEOL();
1057 }
1058
1059 void MCAsmStreamer::EmitCFIRestoreState() {
1060   MCStreamer::EmitCFIRestoreState();
1061   OS << "\t.cfi_restore_state";
1062   EmitEOL();
1063 }
1064
1065 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1066   MCStreamer::EmitCFISameValue(Register);
1067   OS << "\t.cfi_same_value ";
1068   EmitRegisterName(Register);
1069   EmitEOL();
1070 }
1071
1072 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1073   MCStreamer::EmitCFIRelOffset(Register, Offset);
1074   OS << "\t.cfi_rel_offset ";
1075   EmitRegisterName(Register);
1076   OS << ", " << Offset;
1077   EmitEOL();
1078 }
1079
1080 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1081   MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1082   OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1083   EmitEOL();
1084 }
1085
1086 void MCAsmStreamer::EmitCFISignalFrame() {
1087   MCStreamer::EmitCFISignalFrame();
1088   OS << "\t.cfi_signal_frame";
1089   EmitEOL();
1090 }
1091
1092 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1093   MCStreamer::EmitCFIUndefined(Register);
1094   OS << "\t.cfi_undefined " << Register;
1095   EmitEOL();
1096 }
1097
1098 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1099   MCStreamer::EmitCFIRegister(Register1, Register2);
1100   OS << "\t.cfi_register " << Register1 << ", " << Register2;
1101   EmitEOL();
1102 }
1103
1104 void MCAsmStreamer::EmitCFIWindowSave() {
1105   MCStreamer::EmitCFIWindowSave();
1106   OS << "\t.cfi_window_save";
1107   EmitEOL();
1108 }
1109
1110 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) {
1111   MCStreamer::EmitWinCFIStartProc(Symbol);
1112
1113   OS << ".seh_proc ";
1114   Symbol->print(OS, MAI);
1115   EmitEOL();
1116 }
1117
1118 void MCAsmStreamer::EmitWinCFIEndProc() {
1119   MCStreamer::EmitWinCFIEndProc();
1120
1121   OS << "\t.seh_endproc";
1122   EmitEOL();
1123 }
1124
1125 void MCAsmStreamer::EmitWinCFIStartChained() {
1126   MCStreamer::EmitWinCFIStartChained();
1127
1128   OS << "\t.seh_startchained";
1129   EmitEOL();
1130 }
1131
1132 void MCAsmStreamer::EmitWinCFIEndChained() {
1133   MCStreamer::EmitWinCFIEndChained();
1134
1135   OS << "\t.seh_endchained";
1136   EmitEOL();
1137 }
1138
1139 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1140                                       bool Except) {
1141   MCStreamer::EmitWinEHHandler(Sym, Unwind, Except);
1142
1143   OS << "\t.seh_handler ";
1144   Sym->print(OS, MAI);
1145   if (Unwind)
1146     OS << ", @unwind";
1147   if (Except)
1148     OS << ", @except";
1149   EmitEOL();
1150 }
1151
1152 void MCAsmStreamer::EmitWinEHHandlerData() {
1153   MCStreamer::EmitWinEHHandlerData();
1154
1155   // Switch sections. Don't call SwitchSection directly, because that will
1156   // cause the section switch to be visible in the emitted assembly.
1157   // We only do this so the section switch that terminates the handler
1158   // data block is visible.
1159   WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1160   MCSection *XData =
1161       WinEH::UnwindEmitter::getXDataSection(CurFrame->Function, getContext());
1162   SwitchSectionNoChange(XData);
1163
1164   OS << "\t.seh_handlerdata";
1165   EmitEOL();
1166 }
1167
1168 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register) {
1169   MCStreamer::EmitWinCFIPushReg(Register);
1170
1171   OS << "\t.seh_pushreg " << Register;
1172   EmitEOL();
1173 }
1174
1175 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) {
1176   MCStreamer::EmitWinCFISetFrame(Register, Offset);
1177
1178   OS << "\t.seh_setframe " << Register << ", " << Offset;
1179   EmitEOL();
1180 }
1181
1182 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size) {
1183   MCStreamer::EmitWinCFIAllocStack(Size);
1184
1185   OS << "\t.seh_stackalloc " << Size;
1186   EmitEOL();
1187 }
1188
1189 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) {
1190   MCStreamer::EmitWinCFISaveReg(Register, Offset);
1191
1192   OS << "\t.seh_savereg " << Register << ", " << Offset;
1193   EmitEOL();
1194 }
1195
1196 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) {
1197   MCStreamer::EmitWinCFISaveXMM(Register, Offset);
1198
1199   OS << "\t.seh_savexmm " << Register << ", " << Offset;
1200   EmitEOL();
1201 }
1202
1203 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code) {
1204   MCStreamer::EmitWinCFIPushFrame(Code);
1205
1206   OS << "\t.seh_pushframe";
1207   if (Code)
1208     OS << " @code";
1209   EmitEOL();
1210 }
1211
1212 void MCAsmStreamer::EmitWinCFIEndProlog(void) {
1213   MCStreamer::EmitWinCFIEndProlog();
1214
1215   OS << "\t.seh_endprologue";
1216   EmitEOL();
1217 }
1218
1219 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1220                                        const MCSubtargetInfo &STI) {
1221   raw_ostream &OS = GetCommentOS();
1222   SmallString<256> Code;
1223   SmallVector<MCFixup, 4> Fixups;
1224   raw_svector_ostream VecOS(Code);
1225   Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1226   VecOS.flush();
1227
1228   // If we are showing fixups, create symbolic markers in the encoded
1229   // representation. We do this by making a per-bit map to the fixup item index,
1230   // then trying to display it as nicely as possible.
1231   SmallVector<uint8_t, 64> FixupMap;
1232   FixupMap.resize(Code.size() * 8);
1233   for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1234     FixupMap[i] = 0;
1235
1236   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1237     MCFixup &F = Fixups[i];
1238     const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1239     for (unsigned j = 0; j != Info.TargetSize; ++j) {
1240       unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1241       assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1242       FixupMap[Index] = 1 + i;
1243     }
1244   }
1245
1246   // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1247   // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1248   OS << "encoding: [";
1249   for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1250     if (i)
1251       OS << ',';
1252
1253     // See if all bits are the same map entry.
1254     uint8_t MapEntry = FixupMap[i * 8 + 0];
1255     for (unsigned j = 1; j != 8; ++j) {
1256       if (FixupMap[i * 8 + j] == MapEntry)
1257         continue;
1258
1259       MapEntry = uint8_t(~0U);
1260       break;
1261     }
1262
1263     if (MapEntry != uint8_t(~0U)) {
1264       if (MapEntry == 0) {
1265         OS << format("0x%02x", uint8_t(Code[i]));
1266       } else {
1267         if (Code[i]) {
1268           // FIXME: Some of the 8 bits require fix up.
1269           OS << format("0x%02x", uint8_t(Code[i])) << '\''
1270              << char('A' + MapEntry - 1) << '\'';
1271         } else
1272           OS << char('A' + MapEntry - 1);
1273       }
1274     } else {
1275       // Otherwise, write out in binary.
1276       OS << "0b";
1277       for (unsigned j = 8; j--;) {
1278         unsigned Bit = (Code[i] >> j) & 1;
1279
1280         unsigned FixupBit;
1281         if (MAI->isLittleEndian())
1282           FixupBit = i * 8 + j;
1283         else
1284           FixupBit = i * 8 + (7-j);
1285
1286         if (uint8_t MapEntry = FixupMap[FixupBit]) {
1287           assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1288           OS << char('A' + MapEntry - 1);
1289         } else
1290           OS << Bit;
1291       }
1292     }
1293   }
1294   OS << "]\n";
1295
1296   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1297     MCFixup &F = Fixups[i];
1298     const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1299     OS << "  fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1300        << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1301   }
1302 }
1303
1304 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1305   assert(getCurrentSection().first &&
1306          "Cannot emit contents before setting section!");
1307
1308   // Show the encoding in a comment if we have a code emitter.
1309   if (Emitter)
1310     AddEncodingComment(Inst, STI);
1311
1312   // Show the MCInst if enabled.
1313   if (ShowInst) {
1314     Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1315     GetCommentOS() << "\n";
1316   }
1317
1318   if(getTargetStreamer())
1319     getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1320   else
1321     InstPrinter->printInst(&Inst, OS, "", STI);
1322
1323   EmitEOL();
1324 }
1325
1326 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1327   OS << "\t.bundle_align_mode " << AlignPow2;
1328   EmitEOL();
1329 }
1330
1331 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1332   OS << "\t.bundle_lock";
1333   if (AlignToEnd)
1334     OS << " align_to_end";
1335   EmitEOL();
1336 }
1337
1338 void MCAsmStreamer::EmitBundleUnlock() {
1339   OS << "\t.bundle_unlock";
1340   EmitEOL();
1341 }
1342
1343 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1344 /// the specified string in the output .s file.  This capability is
1345 /// indicated by the hasRawTextSupport() predicate.
1346 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1347   if (!String.empty() && String.back() == '\n')
1348     String = String.substr(0, String.size()-1);
1349   OS << String;
1350   EmitEOL();
1351 }
1352
1353 void MCAsmStreamer::FinishImpl() {
1354   // If we are generating dwarf for assembly source files dump out the sections.
1355   if (getContext().getGenDwarfForAssembly())
1356     MCGenDwarfInfo::Emit(this);
1357
1358   // Emit the label for the line table, if requested - since the rest of the
1359   // line table will be defined by .loc/.file directives, and not emitted
1360   // directly, the label is the only work required here.
1361   auto &Tables = getContext().getMCDwarfLineTables();
1362   if (!Tables.empty()) {
1363     assert(Tables.size() == 1 && "asm output only supports one line table");
1364     if (auto *Label = Tables.begin()->second.getLabel()) {
1365       SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1366       EmitLabel(Label);
1367     }
1368   }
1369 }
1370
1371 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1372                                     std::unique_ptr<formatted_raw_ostream> OS,
1373                                     bool isVerboseAsm, bool useDwarfDirectory,
1374                                     MCInstPrinter *IP, MCCodeEmitter *CE,
1375                                     MCAsmBackend *MAB, bool ShowInst) {
1376   return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1377                            useDwarfDirectory, IP, CE, MAB, ShowInst);
1378 }