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