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