When promoting an alloca to registers discard any lifetime intrinsics.
[llvm/stm8.git] / lib / MC / MCAsmStreamer.cpp
blobe8b09fcaced82f2386f45c73605b6af2b5dd90d4
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 //===----------------------------------------------------------------------===//
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/Twine.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Target/TargetAsmBackend.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include <cctype>
31 using namespace llvm;
33 namespace {
35 class MCAsmStreamer : public MCStreamer {
36 formatted_raw_ostream &OS;
37 const MCAsmInfo &MAI;
38 OwningPtr<MCInstPrinter> InstPrinter;
39 OwningPtr<MCCodeEmitter> Emitter;
40 OwningPtr<TargetAsmBackend> AsmBackend;
42 SmallString<128> CommentToEmit;
43 raw_svector_ostream CommentStream;
45 unsigned IsVerboseAsm : 1;
46 unsigned ShowInst : 1;
47 unsigned UseLoc : 1;
48 unsigned UseCFI : 1;
50 enum EHSymbolFlags { EHGlobal = 1,
51 EHWeakDefinition = 1 << 1,
52 EHPrivateExtern = 1 << 2 };
53 DenseMap<const MCSymbol*, unsigned> FlagMap;
55 bool needsSet(const MCExpr *Value);
57 void EmitRegisterName(int64_t Register);
59 public:
60 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
61 bool isVerboseAsm, bool useLoc, bool useCFI,
62 MCInstPrinter *printer, MCCodeEmitter *emitter,
63 TargetAsmBackend *asmbackend,
64 bool showInst)
65 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
66 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
67 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
68 ShowInst(showInst), UseLoc(useLoc), UseCFI(useCFI) {
69 if (InstPrinter && IsVerboseAsm)
70 InstPrinter->setCommentStream(CommentStream);
72 ~MCAsmStreamer() {}
74 inline void EmitEOL() {
75 // If we don't have any comments, just emit a \n.
76 if (!IsVerboseAsm) {
77 OS << '\n';
78 return;
80 EmitCommentsAndEOL();
82 void EmitCommentsAndEOL();
84 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
85 /// all.
86 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
88 /// hasRawTextSupport - We support EmitRawText.
89 virtual bool hasRawTextSupport() const { return true; }
91 /// AddComment - Add a comment that can be emitted to the generated .s
92 /// file if applicable as a QoI issue to make the output of the compiler
93 /// more readable. This only affects the MCAsmStreamer, and only when
94 /// verbose assembly output is enabled.
95 virtual void AddComment(const Twine &T);
97 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
98 virtual void AddEncodingComment(const MCInst &Inst);
100 /// GetCommentOS - Return a raw_ostream that comments can be written to.
101 /// Unlike AddComment, you are required to terminate comments with \n if you
102 /// use this method.
103 virtual raw_ostream &GetCommentOS() {
104 if (!IsVerboseAsm)
105 return nulls(); // Discard comments unless in verbose asm mode.
106 return CommentStream;
109 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
110 virtual void AddBlankLine() {
111 EmitEOL();
114 /// @name MCStreamer Interface
115 /// @{
117 virtual void ChangeSection(const MCSection *Section);
119 virtual void InitSections() {
120 // FIXME, this is MachO specific, but the testsuite
121 // expects this.
122 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
123 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
124 0, SectionKind::getText()));
127 virtual void EmitLabel(MCSymbol *Symbol);
128 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
129 MCSymbol *EHSymbol);
130 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
131 virtual void EmitThumbFunc(MCSymbol *Func);
133 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
134 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
135 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
136 const MCSymbol *LastLabel,
137 const MCSymbol *Label);
138 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
139 const MCSymbol *Label);
141 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
143 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
144 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
145 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
146 virtual void EmitCOFFSymbolType(int Type);
147 virtual void EndCOFFSymbolDef();
148 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
149 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
150 unsigned ByteAlignment);
152 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
154 /// @param Symbol - The common symbol to emit.
155 /// @param Size - The size of the common symbol.
156 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
158 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
159 unsigned Size = 0, unsigned ByteAlignment = 0);
161 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
162 uint64_t Size, unsigned ByteAlignment = 0);
164 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
166 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
167 unsigned AddrSpace);
168 virtual void EmitIntValue(uint64_t Value, unsigned Size,
169 unsigned AddrSpace = 0);
171 virtual void EmitULEB128Value(const MCExpr *Value);
173 virtual void EmitSLEB128Value(const MCExpr *Value);
175 virtual void EmitGPRel32Value(const MCExpr *Value);
178 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
179 unsigned AddrSpace);
181 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
182 unsigned ValueSize = 1,
183 unsigned MaxBytesToEmit = 0);
185 virtual void EmitCodeAlignment(unsigned ByteAlignment,
186 unsigned MaxBytesToEmit = 0);
188 virtual void EmitValueToOffset(const MCExpr *Offset,
189 unsigned char Value = 0);
191 virtual void EmitFileDirective(StringRef Filename);
192 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
193 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
194 unsigned Column, unsigned Flags,
195 unsigned Isa, unsigned Discriminator,
196 StringRef FileName);
198 virtual void EmitCFISections(bool EH, bool Debug);
199 virtual void EmitCFIStartProc();
200 virtual void EmitCFIEndProc();
201 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
202 virtual void EmitCFIDefCfaOffset(int64_t Offset);
203 virtual void EmitCFIDefCfaRegister(int64_t Register);
204 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
205 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
206 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
207 virtual void EmitCFIRememberState();
208 virtual void EmitCFIRestoreState();
209 virtual void EmitCFISameValue(int64_t Register);
210 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
211 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
213 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
214 virtual void EmitWin64EHEndProc();
215 virtual void EmitWin64EHStartChained();
216 virtual void EmitWin64EHEndChained();
217 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
218 bool Except);
219 virtual void EmitWin64EHHandlerData();
220 virtual void EmitWin64EHPushReg(unsigned Register);
221 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
222 virtual void EmitWin64EHAllocStack(unsigned Size);
223 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
224 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
225 virtual void EmitWin64EHPushFrame(bool Code);
226 virtual void EmitWin64EHEndProlog();
228 virtual void EmitFnStart();
229 virtual void EmitFnEnd();
230 virtual void EmitCantUnwind();
231 virtual void EmitPersonality(const MCSymbol *Personality);
232 virtual void EmitHandlerData();
233 virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
234 virtual void EmitPad(int64_t Offset);
235 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList, bool);
238 virtual void EmitInstruction(const MCInst &Inst);
240 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
241 /// the specified string in the output .s file. This capability is
242 /// indicated by the hasRawTextSupport() predicate.
243 virtual void EmitRawText(StringRef String);
245 virtual void Finish();
247 /// @}
250 } // end anonymous namespace.
252 /// AddComment - Add a comment that can be emitted to the generated .s
253 /// file if applicable as a QoI issue to make the output of the compiler
254 /// more readable. This only affects the MCAsmStreamer, and only when
255 /// verbose assembly output is enabled.
256 void MCAsmStreamer::AddComment(const Twine &T) {
257 if (!IsVerboseAsm) return;
259 // Make sure that CommentStream is flushed.
260 CommentStream.flush();
262 T.toVector(CommentToEmit);
263 // Each comment goes on its own line.
264 CommentToEmit.push_back('\n');
266 // Tell the comment stream that the vector changed underneath it.
267 CommentStream.resync();
270 void MCAsmStreamer::EmitCommentsAndEOL() {
271 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
272 OS << '\n';
273 return;
276 CommentStream.flush();
277 StringRef Comments = CommentToEmit.str();
279 assert(Comments.back() == '\n' &&
280 "Comment array not newline terminated");
281 do {
282 // Emit a line of comments.
283 OS.PadToColumn(MAI.getCommentColumn());
284 size_t Position = Comments.find('\n');
285 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
287 Comments = Comments.substr(Position+1);
288 } while (!Comments.empty());
290 CommentToEmit.clear();
291 // Tell the comment stream that the vector changed underneath it.
292 CommentStream.resync();
295 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
296 assert(Bytes && "Invalid size!");
297 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
300 void MCAsmStreamer::ChangeSection(const MCSection *Section) {
301 assert(Section && "Cannot switch to a null section!");
302 Section->PrintSwitchToSection(MAI, OS);
305 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
306 MCSymbol *EHSymbol) {
307 if (UseCFI)
308 return;
310 unsigned Flags = FlagMap.lookup(Symbol);
312 if (Flags & EHGlobal)
313 EmitSymbolAttribute(EHSymbol, MCSA_Global);
314 if (Flags & EHWeakDefinition)
315 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
316 if (Flags & EHPrivateExtern)
317 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
320 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
321 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
322 MCStreamer::EmitLabel(Symbol);
324 OS << *Symbol << MAI.getLabelSuffix();
325 EmitEOL();
328 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
329 switch (Flag) {
330 default: assert(0 && "Invalid flag!");
331 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
332 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
333 case MCAF_Code16: OS << "\t.code\t16"; break;
334 case MCAF_Code32: OS << "\t.code\t32"; break;
336 EmitEOL();
339 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
340 // This needs to emit to a temporary string to get properly quoted
341 // MCSymbols when they have spaces in them.
342 OS << "\t.thumb_func";
343 // Only Mach-O hasSubsectionsViaSymbols()
344 if (MAI.hasSubsectionsViaSymbols())
345 OS << '\t' << *Func;
346 EmitEOL();
349 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
350 OS << *Symbol << " = " << *Value;
351 EmitEOL();
353 // FIXME: Lift context changes into super class.
354 Symbol->setVariableValue(Value);
357 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
358 OS << ".weakref " << *Alias << ", " << *Symbol;
359 EmitEOL();
362 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
363 const MCSymbol *LastLabel,
364 const MCSymbol *Label) {
365 EmitDwarfSetLineAddr(LineDelta, Label,
366 getContext().getTargetAsmInfo().getPointerSize());
369 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
370 const MCSymbol *Label) {
371 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
372 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
373 AddrDelta = ForceExpAbs(AddrDelta);
374 EmitValue(AddrDelta, 4);
378 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
379 MCSymbolAttr Attribute) {
380 switch (Attribute) {
381 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
382 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
383 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
384 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
385 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
386 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
387 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
388 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
389 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
390 OS << "\t.type\t" << *Symbol << ','
391 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
392 switch (Attribute) {
393 default: assert(0 && "Unknown ELF .type");
394 case MCSA_ELF_TypeFunction: OS << "function"; break;
395 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
396 case MCSA_ELF_TypeObject: OS << "object"; break;
397 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
398 case MCSA_ELF_TypeCommon: OS << "common"; break;
399 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
400 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
402 EmitEOL();
403 return;
404 case MCSA_Global: // .globl/.global
405 OS << MAI.getGlobalDirective();
406 FlagMap[Symbol] |= EHGlobal;
407 break;
408 case MCSA_Hidden: OS << "\t.hidden\t"; break;
409 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
410 case MCSA_Internal: OS << "\t.internal\t"; break;
411 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
412 case MCSA_Local: OS << "\t.local\t"; break;
413 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
414 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
415 case MCSA_PrivateExtern:
416 OS << "\t.private_extern\t";
417 FlagMap[Symbol] |= EHPrivateExtern;
418 break;
419 case MCSA_Protected: OS << "\t.protected\t"; break;
420 case MCSA_Reference: OS << "\t.reference\t"; break;
421 case MCSA_Weak: OS << "\t.weak\t"; break;
422 case MCSA_WeakDefinition:
423 OS << "\t.weak_definition\t";
424 FlagMap[Symbol] |= EHWeakDefinition;
425 break;
426 // .weak_reference
427 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
428 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
431 OS << *Symbol;
432 EmitEOL();
435 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
436 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
437 EmitEOL();
440 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
441 OS << "\t.def\t " << *Symbol << ';';
442 EmitEOL();
445 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
446 OS << "\t.scl\t" << StorageClass << ';';
447 EmitEOL();
450 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
451 OS << "\t.type\t" << Type << ';';
452 EmitEOL();
455 void MCAsmStreamer::EndCOFFSymbolDef() {
456 OS << "\t.endef";
457 EmitEOL();
460 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
461 assert(MAI.hasDotTypeDotSizeDirective());
462 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
465 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
466 unsigned ByteAlignment) {
467 OS << "\t.comm\t" << *Symbol << ',' << Size;
468 if (ByteAlignment != 0) {
469 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
470 OS << ',' << ByteAlignment;
471 else
472 OS << ',' << Log2_32(ByteAlignment);
474 EmitEOL();
477 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
479 /// @param Symbol - The common symbol to emit.
480 /// @param Size - The size of the common symbol.
481 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
482 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
483 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
484 EmitEOL();
487 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
488 unsigned Size, unsigned ByteAlignment) {
489 // Note: a .zerofill directive does not switch sections.
490 OS << ".zerofill ";
492 // This is a mach-o specific directive.
493 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
494 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
496 if (Symbol != NULL) {
497 OS << ',' << *Symbol << ',' << Size;
498 if (ByteAlignment != 0)
499 OS << ',' << Log2_32(ByteAlignment);
501 EmitEOL();
504 // .tbss sym, size, align
505 // This depends that the symbol has already been mangled from the original,
506 // e.g. _a.
507 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
508 uint64_t Size, unsigned ByteAlignment) {
509 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
510 // Instead of using the Section we'll just use the shortcut.
511 // This is a mach-o specific directive and section.
512 OS << ".tbss " << *Symbol << ", " << Size;
514 // Output align if we have it. We default to 1 so don't bother printing
515 // that.
516 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
518 EmitEOL();
521 static inline char toOctal(int X) { return (X&7)+'0'; }
523 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
524 OS << '"';
526 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
527 unsigned char C = Data[i];
528 if (C == '"' || C == '\\') {
529 OS << '\\' << (char)C;
530 continue;
533 if (isprint((unsigned char)C)) {
534 OS << (char)C;
535 continue;
538 switch (C) {
539 case '\b': OS << "\\b"; break;
540 case '\f': OS << "\\f"; break;
541 case '\n': OS << "\\n"; break;
542 case '\r': OS << "\\r"; break;
543 case '\t': OS << "\\t"; break;
544 default:
545 OS << '\\';
546 OS << toOctal(C >> 6);
547 OS << toOctal(C >> 3);
548 OS << toOctal(C >> 0);
549 break;
553 OS << '"';
557 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
558 assert(getCurrentSection() && "Cannot emit contents before setting section!");
559 if (Data.empty()) return;
561 if (Data.size() == 1) {
562 OS << MAI.getData8bitsDirective(AddrSpace);
563 OS << (unsigned)(unsigned char)Data[0];
564 EmitEOL();
565 return;
568 // If the data ends with 0 and the target supports .asciz, use it, otherwise
569 // use .ascii
570 if (MAI.getAscizDirective() && Data.back() == 0) {
571 OS << MAI.getAscizDirective();
572 Data = Data.substr(0, Data.size()-1);
573 } else {
574 OS << MAI.getAsciiDirective();
577 OS << ' ';
578 PrintQuotedString(Data, OS);
579 EmitEOL();
582 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
583 unsigned AddrSpace) {
584 EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
587 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
588 unsigned AddrSpace) {
589 assert(getCurrentSection() && "Cannot emit contents before setting section!");
590 const char *Directive = 0;
591 switch (Size) {
592 default: break;
593 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
594 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
595 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
596 case 8:
597 Directive = MAI.getData64bitsDirective(AddrSpace);
598 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
599 if (Directive) break;
600 int64_t IntValue;
601 if (!Value->EvaluateAsAbsolute(IntValue))
602 report_fatal_error("Don't know how to emit this value.");
603 if (getContext().getTargetAsmInfo().isLittleEndian()) {
604 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
605 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
606 } else {
607 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
608 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
610 return;
613 assert(Directive && "Invalid size for machine code value!");
614 OS << Directive << *Value;
615 EmitEOL();
618 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
619 int64_t IntValue;
620 if (Value->EvaluateAsAbsolute(IntValue)) {
621 EmitULEB128IntValue(IntValue);
622 return;
624 assert(MAI.hasLEB128() && "Cannot print a .uleb");
625 OS << ".uleb128 " << *Value;
626 EmitEOL();
629 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
630 int64_t IntValue;
631 if (Value->EvaluateAsAbsolute(IntValue)) {
632 EmitSLEB128IntValue(IntValue);
633 return;
635 assert(MAI.hasLEB128() && "Cannot print a .sleb");
636 OS << ".sleb128 " << *Value;
637 EmitEOL();
640 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
641 assert(MAI.getGPRel32Directive() != 0);
642 OS << MAI.getGPRel32Directive() << *Value;
643 EmitEOL();
647 /// EmitFill - Emit NumBytes bytes worth of the value specified by
648 /// FillValue. This implements directives such as '.space'.
649 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
650 unsigned AddrSpace) {
651 if (NumBytes == 0) return;
653 if (AddrSpace == 0)
654 if (const char *ZeroDirective = MAI.getZeroDirective()) {
655 OS << ZeroDirective << NumBytes;
656 if (FillValue != 0)
657 OS << ',' << (int)FillValue;
658 EmitEOL();
659 return;
662 // Emit a byte at a time.
663 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
666 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
667 unsigned ValueSize,
668 unsigned MaxBytesToEmit) {
669 // Some assemblers don't support non-power of two alignments, so we always
670 // emit alignments as a power of two if possible.
671 if (isPowerOf2_32(ByteAlignment)) {
672 switch (ValueSize) {
673 default: llvm_unreachable("Invalid size for machine code value!");
674 case 1: OS << MAI.getAlignDirective(); break;
675 // FIXME: use MAI for this!
676 case 2: OS << ".p2alignw "; break;
677 case 4: OS << ".p2alignl "; break;
678 case 8: llvm_unreachable("Unsupported alignment size!");
681 if (MAI.getAlignmentIsInBytes())
682 OS << ByteAlignment;
683 else
684 OS << Log2_32(ByteAlignment);
686 if (Value || MaxBytesToEmit) {
687 OS << ", 0x";
688 OS.write_hex(truncateToSize(Value, ValueSize));
690 if (MaxBytesToEmit)
691 OS << ", " << MaxBytesToEmit;
693 EmitEOL();
694 return;
697 // Non-power of two alignment. This is not widely supported by assemblers.
698 // FIXME: Parameterize this based on MAI.
699 switch (ValueSize) {
700 default: llvm_unreachable("Invalid size for machine code value!");
701 case 1: OS << ".balign"; break;
702 case 2: OS << ".balignw"; break;
703 case 4: OS << ".balignl"; break;
704 case 8: llvm_unreachable("Unsupported alignment size!");
707 OS << ' ' << ByteAlignment;
708 OS << ", " << truncateToSize(Value, ValueSize);
709 if (MaxBytesToEmit)
710 OS << ", " << MaxBytesToEmit;
711 EmitEOL();
714 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
715 unsigned MaxBytesToEmit) {
716 // Emit with a text fill value.
717 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
718 1, MaxBytesToEmit);
721 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
722 unsigned char Value) {
723 // FIXME: Verify that Offset is associated with the current section.
724 OS << ".org " << *Offset << ", " << (unsigned) Value;
725 EmitEOL();
729 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
730 assert(MAI.hasSingleParameterDotFile());
731 OS << "\t.file\t";
732 PrintQuotedString(Filename, OS);
733 EmitEOL();
736 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
737 if (UseLoc) {
738 OS << "\t.file\t" << FileNo << ' ';
739 PrintQuotedString(Filename, OS);
740 EmitEOL();
742 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
745 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
746 unsigned Column, unsigned Flags,
747 unsigned Isa,
748 unsigned Discriminator,
749 StringRef FileName) {
750 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
751 Isa, Discriminator, FileName);
752 if (!UseLoc)
753 return;
755 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
756 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
757 OS << " basic_block";
758 if (Flags & DWARF2_FLAG_PROLOGUE_END)
759 OS << " prologue_end";
760 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
761 OS << " epilogue_begin";
763 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
764 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
765 OS << " is_stmt ";
767 if (Flags & DWARF2_FLAG_IS_STMT)
768 OS << "1";
769 else
770 OS << "0";
773 if (Isa)
774 OS << "isa " << Isa;
775 if (Discriminator)
776 OS << "discriminator " << Discriminator;
778 if (IsVerboseAsm) {
779 OS.PadToColumn(MAI.getCommentColumn());
780 OS << MAI.getCommentString() << ' ' << FileName << ':'
781 << Line << ':' << Column;
783 EmitEOL();
786 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
787 MCStreamer::EmitCFISections(EH, Debug);
789 if (!UseCFI)
790 return;
792 OS << "\t.cfi_sections ";
793 if (EH) {
794 OS << ".eh_frame";
795 if (Debug)
796 OS << ", .debug_frame";
797 } else if (Debug) {
798 OS << ".debug_frame";
801 EmitEOL();
804 void MCAsmStreamer::EmitCFIStartProc() {
805 MCStreamer::EmitCFIStartProc();
807 if (!UseCFI)
808 return;
810 OS << "\t.cfi_startproc";
811 EmitEOL();
814 void MCAsmStreamer::EmitCFIEndProc() {
815 MCStreamer::EmitCFIEndProc();
817 if (!UseCFI)
818 return;
820 OS << "\t.cfi_endproc";
821 EmitEOL();
824 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
825 if (InstPrinter) {
826 const TargetAsmInfo &asmInfo = getContext().getTargetAsmInfo();
827 unsigned LLVMRegister = asmInfo.getLLVMRegNum(Register, true);
828 InstPrinter->printRegName(OS, LLVMRegister);
829 } else {
830 OS << Register;
834 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
835 MCStreamer::EmitCFIDefCfa(Register, Offset);
837 if (!UseCFI)
838 return;
840 OS << "\t.cfi_def_cfa ";
841 EmitRegisterName(Register);
842 OS << ", " << Offset;
843 EmitEOL();
846 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
847 MCStreamer::EmitCFIDefCfaOffset(Offset);
849 if (!UseCFI)
850 return;
852 OS << "\t.cfi_def_cfa_offset " << Offset;
853 EmitEOL();
856 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
857 MCStreamer::EmitCFIDefCfaRegister(Register);
859 if (!UseCFI)
860 return;
862 OS << "\t.cfi_def_cfa_register ";
863 EmitRegisterName(Register);
864 EmitEOL();
867 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
868 this->MCStreamer::EmitCFIOffset(Register, Offset);
870 if (!UseCFI)
871 return;
873 OS << "\t.cfi_offset ";
874 EmitRegisterName(Register);
875 OS << ", " << Offset;
876 EmitEOL();
879 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
880 unsigned Encoding) {
881 MCStreamer::EmitCFIPersonality(Sym, Encoding);
883 if (!UseCFI)
884 return;
886 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
887 EmitEOL();
890 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
891 MCStreamer::EmitCFILsda(Sym, Encoding);
893 if (!UseCFI)
894 return;
896 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
897 EmitEOL();
900 void MCAsmStreamer::EmitCFIRememberState() {
901 MCStreamer::EmitCFIRememberState();
903 if (!UseCFI)
904 return;
906 OS << "\t.cfi_remember_state";
907 EmitEOL();
910 void MCAsmStreamer::EmitCFIRestoreState() {
911 MCStreamer::EmitCFIRestoreState();
913 if (!UseCFI)
914 return;
916 OS << "\t.cfi_restore_state";
917 EmitEOL();
920 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
921 MCStreamer::EmitCFISameValue(Register);
923 if (!UseCFI)
924 return;
926 OS << "\t.cfi_same_value ";
927 EmitRegisterName(Register);
928 EmitEOL();
931 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
932 MCStreamer::EmitCFIRelOffset(Register, Offset);
934 if (!UseCFI)
935 return;
937 OS << "\t.cfi_rel_offset ";
938 EmitRegisterName(Register);
939 OS << ", " << Offset;
940 EmitEOL();
943 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
944 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
946 if (!UseCFI)
947 return;
949 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
950 EmitEOL();
953 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
954 MCStreamer::EmitWin64EHStartProc(Symbol);
956 OS << ".seh_proc " << *Symbol;
957 EmitEOL();
960 void MCAsmStreamer::EmitWin64EHEndProc() {
961 MCStreamer::EmitWin64EHEndProc();
963 OS << "\t.seh_endproc";
964 EmitEOL();
967 void MCAsmStreamer::EmitWin64EHStartChained() {
968 MCStreamer::EmitWin64EHStartChained();
970 OS << "\t.seh_startchained";
971 EmitEOL();
974 void MCAsmStreamer::EmitWin64EHEndChained() {
975 MCStreamer::EmitWin64EHEndChained();
977 OS << "\t.seh_endchained";
978 EmitEOL();
981 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
982 bool Except) {
983 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
985 OS << "\t.seh_handler " << *Sym;
986 if (Unwind)
987 OS << ", @unwind";
988 if (Except)
989 OS << ", @except";
990 EmitEOL();
993 void MCAsmStreamer::EmitWin64EHHandlerData() {
994 MCStreamer::EmitWin64EHHandlerData();
996 // Switch sections. Don't call SwitchSection directly, because that will
997 // cause the section switch to be visible in the emitted assembly.
998 // We only do this so the section switch that terminates the handler
999 // data block is visible.
1000 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1001 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1002 const MCSection *xdataSect =
1003 getContext().getTargetAsmInfo().getWin64EHTableSection(suffix);
1004 if (xdataSect)
1005 SwitchSectionNoChange(xdataSect);
1007 OS << "\t.seh_handlerdata";
1008 EmitEOL();
1011 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1012 MCStreamer::EmitWin64EHPushReg(Register);
1014 OS << "\t.seh_pushreg " << Register;
1015 EmitEOL();
1018 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1019 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1021 OS << "\t.seh_setframe " << Register << ", " << Offset;
1022 EmitEOL();
1025 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1026 MCStreamer::EmitWin64EHAllocStack(Size);
1028 OS << "\t.seh_stackalloc " << Size;
1029 EmitEOL();
1032 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1033 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1035 OS << "\t.seh_savereg " << Register << ", " << Offset;
1036 EmitEOL();
1039 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1040 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1042 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1043 EmitEOL();
1046 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1047 MCStreamer::EmitWin64EHPushFrame(Code);
1049 OS << "\t.seh_pushframe";
1050 if (Code)
1051 OS << " @code";
1052 EmitEOL();
1055 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1056 MCStreamer::EmitWin64EHEndProlog();
1058 OS << "\t.seh_endprologue";
1059 EmitEOL();
1062 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
1063 raw_ostream &OS = GetCommentOS();
1064 SmallString<256> Code;
1065 SmallVector<MCFixup, 4> Fixups;
1066 raw_svector_ostream VecOS(Code);
1067 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
1068 VecOS.flush();
1070 // If we are showing fixups, create symbolic markers in the encoded
1071 // representation. We do this by making a per-bit map to the fixup item index,
1072 // then trying to display it as nicely as possible.
1073 SmallVector<uint8_t, 64> FixupMap;
1074 FixupMap.resize(Code.size() * 8);
1075 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1076 FixupMap[i] = 0;
1078 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1079 MCFixup &F = Fixups[i];
1080 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1081 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1082 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1083 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1084 FixupMap[Index] = 1 + i;
1088 // FIXME: Node the fixup comments for Thumb2 are completely bogus since the
1089 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1090 OS << "encoding: [";
1091 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1092 if (i)
1093 OS << ',';
1095 // See if all bits are the same map entry.
1096 uint8_t MapEntry = FixupMap[i * 8 + 0];
1097 for (unsigned j = 1; j != 8; ++j) {
1098 if (FixupMap[i * 8 + j] == MapEntry)
1099 continue;
1101 MapEntry = uint8_t(~0U);
1102 break;
1105 if (MapEntry != uint8_t(~0U)) {
1106 if (MapEntry == 0) {
1107 OS << format("0x%02x", uint8_t(Code[i]));
1108 } else {
1109 if (Code[i]) {
1110 // FIXME: Some of the 8 bits require fix up.
1111 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1112 << char('A' + MapEntry - 1) << '\'';
1113 } else
1114 OS << char('A' + MapEntry - 1);
1116 } else {
1117 // Otherwise, write out in binary.
1118 OS << "0b";
1119 for (unsigned j = 8; j--;) {
1120 unsigned Bit = (Code[i] >> j) & 1;
1122 unsigned FixupBit;
1123 if (getContext().getTargetAsmInfo().isLittleEndian())
1124 FixupBit = i * 8 + j;
1125 else
1126 FixupBit = i * 8 + (7-j);
1128 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1129 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1130 OS << char('A' + MapEntry - 1);
1131 } else
1132 OS << Bit;
1136 OS << "]\n";
1138 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1139 MCFixup &F = Fixups[i];
1140 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1141 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1142 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1146 void MCAsmStreamer::EmitFnStart() {
1147 OS << "\t.fnstart";
1148 EmitEOL();
1151 void MCAsmStreamer::EmitFnEnd() {
1152 OS << "\t.fnend";
1153 EmitEOL();
1156 void MCAsmStreamer::EmitCantUnwind() {
1157 OS << "\t.cantunwind";
1158 EmitEOL();
1161 void MCAsmStreamer::EmitHandlerData() {
1162 OS << "\t.handlerdata";
1163 EmitEOL();
1166 void MCAsmStreamer::EmitPersonality(const MCSymbol *Personality) {
1167 OS << "\t.personality " << Personality->getName();
1168 EmitEOL();
1171 void MCAsmStreamer::EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset) {
1172 OS << "\t.setfp\t";
1173 InstPrinter->printRegName(OS, FpReg);
1174 OS << ", ";
1175 InstPrinter->printRegName(OS, SpReg);
1176 if (Offset)
1177 OS << ", #" << Offset;
1178 EmitEOL();
1181 void MCAsmStreamer::EmitPad(int64_t Offset) {
1182 OS << "\t.pad\t#" << Offset;
1183 EmitEOL();
1186 void MCAsmStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
1187 bool isVector) {
1188 assert(RegList.size() && "RegList should not be empty");
1189 if (isVector)
1190 OS << "\t.vsave\t{";
1191 else
1192 OS << "\t.save\t{";
1194 InstPrinter->printRegName(OS, RegList[0]);
1196 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
1197 OS << ", ";
1198 InstPrinter->printRegName(OS, RegList[i]);
1201 OS << "}";
1202 EmitEOL();
1205 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
1206 assert(getCurrentSection() && "Cannot emit contents before setting section!");
1208 // Show the encoding in a comment if we have a code emitter.
1209 if (Emitter)
1210 AddEncodingComment(Inst);
1212 // Show the MCInst if enabled.
1213 if (ShowInst) {
1214 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
1215 GetCommentOS() << "\n";
1218 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1219 if (InstPrinter)
1220 InstPrinter->printInst(&Inst, OS);
1221 else
1222 Inst.print(OS, &MAI);
1223 EmitEOL();
1226 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1227 /// the specified string in the output .s file. This capability is
1228 /// indicated by the hasRawTextSupport() predicate.
1229 void MCAsmStreamer::EmitRawText(StringRef String) {
1230 if (!String.empty() && String.back() == '\n')
1231 String = String.substr(0, String.size()-1);
1232 OS << String;
1233 EmitEOL();
1236 void MCAsmStreamer::Finish() {
1237 // Dump out the dwarf file & directory tables and line tables.
1238 if (getContext().hasDwarfFiles() && !UseLoc)
1239 MCDwarfFileTable::Emit(this);
1241 if (!UseCFI)
1242 EmitFrames(false);
1245 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1246 formatted_raw_ostream &OS,
1247 bool isVerboseAsm, bool useLoc,
1248 bool useCFI,
1249 MCInstPrinter *IP, MCCodeEmitter *CE,
1250 TargetAsmBackend *TAB, bool ShowInst) {
1251 return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc, useCFI,
1252 IP, CE, TAB, ShowInst);