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