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