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