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