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