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