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