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