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/ADT/OwningPtr.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Path.h"
39 class MCAsmStreamer : public MCStreamer {
41 formatted_raw_ostream &OS;
44 OwningPtr<MCInstPrinter> InstPrinter;
45 OwningPtr<MCCodeEmitter> Emitter;
46 OwningPtr<MCAsmBackend> AsmBackend;
48 SmallString<128> CommentToEmit;
49 raw_svector_ostream CommentStream;
51 unsigned IsVerboseAsm : 1;
52 unsigned ShowInst : 1;
54 unsigned UseDwarfDirectory : 1;
56 enum EHSymbolFlags { EHGlobal = 1,
57 EHWeakDefinition = 1 << 1,
58 EHPrivateExtern = 1 << 2 };
59 DenseMap<const MCSymbol*, unsigned> FlagMap;
61 bool needsSet(const MCExpr *Value);
63 void EmitRegisterName(int64_t Register);
64 virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
65 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame);
68 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
69 bool isVerboseAsm, bool useCFI, bool useDwarfDirectory,
70 MCInstPrinter *printer, MCCodeEmitter *emitter,
71 MCAsmBackend *asmbackend, bool showInst)
72 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
73 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
74 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
75 ShowInst(showInst), UseCFI(useCFI),
76 UseDwarfDirectory(useDwarfDirectory) {
77 if (InstPrinter && IsVerboseAsm)
78 InstPrinter->setCommentStream(CommentStream);
82 inline void EmitEOL() {
83 // If we don't have any comments, just emit a \n.
90 void EmitCommentsAndEOL();
92 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
94 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
96 /// hasRawTextSupport - We support EmitRawText.
97 virtual bool hasRawTextSupport() const { return true; }
99 /// AddComment - Add a comment that can be emitted to the generated .s
100 /// file if applicable as a QoI issue to make the output of the compiler
101 /// more readable. This only affects the MCAsmStreamer, and only when
102 /// verbose assembly output is enabled.
103 virtual void AddComment(const Twine &T);
105 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
106 virtual void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
108 /// GetCommentOS - Return a raw_ostream that comments can be written to.
109 /// Unlike AddComment, you are required to terminate comments with \n if you
111 virtual raw_ostream &GetCommentOS() {
113 return nulls(); // Discard comments unless in verbose asm mode.
114 return CommentStream;
117 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
119 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
120 virtual void AddBlankLine() {
124 /// @name MCStreamer Interface
127 virtual void ChangeSection(const MCSection *Section,
128 const MCExpr *Subsection);
130 virtual void EmitLabel(MCSymbol *Symbol);
131 virtual void EmitDebugLabel(MCSymbol *Symbol);
133 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
135 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
136 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
137 virtual void EmitDataRegion(MCDataRegionType Kind);
138 virtual void EmitThumbFunc(MCSymbol *Func);
140 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
141 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
142 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
143 const MCSymbol *LastLabel,
144 const MCSymbol *Label,
145 unsigned PointerSize);
146 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
147 const MCSymbol *Label);
149 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
151 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
152 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
153 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
154 virtual void EmitCOFFSymbolType(int Type);
155 virtual void EndCOFFSymbolDef();
156 virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
157 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
158 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
159 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
160 unsigned ByteAlignment);
162 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
164 /// @param Symbol - The common symbol to emit.
165 /// @param Size - The size of the common symbol.
166 /// @param ByteAlignment - The alignment of the common symbol in bytes.
167 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
168 unsigned ByteAlignment);
170 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
171 uint64_t Size = 0, unsigned ByteAlignment = 0);
173 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
174 uint64_t Size, unsigned ByteAlignment = 0);
176 virtual void EmitBytes(StringRef Data);
178 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size);
179 virtual void EmitIntValue(uint64_t Value, unsigned Size);
181 virtual void EmitULEB128Value(const MCExpr *Value);
183 virtual void EmitSLEB128Value(const MCExpr *Value);
185 virtual void EmitGPRel64Value(const MCExpr *Value);
187 virtual void EmitGPRel32Value(const MCExpr *Value);
190 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue);
192 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
193 unsigned ValueSize = 1,
194 unsigned MaxBytesToEmit = 0);
196 virtual void EmitCodeAlignment(unsigned ByteAlignment,
197 unsigned MaxBytesToEmit = 0);
199 virtual bool EmitValueToOffset(const MCExpr *Offset,
200 unsigned char Value = 0);
202 virtual void EmitFileDirective(StringRef Filename);
203 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
204 StringRef Filename, unsigned CUID = 0);
205 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
206 unsigned Column, unsigned Flags,
207 unsigned Isa, unsigned Discriminator,
210 virtual void EmitIdent(StringRef IdentString);
211 virtual void EmitCFISections(bool EH, bool Debug);
212 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
213 virtual void EmitCFIDefCfaOffset(int64_t Offset);
214 virtual void EmitCFIDefCfaRegister(int64_t Register);
215 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
216 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
217 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
218 virtual void EmitCFIRememberState();
219 virtual void EmitCFIRestoreState();
220 virtual void EmitCFISameValue(int64_t Register);
221 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
222 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
223 virtual void EmitCFISignalFrame();
224 virtual void EmitCFIUndefined(int64_t Register);
225 virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
226 virtual void EmitCFIWindowSave();
228 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
229 virtual void EmitWin64EHEndProc();
230 virtual void EmitWin64EHStartChained();
231 virtual void EmitWin64EHEndChained();
232 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
234 virtual void EmitWin64EHHandlerData();
235 virtual void EmitWin64EHPushReg(unsigned Register);
236 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
237 virtual void EmitWin64EHAllocStack(unsigned Size);
238 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
239 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
240 virtual void EmitWin64EHPushFrame(bool Code);
241 virtual void EmitWin64EHEndProlog();
243 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI);
245 virtual void EmitBundleAlignMode(unsigned AlignPow2);
246 virtual void EmitBundleLock(bool AlignToEnd);
247 virtual void EmitBundleUnlock();
249 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
250 /// the specified string in the output .s file. This capability is
251 /// indicated by the hasRawTextSupport() predicate.
252 virtual void EmitRawTextImpl(StringRef String);
254 virtual void FinishImpl();
257 } // end anonymous namespace.
259 /// AddComment - Add a comment that can be emitted to the generated .s
260 /// file if applicable as a QoI issue to make the output of the compiler
261 /// more readable. This only affects the MCAsmStreamer, and only when
262 /// verbose assembly output is enabled.
263 void MCAsmStreamer::AddComment(const Twine &T) {
264 if (!IsVerboseAsm) return;
266 // Make sure that CommentStream is flushed.
267 CommentStream.flush();
269 T.toVector(CommentToEmit);
270 // Each comment goes on its own line.
271 CommentToEmit.push_back('\n');
273 // Tell the comment stream that the vector changed underneath it.
274 CommentStream.resync();
277 void MCAsmStreamer::EmitCommentsAndEOL() {
278 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
283 CommentStream.flush();
284 StringRef Comments = CommentToEmit.str();
286 assert(Comments.back() == '\n' &&
287 "Comment array not newline terminated");
289 // Emit a line of comments.
290 OS.PadToColumn(MAI->getCommentColumn());
291 size_t Position = Comments.find('\n');
292 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
294 Comments = Comments.substr(Position+1);
295 } while (!Comments.empty());
297 CommentToEmit.clear();
298 // Tell the comment stream that the vector changed underneath it.
299 CommentStream.resync();
302 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
303 assert(Bytes && "Invalid size!");
304 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
307 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
310 OS << MAI->getCommentString() << T;
314 void MCAsmStreamer::ChangeSection(const MCSection *Section,
315 const MCExpr *Subsection) {
316 assert(Section && "Cannot switch to a null section!");
317 Section->PrintSwitchToSection(*MAI, OS, Subsection);
320 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
321 MCSymbol *EHSymbol) {
325 unsigned Flags = FlagMap.lookup(Symbol);
327 if (Flags & EHGlobal)
328 EmitSymbolAttribute(EHSymbol, MCSA_Global);
329 if (Flags & EHWeakDefinition)
330 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
331 if (Flags & EHPrivateExtern)
332 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
335 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
336 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
337 MCStreamer::EmitLabel(Symbol);
339 OS << *Symbol << MAI->getLabelSuffix();
343 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
344 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
345 MCStreamer::EmitDebugLabel(Symbol);
347 OS << *Symbol << MAI->getDebugLabelSuffix();
351 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
353 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
354 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
355 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
356 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
357 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
362 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
363 assert(!Options.empty() && "At least one option is required!");
364 OS << "\t.linker_option \"" << Options[0] << '"';
365 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
366 ie = Options.end(); it != ie; ++it) {
367 OS << ", " << '"' << *it << '"';
372 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
373 if (!MAI->doesSupportDataRegionDirectives())
376 case MCDR_DataRegion: OS << "\t.data_region"; break;
377 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
378 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
379 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
380 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
385 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
386 // This needs to emit to a temporary string to get properly quoted
387 // MCSymbols when they have spaces in them.
388 OS << "\t.thumb_func";
389 // Only Mach-O hasSubsectionsViaSymbols()
390 if (MAI->hasSubsectionsViaSymbols())
395 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
396 OS << *Symbol << " = " << *Value;
399 // FIXME: Lift context changes into super class.
400 Symbol->setVariableValue(Value);
403 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
404 OS << ".weakref " << *Alias << ", " << *Symbol;
408 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
409 const MCSymbol *LastLabel,
410 const MCSymbol *Label,
411 unsigned PointerSize) {
412 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
415 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
416 const MCSymbol *Label) {
417 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
418 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
419 AddrDelta = ForceExpAbs(AddrDelta);
420 EmitValue(AddrDelta, 4);
424 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
425 MCSymbolAttr Attribute) {
427 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
428 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
429 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
430 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
431 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
432 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
433 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
434 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
435 if (!MAI->hasDotTypeDotSizeDirective())
436 return false; // Symbol attribute not supported
437 OS << "\t.type\t" << *Symbol << ','
438 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
440 default: return false;
441 case MCSA_ELF_TypeFunction: OS << "function"; break;
442 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
443 case MCSA_ELF_TypeObject: OS << "object"; break;
444 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
445 case MCSA_ELF_TypeCommon: OS << "common"; break;
446 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
447 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
451 case MCSA_Global: // .globl/.global
452 OS << MAI->getGlobalDirective();
453 FlagMap[Symbol] |= EHGlobal;
455 case MCSA_Hidden: OS << "\t.hidden\t"; break;
456 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
457 case MCSA_Internal: OS << "\t.internal\t"; break;
458 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
459 case MCSA_Local: OS << "\t.local\t"; break;
460 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
461 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
462 case MCSA_PrivateExtern:
463 OS << "\t.private_extern\t";
464 FlagMap[Symbol] |= EHPrivateExtern;
466 case MCSA_Protected: OS << "\t.protected\t"; break;
467 case MCSA_Reference: OS << "\t.reference\t"; break;
468 case MCSA_Weak: OS << "\t.weak\t"; break;
469 case MCSA_WeakDefinition:
470 OS << "\t.weak_definition\t";
471 FlagMap[Symbol] |= EHWeakDefinition;
474 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
475 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
484 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
485 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
489 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
490 OS << "\t.def\t " << *Symbol << ';';
494 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
495 OS << "\t.scl\t" << StorageClass << ';';
499 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
500 OS << "\t.type\t" << Type << ';';
504 void MCAsmStreamer::EndCOFFSymbolDef() {
509 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
510 OS << "\t.secidx\t" << *Symbol;
514 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
515 OS << "\t.secrel32\t" << *Symbol;
519 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
520 assert(MAI->hasDotTypeDotSizeDirective());
521 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
524 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
525 unsigned ByteAlignment) {
526 // Common symbols do not belong to any actual section.
527 AssignSection(Symbol, NULL);
529 OS << "\t.comm\t" << *Symbol << ',' << Size;
530 if (ByteAlignment != 0) {
531 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
532 OS << ',' << ByteAlignment;
534 OS << ',' << Log2_32(ByteAlignment);
539 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
541 /// @param Symbol - The common symbol to emit.
542 /// @param Size - The size of the common symbol.
543 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
544 unsigned ByteAlign) {
545 // Common symbols do not belong to any actual section.
546 AssignSection(Symbol, NULL);
548 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
550 switch (MAI->getLCOMMDirectiveAlignmentType()) {
551 case LCOMM::NoAlignment:
552 llvm_unreachable("alignment not supported on .lcomm!");
553 case LCOMM::ByteAlignment:
554 OS << ',' << ByteAlign;
556 case LCOMM::Log2Alignment:
557 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
558 OS << ',' << Log2_32(ByteAlign);
565 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
566 uint64_t Size, unsigned ByteAlignment) {
568 AssignSection(Symbol, Section);
570 // Note: a .zerofill directive does not switch sections.
573 // This is a mach-o specific directive.
574 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
575 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
577 if (Symbol != NULL) {
578 OS << ',' << *Symbol << ',' << Size;
579 if (ByteAlignment != 0)
580 OS << ',' << Log2_32(ByteAlignment);
585 // .tbss sym, size, align
586 // This depends that the symbol has already been mangled from the original,
588 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
589 uint64_t Size, unsigned ByteAlignment) {
590 AssignSection(Symbol, Section);
592 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
593 // Instead of using the Section we'll just use the shortcut.
594 // This is a mach-o specific directive and section.
595 OS << ".tbss " << *Symbol << ", " << Size;
597 // Output align if we have it. We default to 1 so don't bother printing
599 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
604 static inline char toOctal(int X) { return (X&7)+'0'; }
606 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
609 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
610 unsigned char C = Data[i];
611 if (C == '"' || C == '\\') {
612 OS << '\\' << (char)C;
616 if (isprint((unsigned char)C)) {
622 case '\b': OS << "\\b"; break;
623 case '\f': OS << "\\f"; break;
624 case '\n': OS << "\\n"; break;
625 case '\r': OS << "\\r"; break;
626 case '\t': OS << "\\t"; break;
629 OS << toOctal(C >> 6);
630 OS << toOctal(C >> 3);
631 OS << toOctal(C >> 0);
640 void MCAsmStreamer::EmitBytes(StringRef Data) {
641 assert(getCurrentSection().first &&
642 "Cannot emit contents before setting section!");
643 if (Data.empty()) return;
645 if (Data.size() == 1) {
646 OS << MAI->getData8bitsDirective();
647 OS << (unsigned)(unsigned char)Data[0];
652 // If the data ends with 0 and the target supports .asciz, use it, otherwise
654 if (MAI->getAscizDirective() && Data.back() == 0) {
655 OS << MAI->getAscizDirective();
656 Data = Data.substr(0, Data.size()-1);
658 OS << MAI->getAsciiDirective();
661 PrintQuotedString(Data, OS);
665 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
666 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
669 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
670 assert(Size <= 8 && "Invalid size");
671 assert(getCurrentSection().first &&
672 "Cannot emit contents before setting section!");
673 const char *Directive = 0;
676 case 1: Directive = MAI->getData8bitsDirective(); break;
677 case 2: Directive = MAI->getData16bitsDirective(); break;
678 case 4: Directive = MAI->getData32bitsDirective(); break;
679 case 8: Directive = MAI->getData64bitsDirective(); break;
684 if (!Value->EvaluateAsAbsolute(IntValue))
685 report_fatal_error("Don't know how to emit this value.");
687 // We couldn't handle the requested integer size so we fallback by breaking
688 // the request down into several, smaller, integers. Since sizes greater
689 // than eight are invalid and size equivalent to eight should have been
690 // handled earlier, we use four bytes as our largest piece of granularity.
691 bool IsLittleEndian = MAI->isLittleEndian();
692 for (unsigned Emitted = 0; Emitted != Size;) {
693 unsigned Remaining = Size - Emitted;
694 // The size of our partial emission must be a power of two less than
696 unsigned EmissionSize = PowerOf2Floor(Remaining);
697 if (EmissionSize > 4)
699 // Calculate the byte offset of our partial emission taking into account
700 // the endianness of the target.
701 unsigned ByteOffset =
702 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
703 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
704 // We truncate our partial emission to fit within the bounds of the
705 // emission domain. This produces nicer output and silences potential
706 // truncation warnings when round tripping through another assembler.
707 ValueToEmit &= ~0ULL >> (64 - EmissionSize * 8);
708 EmitIntValue(ValueToEmit, EmissionSize);
709 Emitted += EmissionSize;
714 assert(Directive && "Invalid size for machine code value!");
715 OS << Directive << *Value;
719 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
721 if (Value->EvaluateAsAbsolute(IntValue)) {
722 EmitULEB128IntValue(IntValue);
725 assert(MAI->hasLEB128() && "Cannot print a .uleb");
726 OS << ".uleb128 " << *Value;
730 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
732 if (Value->EvaluateAsAbsolute(IntValue)) {
733 EmitSLEB128IntValue(IntValue);
736 assert(MAI->hasLEB128() && "Cannot print a .sleb");
737 OS << ".sleb128 " << *Value;
741 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
742 assert(MAI->getGPRel64Directive() != 0);
743 OS << MAI->getGPRel64Directive() << *Value;
747 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
748 assert(MAI->getGPRel32Directive() != 0);
749 OS << MAI->getGPRel32Directive() << *Value;
754 /// EmitFill - Emit NumBytes bytes worth of the value specified by
755 /// FillValue. This implements directives such as '.space'.
756 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
757 if (NumBytes == 0) return;
759 if (const char *ZeroDirective = MAI->getZeroDirective()) {
760 OS << ZeroDirective << NumBytes;
762 OS << ',' << (int)FillValue;
767 // Emit a byte at a time.
768 MCStreamer::EmitFill(NumBytes, FillValue);
771 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
773 unsigned MaxBytesToEmit) {
774 // Some assemblers don't support non-power of two alignments, so we always
775 // emit alignments as a power of two if possible.
776 if (isPowerOf2_32(ByteAlignment)) {
779 llvm_unreachable("Invalid size for machine code value!");
790 llvm_unreachable("Unsupported alignment size!");
793 if (MAI->getAlignmentIsInBytes())
796 OS << Log2_32(ByteAlignment);
798 if (Value || MaxBytesToEmit) {
800 OS.write_hex(truncateToSize(Value, ValueSize));
803 OS << ", " << MaxBytesToEmit;
809 // Non-power of two alignment. This is not widely supported by assemblers.
810 // FIXME: Parameterize this based on MAI.
812 default: llvm_unreachable("Invalid size for machine code value!");
813 case 1: OS << ".balign"; break;
814 case 2: OS << ".balignw"; break;
815 case 4: OS << ".balignl"; break;
816 case 8: llvm_unreachable("Unsupported alignment size!");
819 OS << ' ' << ByteAlignment;
820 OS << ", " << truncateToSize(Value, ValueSize);
822 OS << ", " << MaxBytesToEmit;
826 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
827 unsigned MaxBytesToEmit) {
828 // Emit with a text fill value.
829 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
833 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
834 unsigned char Value) {
835 // FIXME: Verify that Offset is associated with the current section.
836 OS << ".org " << *Offset << ", " << (unsigned) Value;
842 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
843 assert(MAI->hasSingleParameterDotFile());
845 PrintQuotedString(Filename, OS);
849 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
850 StringRef Filename, unsigned CUID) {
851 if (!UseDwarfDirectory && !Directory.empty()) {
852 if (sys::path::is_absolute(Filename))
853 return EmitDwarfFileDirective(FileNo, "", Filename, CUID);
855 SmallString<128> FullPathName = Directory;
856 sys::path::append(FullPathName, Filename);
857 return EmitDwarfFileDirective(FileNo, "", FullPathName, CUID);
860 OS << "\t.file\t" << FileNo << ' ';
861 if (!Directory.empty()) {
862 PrintQuotedString(Directory, OS);
865 PrintQuotedString(Filename, OS);
867 // All .file will belong to a single CUID.
870 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Directory, Filename,
874 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
875 unsigned Column, unsigned Flags,
877 unsigned Discriminator,
878 StringRef FileName) {
879 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
880 Isa, Discriminator, FileName);
881 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
882 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
883 OS << " basic_block";
884 if (Flags & DWARF2_FLAG_PROLOGUE_END)
885 OS << " prologue_end";
886 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
887 OS << " epilogue_begin";
889 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
890 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
893 if (Flags & DWARF2_FLAG_IS_STMT)
900 OS << " isa " << Isa;
902 OS << " discriminator " << Discriminator;
905 OS.PadToColumn(MAI->getCommentColumn());
906 OS << MAI->getCommentString() << ' ' << FileName << ':'
907 << Line << ':' << Column;
912 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
913 assert(MAI->hasIdentDirective() && ".ident directive not supported");
915 PrintQuotedString(IdentString, OS);
919 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
920 MCStreamer::EmitCFISections(EH, Debug);
925 OS << "\t.cfi_sections ";
929 OS << ", .debug_frame";
931 OS << ".debug_frame";
937 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
939 RecordProcStart(Frame);
943 OS << "\t.cfi_startproc";
949 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
951 RecordProcEnd(Frame);
955 // Put a dummy non-null value in Frame.End to mark that this frame has been
957 Frame.End = (MCSymbol *) 1;
959 OS << "\t.cfi_endproc";
963 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
964 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
965 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
966 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
967 InstPrinter->printRegName(OS, LLVMRegister);
973 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
974 MCStreamer::EmitCFIDefCfa(Register, Offset);
979 OS << "\t.cfi_def_cfa ";
980 EmitRegisterName(Register);
981 OS << ", " << Offset;
985 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
986 MCStreamer::EmitCFIDefCfaOffset(Offset);
991 OS << "\t.cfi_def_cfa_offset " << Offset;
995 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
996 MCStreamer::EmitCFIDefCfaRegister(Register);
1001 OS << "\t.cfi_def_cfa_register ";
1002 EmitRegisterName(Register);
1006 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1007 this->MCStreamer::EmitCFIOffset(Register, Offset);
1012 OS << "\t.cfi_offset ";
1013 EmitRegisterName(Register);
1014 OS << ", " << Offset;
1018 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1019 unsigned Encoding) {
1020 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1025 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1029 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1030 MCStreamer::EmitCFILsda(Sym, Encoding);
1035 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1039 void MCAsmStreamer::EmitCFIRememberState() {
1040 MCStreamer::EmitCFIRememberState();
1045 OS << "\t.cfi_remember_state";
1049 void MCAsmStreamer::EmitCFIRestoreState() {
1050 MCStreamer::EmitCFIRestoreState();
1055 OS << "\t.cfi_restore_state";
1059 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1060 MCStreamer::EmitCFISameValue(Register);
1065 OS << "\t.cfi_same_value ";
1066 EmitRegisterName(Register);
1070 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1071 MCStreamer::EmitCFIRelOffset(Register, Offset);
1076 OS << "\t.cfi_rel_offset ";
1077 EmitRegisterName(Register);
1078 OS << ", " << Offset;
1082 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1083 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1088 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1092 void MCAsmStreamer::EmitCFISignalFrame() {
1093 MCStreamer::EmitCFISignalFrame();
1098 OS << "\t.cfi_signal_frame";
1102 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1103 MCStreamer::EmitCFIUndefined(Register);
1108 OS << "\t.cfi_undefined " << Register;
1112 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1113 MCStreamer::EmitCFIRegister(Register1, Register2);
1118 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1122 void MCAsmStreamer::EmitCFIWindowSave() {
1123 MCStreamer::EmitCFIWindowSave();
1128 OS << "\t.cfi_window_save";
1132 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1133 MCStreamer::EmitWin64EHStartProc(Symbol);
1135 OS << ".seh_proc " << *Symbol;
1139 void MCAsmStreamer::EmitWin64EHEndProc() {
1140 MCStreamer::EmitWin64EHEndProc();
1142 OS << "\t.seh_endproc";
1146 void MCAsmStreamer::EmitWin64EHStartChained() {
1147 MCStreamer::EmitWin64EHStartChained();
1149 OS << "\t.seh_startchained";
1153 void MCAsmStreamer::EmitWin64EHEndChained() {
1154 MCStreamer::EmitWin64EHEndChained();
1156 OS << "\t.seh_endchained";
1160 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1162 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1164 OS << "\t.seh_handler " << *Sym;
1172 static const MCSection *getWin64EHTableSection(StringRef suffix,
1173 MCContext &context) {
1174 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1175 /// this duplicate code in MCWin64EH.cpp.
1177 return context.getObjectFileInfo()->getXDataSection();
1178 return context.getCOFFSection((".xdata"+suffix).str(),
1179 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1180 COFF::IMAGE_SCN_MEM_READ |
1181 COFF::IMAGE_SCN_MEM_WRITE,
1182 SectionKind::getDataRel());
1185 void MCAsmStreamer::EmitWin64EHHandlerData() {
1186 MCStreamer::EmitWin64EHHandlerData();
1188 // Switch sections. Don't call SwitchSection directly, because that will
1189 // cause the section switch to be visible in the emitted assembly.
1190 // We only do this so the section switch that terminates the handler
1191 // data block is visible.
1192 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1193 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1194 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1196 SwitchSectionNoChange(xdataSect);
1198 OS << "\t.seh_handlerdata";
1202 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1203 MCStreamer::EmitWin64EHPushReg(Register);
1205 OS << "\t.seh_pushreg " << Register;
1209 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1210 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1212 OS << "\t.seh_setframe " << Register << ", " << Offset;
1216 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1217 MCStreamer::EmitWin64EHAllocStack(Size);
1219 OS << "\t.seh_stackalloc " << Size;
1223 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1224 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1226 OS << "\t.seh_savereg " << Register << ", " << Offset;
1230 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1231 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1233 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1237 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1238 MCStreamer::EmitWin64EHPushFrame(Code);
1240 OS << "\t.seh_pushframe";
1246 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1247 MCStreamer::EmitWin64EHEndProlog();
1249 OS << "\t.seh_endprologue";
1253 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1254 const MCSubtargetInfo &STI) {
1255 raw_ostream &OS = GetCommentOS();
1256 SmallString<256> Code;
1257 SmallVector<MCFixup, 4> Fixups;
1258 raw_svector_ostream VecOS(Code);
1259 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1262 // If we are showing fixups, create symbolic markers in the encoded
1263 // representation. We do this by making a per-bit map to the fixup item index,
1264 // then trying to display it as nicely as possible.
1265 SmallVector<uint8_t, 64> FixupMap;
1266 FixupMap.resize(Code.size() * 8);
1267 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1270 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1271 MCFixup &F = Fixups[i];
1272 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1273 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1274 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1275 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1276 FixupMap[Index] = 1 + i;
1280 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1281 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1282 OS << "encoding: [";
1283 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1287 // See if all bits are the same map entry.
1288 uint8_t MapEntry = FixupMap[i * 8 + 0];
1289 for (unsigned j = 1; j != 8; ++j) {
1290 if (FixupMap[i * 8 + j] == MapEntry)
1293 MapEntry = uint8_t(~0U);
1297 if (MapEntry != uint8_t(~0U)) {
1298 if (MapEntry == 0) {
1299 OS << format("0x%02x", uint8_t(Code[i]));
1302 // FIXME: Some of the 8 bits require fix up.
1303 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1304 << char('A' + MapEntry - 1) << '\'';
1306 OS << char('A' + MapEntry - 1);
1309 // Otherwise, write out in binary.
1311 for (unsigned j = 8; j--;) {
1312 unsigned Bit = (Code[i] >> j) & 1;
1315 if (MAI->isLittleEndian())
1316 FixupBit = i * 8 + j;
1318 FixupBit = i * 8 + (7-j);
1320 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1321 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1322 OS << char('A' + MapEntry - 1);
1330 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1331 MCFixup &F = Fixups[i];
1332 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1333 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1334 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1338 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1339 assert(getCurrentSection().first &&
1340 "Cannot emit contents before setting section!");
1342 // Show the encoding in a comment if we have a code emitter.
1344 AddEncodingComment(Inst, STI);
1346 // Show the MCInst if enabled.
1348 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1349 GetCommentOS() << "\n";
1352 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1354 InstPrinter->printInst(&Inst, OS, "");
1356 Inst.print(OS, MAI);
1360 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1361 OS << "\t.bundle_align_mode " << AlignPow2;
1365 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1366 OS << "\t.bundle_lock";
1368 OS << " align_to_end";
1372 void MCAsmStreamer::EmitBundleUnlock() {
1373 OS << "\t.bundle_unlock";
1377 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1378 /// the specified string in the output .s file. This capability is
1379 /// indicated by the hasRawTextSupport() predicate.
1380 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1381 if (!String.empty() && String.back() == '\n')
1382 String = String.substr(0, String.size()-1);
1387 void MCAsmStreamer::FinishImpl() {
1388 // If we are generating dwarf for assembly source files dump out the sections.
1389 if (getContext().getGenDwarfForAssembly())
1390 MCGenDwarfInfo::Emit(this, NULL);
1393 EmitFrames(AsmBackend.get(), false);
1396 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1397 formatted_raw_ostream &OS,
1398 bool isVerboseAsm, bool useCFI,
1399 bool useDwarfDirectory, MCInstPrinter *IP,
1400 MCCodeEmitter *CE, MCAsmBackend *MAB,
1402 return new MCAsmStreamer(Context, OS, isVerboseAsm, useCFI, useDwarfDirectory,
1403 IP, CE, MAB, ShowInst);