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