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