1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/MCObjectFileInfo.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCSectionCOFF.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/MC/MCAsmBackend.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
37 class MCAsmStreamer : public MCStreamer {
39 formatted_raw_ostream &OS;
42 OwningPtr<MCInstPrinter> InstPrinter;
43 OwningPtr<MCCodeEmitter> Emitter;
44 OwningPtr<MCAsmBackend> AsmBackend;
46 SmallString<128> CommentToEmit;
47 raw_svector_ostream CommentStream;
49 unsigned IsVerboseAsm : 1;
50 unsigned ShowInst : 1;
54 enum EHSymbolFlags { EHGlobal = 1,
55 EHWeakDefinition = 1 << 1,
56 EHPrivateExtern = 1 << 2 };
57 DenseMap<const MCSymbol*, unsigned> FlagMap;
59 bool needsSet(const MCExpr *Value);
61 void EmitRegisterName(int64_t Register);
64 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
65 bool isVerboseAsm, bool useLoc, bool useCFI,
66 MCInstPrinter *printer, MCCodeEmitter *emitter,
67 MCAsmBackend *asmbackend,
69 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
70 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
71 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
72 ShowInst(showInst), UseLoc(useLoc), UseCFI(useCFI) {
73 if (InstPrinter && IsVerboseAsm)
74 InstPrinter->setCommentStream(CommentStream);
78 inline void EmitEOL() {
79 // If we don't have any comments, just emit a \n.
86 void EmitCommentsAndEOL();
88 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
90 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
92 /// hasRawTextSupport - We support EmitRawText.
93 virtual bool hasRawTextSupport() const { return true; }
95 /// AddComment - Add a comment that can be emitted to the generated .s
96 /// file if applicable as a QoI issue to make the output of the compiler
97 /// more readable. This only affects the MCAsmStreamer, and only when
98 /// verbose assembly output is enabled.
99 virtual void AddComment(const Twine &T);
101 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
102 virtual void AddEncodingComment(const MCInst &Inst);
104 /// GetCommentOS - Return a raw_ostream that comments can be written to.
105 /// Unlike AddComment, you are required to terminate comments with \n if you
107 virtual raw_ostream &GetCommentOS() {
109 return nulls(); // Discard comments unless in verbose asm mode.
110 return CommentStream;
113 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
114 virtual void AddBlankLine() {
118 /// @name MCStreamer Interface
121 virtual void ChangeSection(const MCSection *Section);
123 virtual void InitSections() {
124 // FIXME, this is MachO specific, but the testsuite
126 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
127 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
128 0, SectionKind::getText()));
131 virtual void EmitLabel(MCSymbol *Symbol);
132 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
134 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
135 virtual void EmitThumbFunc(MCSymbol *Func);
137 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
138 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
139 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
140 const MCSymbol *LastLabel,
141 const MCSymbol *Label,
142 unsigned PointerSize);
143 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
144 const MCSymbol *Label);
146 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
148 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
149 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
150 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
151 virtual void EmitCOFFSymbolType(int Type);
152 virtual void EndCOFFSymbolDef();
153 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
154 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
155 unsigned ByteAlignment);
157 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
159 /// @param Symbol - The common symbol to emit.
160 /// @param Size - The size of the common symbol.
161 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
163 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
164 unsigned Size = 0, unsigned ByteAlignment = 0);
166 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
167 uint64_t Size, unsigned ByteAlignment = 0);
169 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
171 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
173 virtual void EmitIntValue(uint64_t Value, unsigned Size,
174 unsigned AddrSpace = 0);
176 virtual void EmitULEB128Value(const MCExpr *Value);
178 virtual void EmitSLEB128Value(const MCExpr *Value);
180 virtual void EmitGPRel32Value(const MCExpr *Value);
183 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
186 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
187 unsigned ValueSize = 1,
188 unsigned MaxBytesToEmit = 0);
190 virtual void EmitCodeAlignment(unsigned ByteAlignment,
191 unsigned MaxBytesToEmit = 0);
193 virtual void EmitValueToOffset(const MCExpr *Offset,
194 unsigned char Value = 0);
196 virtual void EmitFileDirective(StringRef Filename);
197 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
198 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
199 unsigned Column, unsigned Flags,
200 unsigned Isa, unsigned Discriminator,
203 virtual void EmitCFISections(bool EH, bool Debug);
204 virtual void EmitCFIStartProc();
205 virtual void EmitCFIEndProc();
206 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
207 virtual void EmitCFIDefCfaOffset(int64_t Offset);
208 virtual void EmitCFIDefCfaRegister(int64_t Register);
209 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
210 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
211 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
212 virtual void EmitCFIRememberState();
213 virtual void EmitCFIRestoreState();
214 virtual void EmitCFISameValue(int64_t Register);
215 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
216 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
218 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
219 virtual void EmitWin64EHEndProc();
220 virtual void EmitWin64EHStartChained();
221 virtual void EmitWin64EHEndChained();
222 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
224 virtual void EmitWin64EHHandlerData();
225 virtual void EmitWin64EHPushReg(unsigned Register);
226 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
227 virtual void EmitWin64EHAllocStack(unsigned Size);
228 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
229 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
230 virtual void EmitWin64EHPushFrame(bool Code);
231 virtual void EmitWin64EHEndProlog();
233 virtual void EmitFnStart();
234 virtual void EmitFnEnd();
235 virtual void EmitCantUnwind();
236 virtual void EmitPersonality(const MCSymbol *Personality);
237 virtual void EmitHandlerData();
238 virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
239 virtual void EmitPad(int64_t Offset);
240 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList, bool);
243 virtual void EmitInstruction(const MCInst &Inst);
245 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
246 /// the specified string in the output .s file. This capability is
247 /// indicated by the hasRawTextSupport() predicate.
248 virtual void EmitRawText(StringRef String);
250 virtual void Finish();
255 } // end anonymous namespace.
257 /// AddComment - Add a comment that can be emitted to the generated .s
258 /// file if applicable as a QoI issue to make the output of the compiler
259 /// more readable. This only affects the MCAsmStreamer, and only when
260 /// verbose assembly output is enabled.
261 void MCAsmStreamer::AddComment(const Twine &T) {
262 if (!IsVerboseAsm) return;
264 // Make sure that CommentStream is flushed.
265 CommentStream.flush();
267 T.toVector(CommentToEmit);
268 // Each comment goes on its own line.
269 CommentToEmit.push_back('\n');
271 // Tell the comment stream that the vector changed underneath it.
272 CommentStream.resync();
275 void MCAsmStreamer::EmitCommentsAndEOL() {
276 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
281 CommentStream.flush();
282 StringRef Comments = CommentToEmit.str();
284 assert(Comments.back() == '\n' &&
285 "Comment array not newline terminated");
287 // Emit a line of comments.
288 OS.PadToColumn(MAI.getCommentColumn());
289 size_t Position = Comments.find('\n');
290 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
292 Comments = Comments.substr(Position+1);
293 } while (!Comments.empty());
295 CommentToEmit.clear();
296 // Tell the comment stream that the vector changed underneath it.
297 CommentStream.resync();
300 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
301 assert(Bytes && "Invalid size!");
302 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
305 void MCAsmStreamer::ChangeSection(const MCSection *Section) {
306 assert(Section && "Cannot switch to a null section!");
307 Section->PrintSwitchToSection(MAI, OS);
310 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
311 MCSymbol *EHSymbol) {
315 unsigned Flags = FlagMap.lookup(Symbol);
317 if (Flags & EHGlobal)
318 EmitSymbolAttribute(EHSymbol, MCSA_Global);
319 if (Flags & EHWeakDefinition)
320 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
321 if (Flags & EHPrivateExtern)
322 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
325 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
326 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
327 MCStreamer::EmitLabel(Symbol);
329 OS << *Symbol << MAI.getLabelSuffix();
333 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
335 default: assert(0 && "Invalid flag!");
336 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
337 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
338 case MCAF_Code16: OS << '\t'<< MAI.getCode16Directive(); break;
339 case MCAF_Code32: OS << '\t'<< MAI.getCode32Directive(); break;
340 case MCAF_Code64: OS << '\t'<< MAI.getCode64Directive(); break;
345 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
346 // This needs to emit to a temporary string to get properly quoted
347 // MCSymbols when they have spaces in them.
348 OS << "\t.thumb_func";
349 // Only Mach-O hasSubsectionsViaSymbols()
350 if (MAI.hasSubsectionsViaSymbols())
355 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
356 OS << *Symbol << " = " << *Value;
359 // FIXME: Lift context changes into super class.
360 Symbol->setVariableValue(Value);
363 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
364 OS << ".weakref " << *Alias << ", " << *Symbol;
368 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
369 const MCSymbol *LastLabel,
370 const MCSymbol *Label,
371 unsigned PointerSize) {
372 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
375 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
376 const MCSymbol *Label) {
377 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
378 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
379 AddrDelta = ForceExpAbs(AddrDelta);
380 EmitValue(AddrDelta, 4);
384 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
385 MCSymbolAttr Attribute) {
387 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
388 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
389 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
390 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
391 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
392 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
393 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
394 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
395 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
396 OS << "\t.type\t" << *Symbol << ','
397 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
399 default: assert(0 && "Unknown ELF .type");
400 case MCSA_ELF_TypeFunction: OS << "function"; break;
401 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
402 case MCSA_ELF_TypeObject: OS << "object"; break;
403 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
404 case MCSA_ELF_TypeCommon: OS << "common"; break;
405 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
406 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
410 case MCSA_Global: // .globl/.global
411 OS << MAI.getGlobalDirective();
412 FlagMap[Symbol] |= EHGlobal;
414 case MCSA_Hidden: OS << "\t.hidden\t"; break;
415 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
416 case MCSA_Internal: OS << "\t.internal\t"; break;
417 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
418 case MCSA_Local: OS << "\t.local\t"; break;
419 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
420 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
421 case MCSA_PrivateExtern:
422 OS << "\t.private_extern\t";
423 FlagMap[Symbol] |= EHPrivateExtern;
425 case MCSA_Protected: OS << "\t.protected\t"; break;
426 case MCSA_Reference: OS << "\t.reference\t"; break;
427 case MCSA_Weak: OS << "\t.weak\t"; break;
428 case MCSA_WeakDefinition:
429 OS << "\t.weak_definition\t";
430 FlagMap[Symbol] |= EHWeakDefinition;
433 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
434 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
441 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
442 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
446 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
447 OS << "\t.def\t " << *Symbol << ';';
451 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
452 OS << "\t.scl\t" << StorageClass << ';';
456 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
457 OS << "\t.type\t" << Type << ';';
461 void MCAsmStreamer::EndCOFFSymbolDef() {
466 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
467 assert(MAI.hasDotTypeDotSizeDirective());
468 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
471 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
472 unsigned ByteAlignment) {
473 OS << "\t.comm\t" << *Symbol << ',' << Size;
474 if (ByteAlignment != 0) {
475 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
476 OS << ',' << ByteAlignment;
478 OS << ',' << Log2_32(ByteAlignment);
483 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
485 /// @param Symbol - The common symbol to emit.
486 /// @param Size - The size of the common symbol.
487 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
488 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
489 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
493 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
494 unsigned Size, unsigned ByteAlignment) {
495 // Note: a .zerofill directive does not switch sections.
498 // This is a mach-o specific directive.
499 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
500 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
502 if (Symbol != NULL) {
503 OS << ',' << *Symbol << ',' << Size;
504 if (ByteAlignment != 0)
505 OS << ',' << Log2_32(ByteAlignment);
510 // .tbss sym, size, align
511 // This depends that the symbol has already been mangled from the original,
513 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
514 uint64_t Size, unsigned ByteAlignment) {
515 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
516 // Instead of using the Section we'll just use the shortcut.
517 // This is a mach-o specific directive and section.
518 OS << ".tbss " << *Symbol << ", " << Size;
520 // Output align if we have it. We default to 1 so don't bother printing
522 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
527 static inline char toOctal(int X) { return (X&7)+'0'; }
529 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
532 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
533 unsigned char C = Data[i];
534 if (C == '"' || C == '\\') {
535 OS << '\\' << (char)C;
539 if (isprint((unsigned char)C)) {
545 case '\b': OS << "\\b"; break;
546 case '\f': OS << "\\f"; break;
547 case '\n': OS << "\\n"; break;
548 case '\r': OS << "\\r"; break;
549 case '\t': OS << "\\t"; break;
552 OS << toOctal(C >> 6);
553 OS << toOctal(C >> 3);
554 OS << toOctal(C >> 0);
563 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
564 assert(getCurrentSection() && "Cannot emit contents before setting section!");
565 if (Data.empty()) return;
567 if (Data.size() == 1) {
568 OS << MAI.getData8bitsDirective(AddrSpace);
569 OS << (unsigned)(unsigned char)Data[0];
574 // If the data ends with 0 and the target supports .asciz, use it, otherwise
576 if (MAI.getAscizDirective() && Data.back() == 0) {
577 OS << MAI.getAscizDirective();
578 Data = Data.substr(0, Data.size()-1);
580 OS << MAI.getAsciiDirective();
584 PrintQuotedString(Data, OS);
588 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
589 unsigned AddrSpace) {
590 EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
593 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
594 unsigned AddrSpace) {
595 assert(getCurrentSection() && "Cannot emit contents before setting section!");
596 const char *Directive = 0;
599 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
600 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
601 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
603 Directive = MAI.getData64bitsDirective(AddrSpace);
604 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
605 if (Directive) break;
607 if (!Value->EvaluateAsAbsolute(IntValue))
608 report_fatal_error("Don't know how to emit this value.");
609 if (getContext().getAsmInfo().isLittleEndian()) {
610 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
611 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
613 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
614 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
619 assert(Directive && "Invalid size for machine code value!");
620 OS << Directive << *Value;
624 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
626 if (Value->EvaluateAsAbsolute(IntValue)) {
627 EmitULEB128IntValue(IntValue);
630 assert(MAI.hasLEB128() && "Cannot print a .uleb");
631 OS << ".uleb128 " << *Value;
635 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
637 if (Value->EvaluateAsAbsolute(IntValue)) {
638 EmitSLEB128IntValue(IntValue);
641 assert(MAI.hasLEB128() && "Cannot print a .sleb");
642 OS << ".sleb128 " << *Value;
646 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
647 assert(MAI.getGPRel32Directive() != 0);
648 OS << MAI.getGPRel32Directive() << *Value;
653 /// EmitFill - Emit NumBytes bytes worth of the value specified by
654 /// FillValue. This implements directives such as '.space'.
655 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
656 unsigned AddrSpace) {
657 if (NumBytes == 0) return;
660 if (const char *ZeroDirective = MAI.getZeroDirective()) {
661 OS << ZeroDirective << NumBytes;
663 OS << ',' << (int)FillValue;
668 // Emit a byte at a time.
669 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
672 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
674 unsigned MaxBytesToEmit) {
675 // Some assemblers don't support non-power of two alignments, so we always
676 // emit alignments as a power of two if possible.
677 if (isPowerOf2_32(ByteAlignment)) {
679 default: llvm_unreachable("Invalid size for machine code value!");
680 case 1: OS << MAI.getAlignDirective(); break;
681 // FIXME: use MAI for this!
682 case 2: OS << ".p2alignw "; break;
683 case 4: OS << ".p2alignl "; break;
684 case 8: llvm_unreachable("Unsupported alignment size!");
687 if (MAI.getAlignmentIsInBytes())
690 OS << Log2_32(ByteAlignment);
692 if (Value || MaxBytesToEmit) {
694 OS.write_hex(truncateToSize(Value, ValueSize));
697 OS << ", " << MaxBytesToEmit;
703 // Non-power of two alignment. This is not widely supported by assemblers.
704 // FIXME: Parameterize this based on MAI.
706 default: llvm_unreachable("Invalid size for machine code value!");
707 case 1: OS << ".balign"; break;
708 case 2: OS << ".balignw"; break;
709 case 4: OS << ".balignl"; break;
710 case 8: llvm_unreachable("Unsupported alignment size!");
713 OS << ' ' << ByteAlignment;
714 OS << ", " << truncateToSize(Value, ValueSize);
716 OS << ", " << MaxBytesToEmit;
720 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
721 unsigned MaxBytesToEmit) {
722 // Emit with a text fill value.
723 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
727 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
728 unsigned char Value) {
729 // FIXME: Verify that Offset is associated with the current section.
730 OS << ".org " << *Offset << ", " << (unsigned) Value;
735 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
736 assert(MAI.hasSingleParameterDotFile());
738 PrintQuotedString(Filename, OS);
742 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
744 OS << "\t.file\t" << FileNo << ' ';
745 PrintQuotedString(Filename, OS);
748 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
751 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
752 unsigned Column, unsigned Flags,
754 unsigned Discriminator,
755 StringRef FileName) {
756 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
757 Isa, Discriminator, FileName);
761 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
762 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
763 OS << " basic_block";
764 if (Flags & DWARF2_FLAG_PROLOGUE_END)
765 OS << " prologue_end";
766 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
767 OS << " epilogue_begin";
769 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
770 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
773 if (Flags & DWARF2_FLAG_IS_STMT)
782 OS << "discriminator " << Discriminator;
785 OS.PadToColumn(MAI.getCommentColumn());
786 OS << MAI.getCommentString() << ' ' << FileName << ':'
787 << Line << ':' << Column;
792 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
793 MCStreamer::EmitCFISections(EH, Debug);
798 OS << "\t.cfi_sections ";
802 OS << ", .debug_frame";
804 OS << ".debug_frame";
810 void MCAsmStreamer::EmitCFIStartProc() {
811 MCStreamer::EmitCFIStartProc();
816 OS << "\t.cfi_startproc";
820 void MCAsmStreamer::EmitCFIEndProc() {
821 MCStreamer::EmitCFIEndProc();
826 OS << "\t.cfi_endproc";
830 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
831 if (InstPrinter && !MAI.useDwarfRegNumForCFI()) {
832 const MCRegisterInfo &MRI = getContext().getRegisterInfo();
833 unsigned LLVMRegister = MRI.getLLVMRegNum(Register, true);
834 InstPrinter->printRegName(OS, LLVMRegister);
840 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
841 MCStreamer::EmitCFIDefCfa(Register, Offset);
846 OS << "\t.cfi_def_cfa ";
847 EmitRegisterName(Register);
848 OS << ", " << Offset;
852 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
853 MCStreamer::EmitCFIDefCfaOffset(Offset);
858 OS << "\t.cfi_def_cfa_offset " << Offset;
862 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
863 MCStreamer::EmitCFIDefCfaRegister(Register);
868 OS << "\t.cfi_def_cfa_register ";
869 EmitRegisterName(Register);
873 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
874 this->MCStreamer::EmitCFIOffset(Register, Offset);
879 OS << "\t.cfi_offset ";
880 EmitRegisterName(Register);
881 OS << ", " << Offset;
885 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
887 MCStreamer::EmitCFIPersonality(Sym, Encoding);
892 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
896 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
897 MCStreamer::EmitCFILsda(Sym, Encoding);
902 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
906 void MCAsmStreamer::EmitCFIRememberState() {
907 MCStreamer::EmitCFIRememberState();
912 OS << "\t.cfi_remember_state";
916 void MCAsmStreamer::EmitCFIRestoreState() {
917 MCStreamer::EmitCFIRestoreState();
922 OS << "\t.cfi_restore_state";
926 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
927 MCStreamer::EmitCFISameValue(Register);
932 OS << "\t.cfi_same_value ";
933 EmitRegisterName(Register);
937 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
938 MCStreamer::EmitCFIRelOffset(Register, Offset);
943 OS << "\t.cfi_rel_offset ";
944 EmitRegisterName(Register);
945 OS << ", " << Offset;
949 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
950 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
955 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
959 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
960 MCStreamer::EmitWin64EHStartProc(Symbol);
962 OS << ".seh_proc " << *Symbol;
966 void MCAsmStreamer::EmitWin64EHEndProc() {
967 MCStreamer::EmitWin64EHEndProc();
969 OS << "\t.seh_endproc";
973 void MCAsmStreamer::EmitWin64EHStartChained() {
974 MCStreamer::EmitWin64EHStartChained();
976 OS << "\t.seh_startchained";
980 void MCAsmStreamer::EmitWin64EHEndChained() {
981 MCStreamer::EmitWin64EHEndChained();
983 OS << "\t.seh_endchained";
987 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
989 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
991 OS << "\t.seh_handler " << *Sym;
999 static const MCSection *getWin64EHTableSection(StringRef suffix,
1000 MCContext &context) {
1001 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1002 /// this duplicate code in MCWin64EH.cpp.
1004 return context.getObjectFileInfo()->getXDataSection();
1005 return context.getCOFFSection((".xdata"+suffix).str(),
1006 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1007 COFF::IMAGE_SCN_MEM_READ |
1008 COFF::IMAGE_SCN_MEM_WRITE,
1009 SectionKind::getDataRel());
1012 void MCAsmStreamer::EmitWin64EHHandlerData() {
1013 MCStreamer::EmitWin64EHHandlerData();
1015 // Switch sections. Don't call SwitchSection directly, because that will
1016 // cause the section switch to be visible in the emitted assembly.
1017 // We only do this so the section switch that terminates the handler
1018 // data block is visible.
1019 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1020 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1021 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1023 SwitchSectionNoChange(xdataSect);
1025 OS << "\t.seh_handlerdata";
1029 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1030 MCStreamer::EmitWin64EHPushReg(Register);
1032 OS << "\t.seh_pushreg " << Register;
1036 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1037 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1039 OS << "\t.seh_setframe " << Register << ", " << Offset;
1043 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1044 MCStreamer::EmitWin64EHAllocStack(Size);
1046 OS << "\t.seh_stackalloc " << Size;
1050 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1051 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1053 OS << "\t.seh_savereg " << Register << ", " << Offset;
1057 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1058 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1060 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1064 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1065 MCStreamer::EmitWin64EHPushFrame(Code);
1067 OS << "\t.seh_pushframe";
1073 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1074 MCStreamer::EmitWin64EHEndProlog();
1076 OS << "\t.seh_endprologue";
1080 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
1081 raw_ostream &OS = GetCommentOS();
1082 SmallString<256> Code;
1083 SmallVector<MCFixup, 4> Fixups;
1084 raw_svector_ostream VecOS(Code);
1085 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
1088 // If we are showing fixups, create symbolic markers in the encoded
1089 // representation. We do this by making a per-bit map to the fixup item index,
1090 // then trying to display it as nicely as possible.
1091 SmallVector<uint8_t, 64> FixupMap;
1092 FixupMap.resize(Code.size() * 8);
1093 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1096 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1097 MCFixup &F = Fixups[i];
1098 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1099 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1100 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1101 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1102 FixupMap[Index] = 1 + i;
1106 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1107 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1108 OS << "encoding: [";
1109 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1113 // See if all bits are the same map entry.
1114 uint8_t MapEntry = FixupMap[i * 8 + 0];
1115 for (unsigned j = 1; j != 8; ++j) {
1116 if (FixupMap[i * 8 + j] == MapEntry)
1119 MapEntry = uint8_t(~0U);
1123 if (MapEntry != uint8_t(~0U)) {
1124 if (MapEntry == 0) {
1125 OS << format("0x%02x", uint8_t(Code[i]));
1128 // FIXME: Some of the 8 bits require fix up.
1129 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1130 << char('A' + MapEntry - 1) << '\'';
1132 OS << char('A' + MapEntry - 1);
1135 // Otherwise, write out in binary.
1137 for (unsigned j = 8; j--;) {
1138 unsigned Bit = (Code[i] >> j) & 1;
1141 if (getContext().getAsmInfo().isLittleEndian())
1142 FixupBit = i * 8 + j;
1144 FixupBit = i * 8 + (7-j);
1146 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1147 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1148 OS << char('A' + MapEntry - 1);
1156 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1157 MCFixup &F = Fixups[i];
1158 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1159 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1160 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1164 void MCAsmStreamer::EmitFnStart() {
1169 void MCAsmStreamer::EmitFnEnd() {
1174 void MCAsmStreamer::EmitCantUnwind() {
1175 OS << "\t.cantunwind";
1179 void MCAsmStreamer::EmitHandlerData() {
1180 OS << "\t.handlerdata";
1184 void MCAsmStreamer::EmitPersonality(const MCSymbol *Personality) {
1185 OS << "\t.personality " << Personality->getName();
1189 void MCAsmStreamer::EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset) {
1191 InstPrinter->printRegName(OS, FpReg);
1193 InstPrinter->printRegName(OS, SpReg);
1195 OS << ", #" << Offset;
1199 void MCAsmStreamer::EmitPad(int64_t Offset) {
1200 OS << "\t.pad\t#" << Offset;
1204 void MCAsmStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
1206 assert(RegList.size() && "RegList should not be empty");
1208 OS << "\t.vsave\t{";
1212 InstPrinter->printRegName(OS, RegList[0]);
1214 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
1216 InstPrinter->printRegName(OS, RegList[i]);
1223 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
1224 assert(getCurrentSection() && "Cannot emit contents before setting section!");
1226 // Show the encoding in a comment if we have a code emitter.
1228 AddEncodingComment(Inst);
1230 // Show the MCInst if enabled.
1232 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
1233 GetCommentOS() << "\n";
1236 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1238 InstPrinter->printInst(&Inst, OS);
1240 Inst.print(OS, &MAI);
1244 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1245 /// the specified string in the output .s file. This capability is
1246 /// indicated by the hasRawTextSupport() predicate.
1247 void MCAsmStreamer::EmitRawText(StringRef String) {
1248 if (!String.empty() && String.back() == '\n')
1249 String = String.substr(0, String.size()-1);
1254 void MCAsmStreamer::Finish() {
1255 // Dump out the dwarf file & directory tables and line tables.
1256 if (getContext().hasDwarfFiles() && !UseLoc)
1257 MCDwarfFileTable::Emit(this);
1262 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1263 formatted_raw_ostream &OS,
1264 bool isVerboseAsm, bool useLoc,
1265 bool useCFI, MCInstPrinter *IP,
1266 MCCodeEmitter *CE, MCAsmBackend *MAB,
1268 return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc, useCFI,
1269 IP, CE, MAB, ShowInst);