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