1 //===- lib/MC/ARMELFStreamer.cpp - ELF Object Output for ARM --------------===//
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 // This file assembles .s files and emits ARM ELF .o object files. Different
11 // from generic ELF streamer in emitting mapping symbols ($a, $t and $d) to
12 // delimit regions of data and code.
14 //===----------------------------------------------------------------------===//
16 #include "ARMArchName.h"
17 #include "ARMFPUName.h"
18 #include "ARMArchExtName.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMUnwindOpAsm.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/MC/MCAsmBackend.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCAssembler.h"
26 #include "llvm/MC/MCCodeEmitter.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCELF.h"
29 #include "llvm/MC/MCELFStreamer.h"
30 #include "llvm/MC/MCELFSymbolFlags.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstPrinter.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCObjectStreamer.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/MC/MCSection.h"
38 #include "llvm/MC/MCSectionELF.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/MC/MCValue.h"
42 #include "llvm/Support/ARMBuildAttributes.h"
43 #include "llvm/Support/ARMEHABI.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/FormattedStream.h"
47 #include "llvm/Support/LEB128.h"
48 #include "llvm/Support/raw_ostream.h"
53 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
54 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
55 "Invalid personality index");
56 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
59 static const char *GetFPUName(unsigned ID) {
62 llvm_unreachable("Unknown FPU kind");
64 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
65 #include "ARMFPUName.def"
70 static const char *GetArchName(unsigned ID) {
73 llvm_unreachable("Unknown ARCH kind");
75 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
76 case ARM::ID: return NAME;
77 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
78 #include "ARMArchName.def"
83 static const char *GetArchDefaultCPUName(unsigned ID) {
86 llvm_unreachable("Unknown ARCH kind");
88 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
89 case ARM::ID: return DEFAULT_CPU_NAME;
90 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
91 #include "ARMArchName.def"
96 static unsigned GetArchDefaultCPUArch(unsigned ID) {
99 llvm_unreachable("Unknown ARCH kind");
101 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
102 case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
103 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
104 #include "ARMArchName.def"
109 static const char *GetArchExtName(unsigned ID) {
112 llvm_unreachable("Unknown ARCH Extension kind");
114 #define ARM_ARCHEXT_NAME(NAME, ID) \
117 #include "ARMArchExtName.def"
124 class ARMELFStreamer;
126 class ARMTargetAsmStreamer : public ARMTargetStreamer {
127 formatted_raw_ostream &OS;
128 MCInstPrinter &InstPrinter;
131 void emitFnStart() override;
132 void emitFnEnd() override;
133 void emitCantUnwind() override;
134 void emitPersonality(const MCSymbol *Personality) override;
135 void emitPersonalityIndex(unsigned Index) override;
136 void emitHandlerData() override;
137 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
138 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
139 void emitPad(int64_t Offset) override;
140 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
141 bool isVector) override;
142 void emitUnwindRaw(int64_t Offset,
143 const SmallVectorImpl<uint8_t> &Opcodes) override;
145 void switchVendor(StringRef Vendor) override;
146 void emitAttribute(unsigned Attribute, unsigned Value) override;
147 void emitTextAttribute(unsigned Attribute, StringRef String) override;
148 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
149 StringRef StrinValue) override;
150 void emitArch(unsigned Arch) override;
151 void emitArchExtension(unsigned ArchExt) override;
152 void emitObjectArch(unsigned Arch) override;
153 void emitFPU(unsigned FPU) override;
154 void emitInst(uint32_t Inst, char Suffix = '\0') override;
155 void finishAttributeSection() override;
157 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
158 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
161 ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
162 MCInstPrinter &InstPrinter, bool VerboseAsm);
165 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
166 formatted_raw_ostream &OS,
167 MCInstPrinter &InstPrinter,
169 : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
170 IsVerboseAsm(VerboseAsm) {}
171 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
172 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
173 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
174 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
175 OS << "\t.personality " << Personality->getName() << '\n';
177 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
178 OS << "\t.personalityindex " << Index << '\n';
180 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
181 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
184 InstPrinter.printRegName(OS, FpReg);
186 InstPrinter.printRegName(OS, SpReg);
188 OS << ", #" << Offset;
191 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
192 assert((Reg != ARM::SP && Reg != ARM::PC) &&
193 "the operand of .movsp cannot be either sp or pc");
196 InstPrinter.printRegName(OS, Reg);
198 OS << ", #" << Offset;
201 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
202 OS << "\t.pad\t#" << Offset << '\n';
204 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
206 assert(RegList.size() && "RegList should not be empty");
212 InstPrinter.printRegName(OS, RegList[0]);
214 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
216 InstPrinter.printRegName(OS, RegList[i]);
221 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
223 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
224 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
226 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
228 OS << "\t@ " << Name;
232 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
235 case ARMBuildAttrs::CPU_name:
236 OS << "\t.cpu\t" << String.lower();
239 OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
241 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
243 OS << "\t@ " << Name;
249 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
251 StringRef StringValue) {
253 default: llvm_unreachable("unsupported multi-value attribute in asm mode");
254 case ARMBuildAttrs::compatibility:
255 OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
256 if (!StringValue.empty())
257 OS << ", \"" << StringValue << "\"";
259 OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
264 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
265 OS << "\t.arch\t" << GetArchName(Arch) << "\n";
267 void ARMTargetAsmStreamer::emitArchExtension(unsigned ArchExt) {
268 OS << "\t.arch_extension\t" << GetArchExtName(ArchExt) << "\n";
270 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
271 OS << "\t.object_arch\t" << GetArchName(Arch) << '\n';
273 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
274 OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
276 void ARMTargetAsmStreamer::finishAttributeSection() {
279 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
280 OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
283 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
284 OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
287 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
291 OS << "\t0x" << utohexstr(Inst) << "\n";
294 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
295 const SmallVectorImpl<uint8_t> &Opcodes) {
296 OS << "\t.unwind_raw " << Offset;
297 for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
300 OS << ", 0x" << utohexstr(*OCI);
304 class ARMTargetELFStreamer : public ARMTargetStreamer {
306 // This structure holds all attributes, accounting for
307 // their string/numeric value, so we can later emmit them
308 // in declaration order, keeping all in the same vector
309 struct AttributeItem {
314 NumericAndTextAttributes
318 StringRef StringValue;
320 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
321 // The conformance tag must be emitted first when serialised
322 // into an object file. Specifically, the addenda to the ARM ABI
323 // states that (2.3.7.4):
325 // "To simplify recognition by consumers in the common case of
326 // claiming conformity for the whole file, this tag should be
327 // emitted first in a file-scope sub-subsection of the first
328 // public subsection of the attributes section."
330 // So it is special-cased in this comparison predicate when the
331 // attributes are sorted in finishAttributeSection().
332 return (RHS.Tag != ARMBuildAttrs::conformance) &&
333 ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
337 StringRef CurrentVendor;
340 unsigned EmittedArch;
341 SmallVector<AttributeItem, 64> Contents;
343 const MCSection *AttributeSection;
345 AttributeItem *getAttributeItem(unsigned Attribute) {
346 for (size_t i = 0; i < Contents.size(); ++i)
347 if (Contents[i].Tag == Attribute)
352 void setAttributeItem(unsigned Attribute, unsigned Value,
353 bool OverwriteExisting) {
354 // Look for existing attribute item
355 if (AttributeItem *Item = getAttributeItem(Attribute)) {
356 if (!OverwriteExisting)
358 Item->Type = AttributeItem::NumericAttribute;
359 Item->IntValue = Value;
363 // Create new attribute item
364 AttributeItem Item = {
365 AttributeItem::NumericAttribute,
370 Contents.push_back(Item);
373 void setAttributeItem(unsigned Attribute, StringRef Value,
374 bool OverwriteExisting) {
375 // Look for existing attribute item
376 if (AttributeItem *Item = getAttributeItem(Attribute)) {
377 if (!OverwriteExisting)
379 Item->Type = AttributeItem::TextAttribute;
380 Item->StringValue = Value;
384 // Create new attribute item
385 AttributeItem Item = {
386 AttributeItem::TextAttribute,
391 Contents.push_back(Item);
394 void setAttributeItems(unsigned Attribute, unsigned IntValue,
395 StringRef StringValue, bool OverwriteExisting) {
396 // Look for existing attribute item
397 if (AttributeItem *Item = getAttributeItem(Attribute)) {
398 if (!OverwriteExisting)
400 Item->Type = AttributeItem::NumericAndTextAttributes;
401 Item->IntValue = IntValue;
402 Item->StringValue = StringValue;
406 // Create new attribute item
407 AttributeItem Item = {
408 AttributeItem::NumericAndTextAttributes,
413 Contents.push_back(Item);
416 void emitArchDefaultAttributes();
417 void emitFPUDefaultAttributes();
419 ARMELFStreamer &getStreamer();
421 void emitFnStart() override;
422 void emitFnEnd() override;
423 void emitCantUnwind() override;
424 void emitPersonality(const MCSymbol *Personality) override;
425 void emitPersonalityIndex(unsigned Index) override;
426 void emitHandlerData() override;
427 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
428 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
429 void emitPad(int64_t Offset) override;
430 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
431 bool isVector) override;
432 void emitUnwindRaw(int64_t Offset,
433 const SmallVectorImpl<uint8_t> &Opcodes) override;
435 void switchVendor(StringRef Vendor) override;
436 void emitAttribute(unsigned Attribute, unsigned Value) override;
437 void emitTextAttribute(unsigned Attribute, StringRef String) override;
438 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
439 StringRef StringValue) override;
440 void emitArch(unsigned Arch) override;
441 void emitObjectArch(unsigned Arch) override;
442 void emitFPU(unsigned FPU) override;
443 void emitInst(uint32_t Inst, char Suffix = '\0') override;
444 void finishAttributeSection() override;
445 void emitLabel(MCSymbol *Symbol) override;
447 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
448 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
450 size_t calculateContentSize() const;
453 ARMTargetELFStreamer(MCStreamer &S)
454 : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
455 Arch(ARM::INVALID_ARCH), EmittedArch(ARM::INVALID_ARCH),
456 AttributeSection(nullptr) {}
459 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
460 /// the appropriate points in the object files. These symbols are defined in the
461 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
463 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
464 /// region of ARM code, Thumb code or data in a section. In practice, this
465 /// emission does not rely on explicit assembler directives but on inherent
466 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
467 /// r0, r0, r0" an instruction).
469 /// As a result this system is orthogonal to the DataRegion infrastructure used
470 /// by MachO. Beware!
471 class ARMELFStreamer : public MCELFStreamer {
473 friend class ARMTargetELFStreamer;
475 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_ostream &OS,
476 MCCodeEmitter *Emitter, bool IsThumb)
477 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
478 MappingSymbolCounter(0), LastEMS(EMS_None) {
484 void FinishImpl() override;
486 // ARM exception handling directives
489 void emitCantUnwind();
490 void emitPersonality(const MCSymbol *Per);
491 void emitPersonalityIndex(unsigned index);
492 void emitHandlerData();
493 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
494 void emitMovSP(unsigned Reg, int64_t Offset = 0);
495 void emitPad(int64_t Offset);
496 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
497 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
499 void ChangeSection(const MCSection *Section,
500 const MCExpr *Subsection) override {
501 // We have to keep track of the mapping symbol state of any sections we
502 // use. Each one should start off as EMS_None, which is provided as the
503 // default constructor by DenseMap::lookup.
504 LastMappingSymbols[getPreviousSection().first] = LastEMS;
505 LastEMS = LastMappingSymbols.lookup(Section);
507 MCELFStreamer::ChangeSection(Section, Subsection);
510 /// This function is the one used to emit instruction data into the ELF
511 /// streamer. We override it to add the appropriate mapping symbol if
513 void EmitInstruction(const MCInst& Inst,
514 const MCSubtargetInfo &STI) override {
516 EmitThumbMappingSymbol();
518 EmitARMMappingSymbol();
520 MCELFStreamer::EmitInstruction(Inst, STI);
523 void emitInst(uint32_t Inst, char Suffix) {
526 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
533 EmitARMMappingSymbol();
534 for (unsigned II = 0, IE = Size; II != IE; II++) {
535 const unsigned I = LittleEndian ? (Size - II - 1) : II;
536 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
542 Size = (Suffix == 'n' ? 2 : 4);
545 EmitThumbMappingSymbol();
546 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
547 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
548 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
549 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
550 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
555 llvm_unreachable("Invalid Suffix");
558 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
561 /// This is one of the functions used to emit data into an ELF section, so the
562 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
564 void EmitBytes(StringRef Data) override {
565 EmitDataMappingSymbol();
566 MCELFStreamer::EmitBytes(Data);
569 /// This is one of the functions used to emit data into an ELF section, so the
570 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
572 void EmitValueImpl(const MCExpr *Value, unsigned Size,
573 const SMLoc &Loc) override {
574 if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value))
575 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4))
576 getContext().FatalError(Loc, "relocated expression must be 32-bit");
578 EmitDataMappingSymbol();
579 MCELFStreamer::EmitValueImpl(Value, Size);
582 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
583 MCELFStreamer::EmitAssemblerFlag(Flag);
586 case MCAF_SyntaxUnified:
587 return; // no-op here.
590 return; // Change to Thumb mode
593 return; // Change to ARM mode
596 case MCAF_SubsectionsViaSymbols:
602 enum ElfMappingSymbol {
609 void EmitDataMappingSymbol() {
610 if (LastEMS == EMS_Data) return;
611 EmitMappingSymbol("$d");
615 void EmitThumbMappingSymbol() {
616 if (LastEMS == EMS_Thumb) return;
617 EmitMappingSymbol("$t");
621 void EmitARMMappingSymbol() {
622 if (LastEMS == EMS_ARM) return;
623 EmitMappingSymbol("$a");
627 void EmitMappingSymbol(StringRef Name) {
628 MCSymbol *Start = getContext().CreateTempSymbol();
632 getContext().GetOrCreateSymbol(Name + "." +
633 Twine(MappingSymbolCounter++));
635 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
636 MCELF::SetType(SD, ELF::STT_NOTYPE);
637 MCELF::SetBinding(SD, ELF::STB_LOCAL);
638 SD.setExternal(false);
639 AssignSection(Symbol, getCurrentSection().first);
641 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
642 Symbol->setVariableValue(Value);
645 void EmitThumbFunc(MCSymbol *Func) override {
646 getAssembler().setIsThumbFunc(Func);
647 EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
650 // Helper functions for ARM exception handling directives
653 void EmitPersonalityFixup(StringRef Name);
654 void FlushPendingOffset();
655 void FlushUnwindOpcodes(bool NoHandlerData);
657 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
658 SectionKind Kind, const MCSymbol &Fn);
659 void SwitchToExTabSection(const MCSymbol &FnStart);
660 void SwitchToExIdxSection(const MCSymbol &FnStart);
662 void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
665 int64_t MappingSymbolCounter;
667 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
668 ElfMappingSymbol LastEMS;
670 // ARM Exception Handling Frame Information
673 const MCSymbol *Personality;
674 unsigned PersonalityIndex;
675 unsigned FPReg; // Frame pointer register
676 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
677 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
678 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
681 SmallVector<uint8_t, 64> Opcodes;
682 UnwindOpcodeAssembler UnwindOpAsm;
684 } // end anonymous namespace
686 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
687 return static_cast<ARMELFStreamer &>(Streamer);
690 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
691 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
692 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
693 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
694 getStreamer().emitPersonality(Personality);
696 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
697 getStreamer().emitPersonalityIndex(Index);
699 void ARMTargetELFStreamer::emitHandlerData() {
700 getStreamer().emitHandlerData();
702 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
704 getStreamer().emitSetFP(FpReg, SpReg, Offset);
706 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
707 getStreamer().emitMovSP(Reg, Offset);
709 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
710 getStreamer().emitPad(Offset);
712 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
714 getStreamer().emitRegSave(RegList, isVector);
716 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
717 const SmallVectorImpl<uint8_t> &Opcodes) {
718 getStreamer().emitUnwindRaw(Offset, Opcodes);
720 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
721 assert(!Vendor.empty() && "Vendor cannot be empty.");
723 if (CurrentVendor == Vendor)
726 if (!CurrentVendor.empty())
727 finishAttributeSection();
729 assert(Contents.empty() &&
730 ".ARM.attributes should be flushed before changing vendor");
731 CurrentVendor = Vendor;
734 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
735 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
737 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
739 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
741 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
743 StringRef StringValue) {
744 setAttributeItems(Attribute, IntValue, StringValue,
745 /* OverwriteExisting= */ true);
747 void ARMTargetELFStreamer::emitArch(unsigned Value) {
750 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
753 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
754 using namespace ARMBuildAttrs;
756 setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
757 if (EmittedArch == ARM::INVALID_ARCH)
758 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
760 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(EmittedArch), false);
769 setAttributeItem(ARM_ISA_use, Allowed, false);
777 setAttributeItem(ARM_ISA_use, Allowed, false);
778 setAttributeItem(THUMB_ISA_use, Allowed, false);
782 setAttributeItem(ARM_ISA_use, Allowed, false);
783 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
789 setAttributeItem(ARM_ISA_use, Allowed, false);
790 setAttributeItem(THUMB_ISA_use, Allowed, false);
791 setAttributeItem(Virtualization_use, AllowTZ, false);
795 setAttributeItem(THUMB_ISA_use, Allowed, false);
799 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
803 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
804 setAttributeItem(ARM_ISA_use, Allowed, false);
805 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
809 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
810 setAttributeItem(ARM_ISA_use, Allowed, false);
811 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
815 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
816 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
821 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
822 setAttributeItem(ARM_ISA_use, Allowed, false);
823 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
824 setAttributeItem(MPextension_use, Allowed, false);
825 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
829 setAttributeItem(ARM_ISA_use, Allowed, false);
830 setAttributeItem(THUMB_ISA_use, Allowed, false);
831 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
835 setAttributeItem(ARM_ISA_use, Allowed, false);
836 setAttributeItem(THUMB_ISA_use, Allowed, false);
837 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
841 report_fatal_error("Unknown Arch: " + Twine(Arch));
845 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
848 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
852 setAttributeItem(ARMBuildAttrs::FP_arch,
853 ARMBuildAttrs::AllowFPv2,
854 /* OverwriteExisting= */ false);
858 setAttributeItem(ARMBuildAttrs::FP_arch,
859 ARMBuildAttrs::AllowFPv3A,
860 /* OverwriteExisting= */ false);
864 setAttributeItem(ARMBuildAttrs::FP_arch,
865 ARMBuildAttrs::AllowFPv3B,
866 /* OverwriteExisting= */ false);
870 setAttributeItem(ARMBuildAttrs::FP_arch,
871 ARMBuildAttrs::AllowFPv4A,
872 /* OverwriteExisting= */ false);
876 setAttributeItem(ARMBuildAttrs::FP_arch,
877 ARMBuildAttrs::AllowFPv4B,
878 /* OverwriteExisting= */ false);
882 setAttributeItem(ARMBuildAttrs::FP_arch,
883 ARMBuildAttrs::AllowFPARMv8A,
884 /* OverwriteExisting= */ false);
887 // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
888 // uses the FP_ARMV8_D16 build attribute.
890 setAttributeItem(ARMBuildAttrs::FP_arch,
891 ARMBuildAttrs::AllowFPARMv8B,
892 /* OverwriteExisting= */ false);
896 setAttributeItem(ARMBuildAttrs::FP_arch,
897 ARMBuildAttrs::AllowFPv3A,
898 /* OverwriteExisting= */ false);
899 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
900 ARMBuildAttrs::AllowNeon,
901 /* OverwriteExisting= */ false);
904 case ARM::NEON_VFPV4:
905 setAttributeItem(ARMBuildAttrs::FP_arch,
906 ARMBuildAttrs::AllowFPv4A,
907 /* OverwriteExisting= */ false);
908 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
909 ARMBuildAttrs::AllowNeon2,
910 /* OverwriteExisting= */ false);
913 case ARM::NEON_FP_ARMV8:
914 case ARM::CRYPTO_NEON_FP_ARMV8:
915 setAttributeItem(ARMBuildAttrs::FP_arch,
916 ARMBuildAttrs::AllowFPARMv8A,
917 /* OverwriteExisting= */ false);
918 // 'Advanced_SIMD_arch' must be emitted not here, but within
919 // ARMAsmPrinter::emitAttributes(), depending on hasV8Ops() and hasV8_1a()
926 report_fatal_error("Unknown FPU: " + Twine(FPU));
930 size_t ARMTargetELFStreamer::calculateContentSize() const {
932 for (size_t i = 0; i < Contents.size(); ++i) {
933 AttributeItem item = Contents[i];
935 case AttributeItem::HiddenAttribute:
937 case AttributeItem::NumericAttribute:
938 Result += getULEB128Size(item.Tag);
939 Result += getULEB128Size(item.IntValue);
941 case AttributeItem::TextAttribute:
942 Result += getULEB128Size(item.Tag);
943 Result += item.StringValue.size() + 1; // string + '\0'
945 case AttributeItem::NumericAndTextAttributes:
946 Result += getULEB128Size(item.Tag);
947 Result += getULEB128Size(item.IntValue);
948 Result += item.StringValue.size() + 1; // string + '\0';
954 void ARMTargetELFStreamer::finishAttributeSection() {
956 // [ <section-length> "vendor-name"
957 // [ <file-tag> <size> <attribute>*
958 // | <section-tag> <size> <section-number>* 0 <attribute>*
959 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
963 if (FPU != ARM::INVALID_FPU)
964 emitFPUDefaultAttributes();
966 if (Arch != ARM::INVALID_ARCH)
967 emitArchDefaultAttributes();
969 if (Contents.empty())
972 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
974 ARMELFStreamer &Streamer = getStreamer();
976 // Switch to .ARM.attributes section
977 if (AttributeSection) {
978 Streamer.SwitchSection(AttributeSection);
980 AttributeSection = Streamer.getContext().getELFSection(
981 ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
982 Streamer.SwitchSection(AttributeSection);
985 Streamer.EmitIntValue(0x41, 1);
988 // Vendor size + Vendor name + '\0'
989 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
992 const size_t TagHeaderSize = 1 + 4;
994 const size_t ContentsSize = calculateContentSize();
996 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
997 Streamer.EmitBytes(CurrentVendor);
998 Streamer.EmitIntValue(0, 1); // '\0'
1000 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
1001 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
1003 // Size should have been accounted for already, now
1004 // emit each field as its type (ULEB or String)
1005 for (size_t i = 0; i < Contents.size(); ++i) {
1006 AttributeItem item = Contents[i];
1007 Streamer.EmitULEB128IntValue(item.Tag);
1008 switch (item.Type) {
1009 default: llvm_unreachable("Invalid attribute type");
1010 case AttributeItem::NumericAttribute:
1011 Streamer.EmitULEB128IntValue(item.IntValue);
1013 case AttributeItem::TextAttribute:
1014 Streamer.EmitBytes(item.StringValue);
1015 Streamer.EmitIntValue(0, 1); // '\0'
1017 case AttributeItem::NumericAndTextAttributes:
1018 Streamer.EmitULEB128IntValue(item.IntValue);
1019 Streamer.EmitBytes(item.StringValue);
1020 Streamer.EmitIntValue(0, 1); // '\0'
1026 FPU = ARM::INVALID_FPU;
1029 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
1030 ARMELFStreamer &Streamer = getStreamer();
1031 if (!Streamer.IsThumb)
1034 const MCSymbolData &SD = Streamer.getOrCreateSymbolData(Symbol);
1035 unsigned Type = MCELF::GetType(SD);
1036 if (Type == ELF_STT_Func || Type == ELF_STT_GnuIFunc)
1037 Streamer.EmitThumbFunc(Symbol);
1041 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
1042 getStreamer().EmitFixup(S, FK_Data_4);
1045 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
1046 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
1047 const MCSymbol &Sym = SRE->getSymbol();
1048 if (!Sym.isDefined()) {
1049 getStreamer().EmitAssignment(Symbol, Value);
1054 getStreamer().EmitThumbFunc(Symbol);
1055 getStreamer().EmitAssignment(Symbol, Value);
1058 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
1059 getStreamer().emitInst(Inst, Suffix);
1062 void ARMELFStreamer::FinishImpl() {
1063 MCTargetStreamer &TS = *getTargetStreamer();
1064 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1065 ATS.finishAttributeSection();
1067 MCELFStreamer::FinishImpl();
1070 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1074 const MCSymbol &Fn) {
1075 const MCSectionELF &FnSection =
1076 static_cast<const MCSectionELF &>(Fn.getSection());
1078 // Create the name for new section
1079 StringRef FnSecName(FnSection.getSectionName());
1080 SmallString<128> EHSecName(Prefix);
1081 if (FnSecName != ".text") {
1082 EHSecName += FnSecName;
1085 // Get .ARM.extab or .ARM.exidx section
1086 const MCSymbol *Group = FnSection.getGroup();
1088 Flags |= ELF::SHF_GROUP;
1089 const MCSectionELF *EHSection =
1090 getContext().getELFSection(EHSecName, Type, Flags, 0, Group,
1091 FnSection.getUniqueID(), nullptr, &FnSection);
1093 assert(EHSection && "Failed to get the required EH section");
1095 // Switch to .ARM.extab or .ARM.exidx section
1096 SwitchSection(EHSection);
1097 EmitCodeAlignment(4);
1100 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1101 SwitchToEHSection(".ARM.extab",
1104 SectionKind::getDataRel(),
1108 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1109 SwitchToEHSection(".ARM.exidx",
1111 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1112 SectionKind::getDataRel(),
1115 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1116 MCDataFragment *Frag = getOrCreateDataFragment();
1117 Frag->getFixups().push_back(MCFixup::Create(Frag->getContents().size(), Expr,
1121 void ARMELFStreamer::Reset() {
1124 Personality = nullptr;
1125 PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1134 UnwindOpAsm.Reset();
1137 void ARMELFStreamer::emitFnStart() {
1138 assert(FnStart == nullptr);
1139 FnStart = getContext().CreateTempSymbol();
1143 void ARMELFStreamer::emitFnEnd() {
1144 assert(FnStart && ".fnstart must precedes .fnend");
1146 // Emit unwind opcodes if there is no .handlerdata directive
1147 if (!ExTab && !CantUnwind)
1148 FlushUnwindOpcodes(true);
1150 // Emit the exception index table entry
1151 SwitchToExIdxSection(*FnStart);
1153 if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1154 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1156 const MCSymbolRefExpr *FnStartRef =
1157 MCSymbolRefExpr::Create(FnStart,
1158 MCSymbolRefExpr::VK_ARM_PREL31,
1161 EmitValue(FnStartRef, 4);
1164 EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1166 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1167 const MCSymbolRefExpr *ExTabEntryRef =
1168 MCSymbolRefExpr::Create(ExTab,
1169 MCSymbolRefExpr::VK_ARM_PREL31,
1171 EmitValue(ExTabEntryRef, 4);
1173 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1174 // the second word of exception index table entry. The size of the unwind
1175 // opcodes should always be 4 bytes.
1176 assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1177 "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1178 assert(Opcodes.size() == 4u &&
1179 "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1180 uint64_t Intval = Opcodes[0] |
1184 EmitIntValue(Intval, Opcodes.size());
1187 // Switch to the section containing FnStart
1188 SwitchSection(&FnStart->getSection());
1190 // Clean exception handling frame information
1194 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1196 // Add the R_ARM_NONE fixup at the same position
1197 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1198 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
1200 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
1201 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1203 visitUsedExpr(*PersonalityRef);
1204 MCDataFragment *DF = getOrCreateDataFragment();
1205 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
1207 MCFixup::getKindForSize(4, false)));
1210 void ARMELFStreamer::FlushPendingOffset() {
1211 if (PendingOffset != 0) {
1212 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1217 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1218 // Emit the unwind opcode to restore $sp.
1220 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1221 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1222 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1223 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1225 FlushPendingOffset();
1228 // Finalize the unwind opcode sequence
1229 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1231 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1232 // section. Thus, we don't have to create an entry in the .ARM.extab
1234 if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1237 // Switch to .ARM.extab section.
1238 SwitchToExTabSection(*FnStart);
1240 // Create .ARM.extab label for offset in .ARM.exidx
1242 ExTab = getContext().CreateTempSymbol();
1247 const MCSymbolRefExpr *PersonalityRef =
1248 MCSymbolRefExpr::Create(Personality,
1249 MCSymbolRefExpr::VK_ARM_PREL31,
1252 EmitValue(PersonalityRef, 4);
1255 // Emit unwind opcodes
1256 assert((Opcodes.size() % 4) == 0 &&
1257 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1258 for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1259 uint64_t Intval = Opcodes[I] |
1260 Opcodes[I + 1] << 8 |
1261 Opcodes[I + 2] << 16 |
1262 Opcodes[I + 3] << 24;
1263 EmitIntValue(Intval, 4);
1266 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1267 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1268 // after the unwind opcodes. The handler data consists of several 32-bit
1269 // words, and should be terminated by zero.
1271 // In case that the .handlerdata directive is not specified by the
1272 // programmer, we should emit zero to terminate the handler data.
1273 if (NoHandlerData && !Personality)
1277 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1279 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1281 UnwindOpAsm.setPersonality(Per);
1284 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1285 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1286 PersonalityIndex = Index;
1289 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1291 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1292 "the operand of .setfp directive should be either $sp or $fp");
1297 if (NewSPReg == ARM::SP)
1298 FPOffset = SPOffset + Offset;
1303 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1304 assert((Reg != ARM::SP && Reg != ARM::PC) &&
1305 "the operand of .movsp cannot be either sp or pc");
1306 assert(FPReg == ARM::SP && "current FP must be SP");
1308 FlushPendingOffset();
1311 FPOffset = SPOffset + Offset;
1313 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1314 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1317 void ARMELFStreamer::emitPad(int64_t Offset) {
1318 // Track the change of the $sp offset
1321 // To squash multiple .pad directives, we should delay the unwind opcode
1322 // until the .save, .vsave, .handlerdata, or .fnend directives.
1323 PendingOffset -= Offset;
1326 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1328 // Collect the registers in the register list
1331 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1332 for (size_t i = 0; i < RegList.size(); ++i) {
1333 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1334 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1335 unsigned Bit = (1u << Reg);
1336 if ((Mask & Bit) == 0) {
1342 // Track the change the $sp offset: For the .save directive, the
1343 // corresponding push instruction will decrease the $sp by (4 * Count).
1344 // For the .vsave directive, the corresponding vpush instruction will
1345 // decrease $sp by (8 * Count).
1346 SPOffset -= Count * (IsVector ? 8 : 4);
1349 FlushPendingOffset();
1351 UnwindOpAsm.EmitVFPRegSave(Mask);
1353 UnwindOpAsm.EmitRegSave(Mask);
1356 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1357 const SmallVectorImpl<uint8_t> &Opcodes) {
1358 FlushPendingOffset();
1359 SPOffset = SPOffset - Offset;
1360 UnwindOpAsm.EmitRaw(Opcodes);
1365 MCTargetStreamer *createARMTargetAsmStreamer(MCStreamer &S,
1366 formatted_raw_ostream &OS,
1367 MCInstPrinter *InstPrint,
1368 bool isVerboseAsm) {
1369 return new ARMTargetAsmStreamer(S, OS, *InstPrint, isVerboseAsm);
1372 MCTargetStreamer *createARMNullTargetStreamer(MCStreamer &S) {
1373 return new ARMTargetStreamer(S);
1376 MCTargetStreamer *createARMObjectTargetStreamer(MCStreamer &S,
1377 const MCSubtargetInfo &STI) {
1378 Triple TT(STI.getTargetTriple());
1379 if (TT.getObjectFormat() == Triple::ELF)
1380 return new ARMTargetELFStreamer(S);
1381 return new ARMTargetStreamer(S);
1384 MCELFStreamer *createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1385 raw_ostream &OS, MCCodeEmitter *Emitter,
1386 bool RelaxAll, bool IsThumb) {
1387 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1388 // FIXME: This should eventually end up somewhere else where more
1389 // intelligent flag decisions can be made. For now we are just maintaining
1390 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1391 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1394 S->getAssembler().setRelaxAll(true);