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