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