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 "ARMBuildAttrs.h"
17 #include "ARMArchName.h"
18 #include "ARMFPUName.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMUnwindOp.h"
21 #include "ARMUnwindOpAsm.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/MC/MCAsmBackend.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCAssembler.h"
28 #include "llvm/MC/MCCodeEmitter.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCELF.h"
31 #include "llvm/MC/MCELFStreamer.h"
32 #include "llvm/MC/MCELFSymbolFlags.h"
33 #include "llvm/MC/MCExpr.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/MC/MCInstPrinter.h"
36 #include "llvm/MC/MCObjectStreamer.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MC/MCSection.h"
39 #include "llvm/MC/MCSectionELF.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/MC/MCValue.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/raw_ostream.h"
51 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
52 assert(Index < NUM_PERSONALITY_INDEX && "Invalid personality index");
53 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
56 static const char *GetFPUName(unsigned ID) {
59 llvm_unreachable("Unknown FPU kind");
61 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
62 #include "ARMFPUName.def"
67 static const char *GetArchName(unsigned ID) {
70 llvm_unreachable("Unknown ARCH kind");
72 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
73 case ARM::ID: return NAME;
74 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
75 #include "ARMArchName.def"
80 static const char *GetArchDefaultCPUName(unsigned ID) {
83 llvm_unreachable("Unknown ARCH kind");
85 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
86 case ARM::ID: return DEFAULT_CPU_NAME;
87 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
88 #include "ARMArchName.def"
93 static unsigned GetArchDefaultCPUArch(unsigned ID) {
96 llvm_unreachable("Unknown ARCH kind");
98 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
99 case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
100 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
101 #include "ARMArchName.def"
108 class ARMELFStreamer;
110 class ARMTargetAsmStreamer : public ARMTargetStreamer {
111 formatted_raw_ostream &OS;
112 MCInstPrinter &InstPrinter;
114 virtual void emitFnStart();
115 virtual void emitFnEnd();
116 virtual void emitCantUnwind();
117 virtual void emitPersonality(const MCSymbol *Personality);
118 virtual void emitHandlerData();
119 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
120 virtual void emitPad(int64_t Offset);
121 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
124 virtual void switchVendor(StringRef Vendor);
125 virtual void emitAttribute(unsigned Attribute, unsigned Value);
126 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
127 virtual void emitArch(unsigned Arch);
128 virtual void emitFPU(unsigned FPU);
129 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
130 virtual void finishAttributeSection();
133 ARMTargetAsmStreamer(formatted_raw_ostream &OS, MCInstPrinter &InstPrinter);
136 ARMTargetAsmStreamer::ARMTargetAsmStreamer(formatted_raw_ostream &OS,
137 MCInstPrinter &InstPrinter)
138 : OS(OS), InstPrinter(InstPrinter) {}
139 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
140 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
141 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
142 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
143 OS << "\t.personality " << Personality->getName() << '\n';
145 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
146 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
149 InstPrinter.printRegName(OS, FpReg);
151 InstPrinter.printRegName(OS, SpReg);
153 OS << ", #" << Offset;
156 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
157 OS << "\t.pad\t#" << Offset << '\n';
159 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
161 assert(RegList.size() && "RegList should not be empty");
167 InstPrinter.printRegName(OS, RegList[0]);
169 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
171 InstPrinter.printRegName(OS, RegList[i]);
176 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
178 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
179 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value) << "\n";
181 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
184 default: llvm_unreachable("Unsupported Text attribute in ASM Mode");
185 case ARMBuildAttrs::CPU_name:
186 OS << "\t.cpu\t" << String.lower() << "\n";
190 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
191 OS << "\t.arch\t" << GetArchName(Arch) << "\n";
193 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
194 OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
196 void ARMTargetAsmStreamer::finishAttributeSection() {
199 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
203 OS << "\t0x" << utohexstr(Inst) << "\n";
206 class ARMTargetELFStreamer : public ARMTargetStreamer {
208 // This structure holds all attributes, accounting for
209 // their string/numeric value, so we can later emmit them
210 // in declaration order, keeping all in the same vector
211 struct AttributeItem {
219 StringRef StringValue;
221 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
222 return (LHS.Tag < RHS.Tag);
226 StringRef CurrentVendor;
229 SmallVector<AttributeItem, 64> Contents;
231 const MCSection *AttributeSection;
233 // FIXME: this should be in a more generic place, but
234 // getULEBSize() is in MCAsmInfo and will be moved to MCDwarf
235 static size_t getULEBSize(int Value) {
239 Size += sizeof(int8_t); // Is this really necessary?
244 AttributeItem *getAttributeItem(unsigned Attribute) {
245 for (size_t i = 0; i < Contents.size(); ++i)
246 if (Contents[i].Tag == Attribute)
251 void setAttributeItem(unsigned Attribute, unsigned Value,
252 bool OverwriteExisting) {
253 // Look for existing attribute item
254 if (AttributeItem *Item = getAttributeItem(Attribute)) {
255 if (!OverwriteExisting)
257 Item->IntValue = Value;
261 // Create new attribute item
262 AttributeItem Item = {
263 AttributeItem::NumericAttribute,
268 Contents.push_back(Item);
271 void setAttributeItem(unsigned Attribute, StringRef Value,
272 bool OverwriteExisting) {
273 // Look for existing attribute item
274 if (AttributeItem *Item = getAttributeItem(Attribute)) {
275 if (!OverwriteExisting)
277 Item->StringValue = Value;
281 // Create new attribute item
282 AttributeItem Item = {
283 AttributeItem::TextAttribute,
288 Contents.push_back(Item);
291 void emitArchDefaultAttributes();
292 void emitFPUDefaultAttributes();
294 ARMELFStreamer &getStreamer();
296 virtual void emitFnStart();
297 virtual void emitFnEnd();
298 virtual void emitCantUnwind();
299 virtual void emitPersonality(const MCSymbol *Personality);
300 virtual void emitHandlerData();
301 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
302 virtual void emitPad(int64_t Offset);
303 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
306 virtual void switchVendor(StringRef Vendor);
307 virtual void emitAttribute(unsigned Attribute, unsigned Value);
308 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
309 virtual void emitArch(unsigned Arch);
310 virtual void emitFPU(unsigned FPU);
311 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
312 virtual void finishAttributeSection();
314 size_t calculateContentSize() const;
317 ARMTargetELFStreamer()
318 : ARMTargetStreamer(), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
319 Arch(ARM::INVALID_ARCH), AttributeSection(0) {
323 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
324 /// the appropriate points in the object files. These symbols are defined in the
325 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
327 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
328 /// region of ARM code, Thumb code or data in a section. In practice, this
329 /// emission does not rely on explicit assembler directives but on inherent
330 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
331 /// r0, r0, r0" an instruction).
333 /// As a result this system is orthogonal to the DataRegion infrastructure used
334 /// by MachO. Beware!
335 class ARMELFStreamer : public MCELFStreamer {
337 friend class ARMTargetELFStreamer;
339 ARMELFStreamer(MCContext &Context, MCTargetStreamer *TargetStreamer,
340 MCAsmBackend &TAB, raw_ostream &OS, MCCodeEmitter *Emitter,
342 : MCELFStreamer(Context, TargetStreamer, TAB, OS, Emitter),
343 IsThumb(IsThumb), MappingSymbolCounter(0), LastEMS(EMS_None) {
349 virtual void FinishImpl();
351 // ARM exception handling directives
354 void emitCantUnwind();
355 void emitPersonality(const MCSymbol *Per);
356 void emitHandlerData();
357 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
358 void emitPad(int64_t Offset);
359 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
361 virtual void ChangeSection(const MCSection *Section,
362 const MCExpr *Subsection) {
363 // We have to keep track of the mapping symbol state of any sections we
364 // use. Each one should start off as EMS_None, which is provided as the
365 // default constructor by DenseMap::lookup.
366 LastMappingSymbols[getPreviousSection().first] = LastEMS;
367 LastEMS = LastMappingSymbols.lookup(Section);
369 MCELFStreamer::ChangeSection(Section, Subsection);
372 /// This function is the one used to emit instruction data into the ELF
373 /// streamer. We override it to add the appropriate mapping symbol if
375 virtual void EmitInstruction(const MCInst& Inst) {
377 EmitThumbMappingSymbol();
379 EmitARMMappingSymbol();
381 MCELFStreamer::EmitInstruction(Inst);
384 virtual void emitInst(uint32_t Inst, char Suffix) {
387 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
394 EmitARMMappingSymbol();
395 for (unsigned II = 0, IE = Size; II != IE; II++) {
396 const unsigned I = LittleEndian ? (Size - II - 1) : II;
397 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
403 Size = (Suffix == 'n' ? 2 : 4);
406 EmitThumbMappingSymbol();
407 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
408 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
409 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
410 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
411 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
416 llvm_unreachable("Invalid Suffix");
419 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
422 /// This is one of the functions used to emit data into an ELF section, so the
423 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
425 virtual void EmitBytes(StringRef Data) {
426 EmitDataMappingSymbol();
427 MCELFStreamer::EmitBytes(Data);
430 /// This is one of the functions used to emit data into an ELF section, so the
431 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
433 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {
434 EmitDataMappingSymbol();
435 MCELFStreamer::EmitValueImpl(Value, Size);
438 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {
439 MCELFStreamer::EmitAssemblerFlag(Flag);
442 case MCAF_SyntaxUnified:
443 return; // no-op here.
446 return; // Change to Thumb mode
449 return; // Change to ARM mode
452 case MCAF_SubsectionsViaSymbols:
458 enum ElfMappingSymbol {
465 void EmitDataMappingSymbol() {
466 if (LastEMS == EMS_Data) return;
467 EmitMappingSymbol("$d");
471 void EmitThumbMappingSymbol() {
472 if (LastEMS == EMS_Thumb) return;
473 EmitMappingSymbol("$t");
477 void EmitARMMappingSymbol() {
478 if (LastEMS == EMS_ARM) return;
479 EmitMappingSymbol("$a");
483 void EmitMappingSymbol(StringRef Name) {
484 MCSymbol *Start = getContext().CreateTempSymbol();
488 getContext().GetOrCreateSymbol(Name + "." +
489 Twine(MappingSymbolCounter++));
491 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
492 MCELF::SetType(SD, ELF::STT_NOTYPE);
493 MCELF::SetBinding(SD, ELF::STB_LOCAL);
494 SD.setExternal(false);
495 AssignSection(Symbol, getCurrentSection().first);
497 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
498 Symbol->setVariableValue(Value);
501 void EmitThumbFunc(MCSymbol *Func) {
502 // FIXME: Anything needed here to flag the function as thumb?
504 getAssembler().setIsThumbFunc(Func);
506 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
507 SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
510 // Helper functions for ARM exception handling directives
513 void EmitPersonalityFixup(StringRef Name);
514 void FlushPendingOffset();
515 void FlushUnwindOpcodes(bool NoHandlerData);
517 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
518 SectionKind Kind, const MCSymbol &Fn);
519 void SwitchToExTabSection(const MCSymbol &FnStart);
520 void SwitchToExIdxSection(const MCSymbol &FnStart);
523 int64_t MappingSymbolCounter;
525 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
526 ElfMappingSymbol LastEMS;
528 // ARM Exception Handling Frame Information
531 const MCSymbol *Personality;
532 unsigned PersonalityIndex;
533 unsigned FPReg; // Frame pointer register
534 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
535 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
536 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
539 SmallVector<uint8_t, 64> Opcodes;
540 UnwindOpcodeAssembler UnwindOpAsm;
542 } // end anonymous namespace
544 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
545 ARMELFStreamer *S = static_cast<ARMELFStreamer *>(Streamer);
549 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
550 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
551 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
552 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
553 getStreamer().emitPersonality(Personality);
555 void ARMTargetELFStreamer::emitHandlerData() {
556 getStreamer().emitHandlerData();
558 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
560 getStreamer().emitSetFP(FpReg, SpReg, Offset);
562 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
563 getStreamer().emitPad(Offset);
565 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
567 getStreamer().emitRegSave(RegList, isVector);
569 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
570 assert(!Vendor.empty() && "Vendor cannot be empty.");
572 if (CurrentVendor == Vendor)
575 if (!CurrentVendor.empty())
576 finishAttributeSection();
578 assert(Contents.empty() &&
579 ".ARM.attributes should be flushed before changing vendor");
580 CurrentVendor = Vendor;
583 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
584 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
586 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
588 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
590 void ARMTargetELFStreamer::emitArch(unsigned Value) {
593 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
594 using namespace ARMBuildAttrs;
595 setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
596 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
605 setAttributeItem(ARM_ISA_use, Allowed, false);
613 setAttributeItem(ARM_ISA_use, Allowed, false);
614 setAttributeItem(THUMB_ISA_use, Allowed, false);
618 setAttributeItem(ARM_ISA_use, Allowed, false);
619 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
624 setAttributeItem(ARM_ISA_use, Allowed, false);
625 setAttributeItem(THUMB_ISA_use, Allowed, false);
626 setAttributeItem(Virtualization_use, AllowTZ, false);
630 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
631 setAttributeItem(THUMB_ISA_use, Allowed, false);
635 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
639 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
640 setAttributeItem(ARM_ISA_use, Allowed, false);
641 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
645 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
646 setAttributeItem(ARM_ISA_use, Allowed, false);
647 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
651 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
652 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
656 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
657 setAttributeItem(ARM_ISA_use, Allowed, false);
658 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
659 setAttributeItem(MPextension_use, Allowed, false);
660 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
664 setAttributeItem(ARM_ISA_use, Allowed, false);
665 setAttributeItem(THUMB_ISA_use, Allowed, false);
666 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
670 setAttributeItem(ARM_ISA_use, Allowed, false);
671 setAttributeItem(THUMB_ISA_use, Allowed, false);
672 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
676 report_fatal_error("Unknown Arch: " + Twine(Arch));
680 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
683 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
687 setAttributeItem(ARMBuildAttrs::FP_arch,
688 ARMBuildAttrs::AllowFPv2,
689 /* OverwriteExisting= */ false);
693 setAttributeItem(ARMBuildAttrs::FP_arch,
694 ARMBuildAttrs::AllowFPv3A,
695 /* OverwriteExisting= */ false);
699 setAttributeItem(ARMBuildAttrs::FP_arch,
700 ARMBuildAttrs::AllowFPv3B,
701 /* OverwriteExisting= */ false);
705 setAttributeItem(ARMBuildAttrs::FP_arch,
706 ARMBuildAttrs::AllowFPv4A,
707 /* OverwriteExisting= */ false);
711 setAttributeItem(ARMBuildAttrs::FP_arch,
712 ARMBuildAttrs::AllowFPv4B,
713 /* OverwriteExisting= */ false);
717 setAttributeItem(ARMBuildAttrs::FP_arch,
718 ARMBuildAttrs::AllowFPARMv8A,
719 /* OverwriteExisting= */ false);
723 setAttributeItem(ARMBuildAttrs::FP_arch,
724 ARMBuildAttrs::AllowFPv3A,
725 /* OverwriteExisting= */ false);
726 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
727 ARMBuildAttrs::AllowNeon,
728 /* OverwriteExisting= */ false);
731 case ARM::NEON_VFPV4:
732 setAttributeItem(ARMBuildAttrs::FP_arch,
733 ARMBuildAttrs::AllowFPv4A,
734 /* OverwriteExisting= */ false);
735 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
736 ARMBuildAttrs::AllowNeon2,
737 /* OverwriteExisting= */ false);
740 case ARM::NEON_FP_ARMV8:
741 case ARM::CRYPTO_NEON_FP_ARMV8:
742 setAttributeItem(ARMBuildAttrs::FP_arch,
743 ARMBuildAttrs::AllowFPARMv8A,
744 /* OverwriteExisting= */ false);
745 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
746 ARMBuildAttrs::AllowNeonARMv8,
747 /* OverwriteExisting= */ false);
754 report_fatal_error("Unknown FPU: " + Twine(FPU));
758 size_t ARMTargetELFStreamer::calculateContentSize() const {
760 for (size_t i = 0; i < Contents.size(); ++i) {
761 AttributeItem item = Contents[i];
763 case AttributeItem::HiddenAttribute:
765 case AttributeItem::NumericAttribute:
766 Result += getULEBSize(item.Tag);
767 Result += getULEBSize(item.IntValue);
769 case AttributeItem::TextAttribute:
770 Result += getULEBSize(item.Tag);
771 Result += item.StringValue.size() + 1; // string + '\0'
777 void ARMTargetELFStreamer::finishAttributeSection() {
779 // [ <section-length> "vendor-name"
780 // [ <file-tag> <size> <attribute>*
781 // | <section-tag> <size> <section-number>* 0 <attribute>*
782 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
786 if (FPU != ARM::INVALID_FPU)
787 emitFPUDefaultAttributes();
789 if (Arch != ARM::INVALID_ARCH)
790 emitArchDefaultAttributes();
792 if (Contents.empty())
795 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
797 ARMELFStreamer &Streamer = getStreamer();
799 // Switch to .ARM.attributes section
800 if (AttributeSection) {
801 Streamer.SwitchSection(AttributeSection);
804 Streamer.getContext().getELFSection(".ARM.attributes",
805 ELF::SHT_ARM_ATTRIBUTES,
807 SectionKind::getMetadata());
808 Streamer.SwitchSection(AttributeSection);
811 Streamer.EmitIntValue(0x41, 1);
814 // Vendor size + Vendor name + '\0'
815 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
818 const size_t TagHeaderSize = 1 + 4;
820 const size_t ContentsSize = calculateContentSize();
822 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
823 Streamer.EmitBytes(CurrentVendor);
824 Streamer.EmitIntValue(0, 1); // '\0'
826 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
827 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
829 // Size should have been accounted for already, now
830 // emit each field as its type (ULEB or String)
831 for (size_t i = 0; i < Contents.size(); ++i) {
832 AttributeItem item = Contents[i];
833 Streamer.EmitULEB128IntValue(item.Tag);
835 default: llvm_unreachable("Invalid attribute type");
836 case AttributeItem::NumericAttribute:
837 Streamer.EmitULEB128IntValue(item.IntValue);
839 case AttributeItem::TextAttribute:
840 Streamer.EmitBytes(item.StringValue.upper());
841 Streamer.EmitIntValue(0, 1); // '\0'
847 FPU = ARM::INVALID_FPU;
849 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
850 getStreamer().emitInst(Inst, Suffix);
853 void ARMELFStreamer::FinishImpl() {
854 MCTargetStreamer &TS = getTargetStreamer();
855 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
856 ATS.finishAttributeSection();
858 MCELFStreamer::FinishImpl();
861 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
865 const MCSymbol &Fn) {
866 const MCSectionELF &FnSection =
867 static_cast<const MCSectionELF &>(Fn.getSection());
869 // Create the name for new section
870 StringRef FnSecName(FnSection.getSectionName());
871 SmallString<128> EHSecName(Prefix);
872 if (FnSecName != ".text") {
873 EHSecName += FnSecName;
876 // Get .ARM.extab or .ARM.exidx section
877 const MCSectionELF *EHSection = NULL;
878 if (const MCSymbol *Group = FnSection.getGroup()) {
879 EHSection = getContext().getELFSection(
880 EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
881 FnSection.getEntrySize(), Group->getName());
883 EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
885 assert(EHSection && "Failed to get the required EH section");
887 // Switch to .ARM.extab or .ARM.exidx section
888 SwitchSection(EHSection);
889 EmitCodeAlignment(4, 0);
892 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
893 SwitchToEHSection(".ARM.extab",
896 SectionKind::getDataRel(),
900 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
901 SwitchToEHSection(".ARM.exidx",
903 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
904 SectionKind::getDataRel(),
908 void ARMELFStreamer::Reset() {
912 PersonalityIndex = NUM_PERSONALITY_INDEX;
924 void ARMELFStreamer::emitFnStart() {
925 assert(FnStart == 0);
926 FnStart = getContext().CreateTempSymbol();
930 void ARMELFStreamer::emitFnEnd() {
931 assert(FnStart && ".fnstart must preceeds .fnend");
933 // Emit unwind opcodes if there is no .handlerdata directive
934 if (!ExTab && !CantUnwind)
935 FlushUnwindOpcodes(true);
937 // Emit the exception index table entry
938 SwitchToExIdxSection(*FnStart);
940 if (PersonalityIndex < NUM_PERSONALITY_INDEX)
941 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
943 const MCSymbolRefExpr *FnStartRef =
944 MCSymbolRefExpr::Create(FnStart,
945 MCSymbolRefExpr::VK_ARM_PREL31,
948 EmitValue(FnStartRef, 4);
951 EmitIntValue(EXIDX_CANTUNWIND, 4);
953 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
954 const MCSymbolRefExpr *ExTabEntryRef =
955 MCSymbolRefExpr::Create(ExTab,
956 MCSymbolRefExpr::VK_ARM_PREL31,
958 EmitValue(ExTabEntryRef, 4);
960 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
961 // the second word of exception index table entry. The size of the unwind
962 // opcodes should always be 4 bytes.
963 assert(PersonalityIndex == AEABI_UNWIND_CPP_PR0 &&
964 "Compact model must use __aeabi_cpp_unwind_pr0 as personality");
965 assert(Opcodes.size() == 4u &&
966 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be equal to 4");
967 EmitBytes(StringRef(reinterpret_cast<const char*>(Opcodes.data()),
971 // Switch to the section containing FnStart
972 SwitchSection(&FnStart->getSection());
974 // Clean exception handling frame information
978 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
980 // Add the R_ARM_NONE fixup at the same position
981 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
982 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
984 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
985 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
987 AddValueSymbols(PersonalityRef);
988 MCDataFragment *DF = getOrCreateDataFragment();
989 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
991 MCFixup::getKindForSize(4, false)));
994 void ARMELFStreamer::FlushPendingOffset() {
995 if (PendingOffset != 0) {
996 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1001 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1002 // Emit the unwind opcode to restore $sp.
1004 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1005 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1006 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1007 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1009 FlushPendingOffset();
1012 // Finalize the unwind opcode sequence
1013 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1015 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1016 // section. Thus, we don't have to create an entry in the .ARM.extab
1018 if (NoHandlerData && PersonalityIndex == AEABI_UNWIND_CPP_PR0)
1021 // Switch to .ARM.extab section.
1022 SwitchToExTabSection(*FnStart);
1024 // Create .ARM.extab label for offset in .ARM.exidx
1026 ExTab = getContext().CreateTempSymbol();
1031 const MCSymbolRefExpr *PersonalityRef =
1032 MCSymbolRefExpr::Create(Personality,
1033 MCSymbolRefExpr::VK_ARM_PREL31,
1036 EmitValue(PersonalityRef, 4);
1039 // Emit unwind opcodes
1040 EmitBytes(StringRef(reinterpret_cast<const char *>(Opcodes.data()),
1043 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1044 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1045 // after the unwind opcodes. The handler data consists of several 32-bit
1046 // words, and should be terminated by zero.
1048 // In case that the .handlerdata directive is not specified by the
1049 // programmer, we should emit zero to terminate the handler data.
1050 if (NoHandlerData && !Personality)
1054 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1056 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1058 UnwindOpAsm.setPersonality(Per);
1061 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1063 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1064 "the operand of .setfp directive should be either $sp or $fp");
1069 if (NewSPReg == ARM::SP)
1070 FPOffset = SPOffset + Offset;
1075 void ARMELFStreamer::emitPad(int64_t Offset) {
1076 // Track the change of the $sp offset
1079 // To squash multiple .pad directives, we should delay the unwind opcode
1080 // until the .save, .vsave, .handlerdata, or .fnend directives.
1081 PendingOffset -= Offset;
1084 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1086 // Collect the registers in the register list
1089 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1090 for (size_t i = 0; i < RegList.size(); ++i) {
1091 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1092 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1093 unsigned Bit = (1u << Reg);
1094 if ((Mask & Bit) == 0) {
1100 // Track the change the $sp offset: For the .save directive, the
1101 // corresponding push instruction will decrease the $sp by (4 * Count).
1102 // For the .vsave directive, the corresponding vpush instruction will
1103 // decrease $sp by (8 * Count).
1104 SPOffset -= Count * (IsVector ? 8 : 4);
1107 FlushPendingOffset();
1109 UnwindOpAsm.EmitVFPRegSave(Mask);
1111 UnwindOpAsm.EmitRegSave(Mask);
1116 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
1117 bool isVerboseAsm, bool useLoc, bool useCFI,
1118 bool useDwarfDirectory,
1119 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1120 MCAsmBackend *TAB, bool ShowInst) {
1121 ARMTargetAsmStreamer *S = new ARMTargetAsmStreamer(OS, *InstPrint);
1123 return llvm::createAsmStreamer(Ctx, S, OS, isVerboseAsm, useLoc, useCFI,
1124 useDwarfDirectory, InstPrint, CE, TAB,
1128 MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1129 raw_ostream &OS, MCCodeEmitter *Emitter,
1130 bool RelaxAll, bool NoExecStack,
1132 ARMTargetELFStreamer *TS = new ARMTargetELFStreamer();
1134 new ARMELFStreamer(Context, TS, TAB, OS, Emitter, IsThumb);
1135 // FIXME: This should eventually end up somewhere else where more
1136 // intelligent flag decisions can be made. For now we are just maintaining
1137 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1138 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1141 S->getAssembler().setRelaxAll(true);
1143 S->getAssembler().setNoExecStack(true);