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