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