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